blob: 1aa46d74f723cea804c467f46c22f5065d215141 [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>
Christopher Faulet31af49d2015-06-09 17:29:50 +020046
Willy Tarreaub2551052020-06-09 09:07:15 +020047#include <haproxy/api.h>
48#include <haproxy/arg.h>
49#include <haproxy/base64.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020050#include <haproxy/channel.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020051#include <haproxy/chunk.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020052#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020053#include <haproxy/connection.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020054#include <haproxy/dynbuf.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020055#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020056#include <haproxy/fd.h>
57#include <haproxy/freq_ctr.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020058#include <haproxy/frontend.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020059#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020060#include <haproxy/http_rules.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020061#include <haproxy/log.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020062#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020063#include <haproxy/pattern-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/proto_tcp.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020065#include <haproxy/proxy.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020066#include <haproxy/server.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020067#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020068#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020069#include <haproxy/ssl_crtlist.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020070#include <haproxy/ssl_sock.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020071#include <haproxy/ssl_utils.h>
Amaury Denoyelle9963fa72020-11-03 17:10:00 +010072#include <haproxy/stats.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020073#include <haproxy/stream-t.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020074#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020075#include <haproxy/task.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020076#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020077#include <haproxy/time.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020078#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020079#include <haproxy/vars.h>
Frédéric Lécailleec216522020-11-23 14:33:30 +010080#include <haproxy/xprt_quic.h>
Tim Duesterhusd5fc8fc2021-09-11 17:51:13 +020081#include <haproxy/xxhash.h>
Emeric Brun46591952012-05-18 15:47:34 +020082
Emeric Brun46591952012-05-18 15:47:34 +020083
Willy Tarreau9356dac2019-05-10 09:22:53 +020084/* ***** READ THIS before adding code here! *****
85 *
86 * Due to API incompatibilities between multiple OpenSSL versions and their
87 * derivatives, it's often tempting to add macros to (re-)define certain
88 * symbols. Please do not do this here, and do it in common/openssl-compat.h
89 * exclusively so that the whole code consistently uses the same macros.
90 *
91 * Whenever possible if a macro is missing in certain versions, it's better
92 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
93 */
94
Emeric Brunece0c332017-12-06 13:51:49 +010095int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +020096
William Lallemande0f3fd52020-02-25 14:53:06 +010097static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
98
William Lallemand7fd8b452020-05-07 15:20:43 +020099struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100100#ifdef LISTEN_DEFAULT_CIPHERS
101 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
102#endif
103#ifdef CONNECT_DEFAULT_CIPHERS
104 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
105#endif
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +0500106#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200107 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200108 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
109#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100110 .listen_default_ssloptions = BC_SSL_O_NONE,
111 .connect_default_ssloptions = SRV_SSL_O_NONE,
112
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200113 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
114 .listen_default_sslmethods.min = CONF_TLSV_NONE,
115 .listen_default_sslmethods.max = CONF_TLSV_NONE,
116 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
117 .connect_default_sslmethods.min = CONF_TLSV_NONE,
118 .connect_default_sslmethods.max = CONF_TLSV_NONE,
119
Willy Tarreauef934602016-12-22 23:12:01 +0100120#ifdef DEFAULT_SSL_MAX_RECORD
121 .max_record = DEFAULT_SSL_MAX_RECORD,
122#endif
123 .default_dh_param = SSL_DEFAULT_DH_PARAM,
124 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Marcin Deranek310a2602021-07-13 19:04:24 +0200125 .capture_buffer_size = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100126 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200127 .extra_files_noext = 0,
William Lallemand722180a2021-06-09 16:46:12 +0200128#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200129 .keylog = 0
130#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100131};
132
Olivier Houcharda8955d52019-04-07 22:00:38 +0200133static BIO_METHOD *ha_meth;
134
Olivier Houchard66ab4982019-02-26 18:37:15 +0100135DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
136
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100137DECLARE_STATIC_POOL(ssl_sock_client_sni_pool, "ssl_sock_client_sni_pool", TLSEXT_MAXLEN_host_name + 1);
138
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100139/* ssl stats module */
140enum {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100141 SSL_ST_SESS,
142 SSL_ST_REUSED_SESS,
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100143 SSL_ST_FAILED_HANDSHAKE,
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100144
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100145 SSL_ST_STATS_COUNT /* must be the last member of the enum */
146};
147
148static struct name_desc ssl_stats[] = {
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100149 [SSL_ST_SESS] = { .name = "ssl_sess",
150 .desc = "Total number of ssl sessions established" },
151 [SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
152 .desc = "Total number of ssl sessions reused" },
153 [SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
154 .desc = "Total number of failed handshake" },
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100155};
156
157static struct ssl_counters {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100158 long long sess;
159 long long reused_sess;
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100160 long long failed_handshake;
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100161} ssl_counters;
162
163static void ssl_fill_stats(void *data, struct field *stats)
164{
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100165 struct ssl_counters *counters = data;
166
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100167 stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
168 stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
169 stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100170}
171
172static struct stats_module ssl_stats_module = {
173 .name = "ssl",
174 .fill_stats = ssl_fill_stats,
175 .stats = ssl_stats,
176 .stats_count = SSL_ST_STATS_COUNT,
177 .counters = &ssl_counters,
178 .counters_size = sizeof(ssl_counters),
179 .domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
180 .clearable = 1,
181};
182
183INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
184
Willy Tarreau691d5032021-01-20 14:55:01 +0100185/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100186struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
Olivier Houchard000694c2019-05-23 14:45:12 +0200187static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200188
Olivier Houcharda8955d52019-04-07 22:00:38 +0200189/* Methods to implement OpenSSL BIO */
190static int ha_ssl_write(BIO *h, const char *buf, int num)
191{
192 struct buffer tmpbuf;
193 struct ssl_sock_ctx *ctx;
194 int ret;
195
196 ctx = BIO_get_data(h);
197 tmpbuf.size = num;
198 tmpbuf.area = (void *)(uintptr_t)buf;
199 tmpbuf.data = num;
200 tmpbuf.head = 0;
201 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200202 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200203 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200204 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200205 } else if (ret == 0)
206 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200207 return ret;
208}
209
210static int ha_ssl_gets(BIO *h, char *buf, int size)
211{
212
213 return 0;
214}
215
216static int ha_ssl_puts(BIO *h, const char *str)
217{
218
219 return ha_ssl_write(h, str, strlen(str));
220}
221
222static int ha_ssl_read(BIO *h, char *buf, int size)
223{
224 struct buffer tmpbuf;
225 struct ssl_sock_ctx *ctx;
226 int ret;
227
228 ctx = BIO_get_data(h);
229 tmpbuf.size = size;
230 tmpbuf.area = buf;
231 tmpbuf.data = 0;
232 tmpbuf.head = 0;
233 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200234 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200235 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200236 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200237 } else if (ret == 0)
238 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200239
240 return ret;
241}
242
243static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
244{
245 int ret = 0;
246 switch (cmd) {
247 case BIO_CTRL_DUP:
248 case BIO_CTRL_FLUSH:
249 ret = 1;
250 break;
251 }
252 return ret;
253}
254
255static int ha_ssl_new(BIO *h)
256{
257 BIO_set_init(h, 1);
258 BIO_set_data(h, NULL);
259 BIO_clear_flags(h, ~0);
260 return 1;
261}
262
263static int ha_ssl_free(BIO *data)
264{
265
266 return 1;
267}
268
269
Willy Tarreau5db847a2019-05-09 14:13:35 +0200270#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100271
Emeric Brun821bb9b2017-06-15 16:37:39 +0200272static HA_RWLOCK_T *ssl_rwlocks;
273
274
275unsigned long ssl_id_function(void)
276{
277 return (unsigned long)tid;
278}
279
280void ssl_locking_function(int mode, int n, const char * file, int line)
281{
282 if (mode & CRYPTO_LOCK) {
283 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100284 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200285 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100286 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200287 }
288 else {
289 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100290 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200291 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100292 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200293 }
294}
295
296static int ssl_locking_init(void)
297{
298 int i;
299
300 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
301 if (!ssl_rwlocks)
302 return -1;
303
304 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100305 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200306
307 CRYPTO_set_id_callback(ssl_id_function);
308 CRYPTO_set_locking_callback(ssl_locking_function);
309
310 return 0;
311}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100312
Emeric Brun821bb9b2017-06-15 16:37:39 +0200313#endif
314
Willy Tarreauaf613e82020-06-05 08:40:51 +0200315__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200316
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100317
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200318
319/* mimic what X509_STORE_load_locations do with store_ctx */
320static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
321{
Remi Tricot-Le Bretond75b99e2021-05-17 11:45:55 +0200322 X509_STORE *store = NULL;
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +0100323 struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
324 if (ca_e)
325 store = ca_e->ca_store;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200326 if (store_ctx && store) {
327 int i;
328 X509_OBJECT *obj;
329 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
330 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
331 obj = sk_X509_OBJECT_value(objs, i);
332 switch (X509_OBJECT_get_type(obj)) {
333 case X509_LU_X509:
334 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
335 break;
336 case X509_LU_CRL:
337 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
338 break;
339 default:
340 break;
341 }
342 }
343 return 1;
344 }
345 return 0;
346}
347
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500348/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200349static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
350{
351 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
352 return ssl_set_cert_crl_file(store_ctx, path);
353}
354
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200355/*
356 Extract CA_list from CA_file already in tree.
357 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
358 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
359*/
360static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
361{
362 struct ebmb_node *eb;
363 struct cafile_entry *ca_e;
364
365 eb = ebst_lookup(&cafile_tree, path);
366 if (!eb)
367 return NULL;
368 ca_e = ebmb_entry(eb, struct cafile_entry, node);
369
370 if (ca_e->ca_list == NULL) {
371 int i;
372 unsigned long key;
373 struct eb_root ca_name_tree = EB_ROOT;
374 struct eb64_node *node, *back;
375 struct {
376 struct eb64_node node;
377 X509_NAME *xname;
378 } *ca_name;
379 STACK_OF(X509_OBJECT) *objs;
380 STACK_OF(X509_NAME) *skn;
381 X509 *x;
382 X509_NAME *xn;
383
384 skn = sk_X509_NAME_new_null();
385 /* take x509 from cafile_tree */
386 objs = X509_STORE_get0_objects(ca_e->ca_store);
387 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
388 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
389 if (!x)
390 continue;
391 xn = X509_get_subject_name(x);
392 if (!xn)
393 continue;
394 /* Check for duplicates. */
395 key = X509_NAME_hash(xn);
396 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
397 node && ca_name == NULL;
398 node = eb64_next(node)) {
399 ca_name = container_of(node, typeof(*ca_name), node);
400 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
401 ca_name = NULL;
402 }
403 /* find a duplicate */
404 if (ca_name)
405 continue;
406 ca_name = calloc(1, sizeof *ca_name);
407 xn = X509_NAME_dup(xn);
408 if (!ca_name ||
409 !xn ||
410 !sk_X509_NAME_push(skn, xn)) {
411 free(ca_name);
412 X509_NAME_free(xn);
413 sk_X509_NAME_pop_free(skn, X509_NAME_free);
414 sk_X509_NAME_free(skn);
415 skn = NULL;
416 break;
417 }
418 ca_name->node.key = key;
419 ca_name->xname = xn;
420 eb64_insert(&ca_name_tree, &ca_name->node);
421 }
422 ca_e->ca_list = skn;
423 /* remove temporary ca_name tree */
424 node = eb64_first(&ca_name_tree);
425 while (node) {
426 ca_name = container_of(node, typeof(*ca_name), node);
427 back = eb64_next(node);
428 eb64_delete(node);
429 free(ca_name);
430 node = back;
431 }
432 }
433 return ca_e->ca_list;
434}
435
Willy Tarreauff882702021-04-10 17:23:00 +0200436struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200437int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100438int ssl_app_data_index = -1;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +0100439#ifdef USE_QUIC
440int ssl_qc_app_data_index = -1;
441#endif /* USE_QUIC */
Willy Tarreauef934602016-12-22 23:12:01 +0100442
William Lallemand722180a2021-06-09 16:46:12 +0200443#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200444int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200445struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
446struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200447#endif
448
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +0200449int ssl_client_crt_ref_index = -1;
450
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100451/* Used to store the client's SNI in case of ClientHello callback error */
452int ssl_client_sni_index = -1;
453
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200454#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
455struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
456#endif
457
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200458#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200459unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000460struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
461struct ssl_engine_list {
462 struct list list;
463 ENGINE *e;
464};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200465#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000466
Remi Gacogne8de54152014-07-15 11:36:40 +0200467#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200468static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200469static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200470static DH *local_dh_1024 = NULL;
471static DH *local_dh_2048 = NULL;
472static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100473static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200474#endif /* OPENSSL_NO_DH */
475
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100476#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200477/* X509V3 Extensions that will be added on generated certificates */
478#define X509V3_EXT_SIZE 5
479static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
480 "basicConstraints",
481 "nsComment",
482 "subjectKeyIdentifier",
483 "authorityKeyIdentifier",
484 "keyUsage",
485};
486static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
487 "CA:FALSE",
488 "\"OpenSSL Generated Certificate\"",
489 "hash",
490 "keyid,issuer:always",
491 "nonRepudiation,digitalSignature,keyEncipherment"
492};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200493/* LRU cache to store generated certificate */
494static struct lru64_head *ssl_ctx_lru_tree = NULL;
495static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200496static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100497__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200498
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200499#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
500
yanbzhube2774d2015-12-10 15:07:30 -0500501/* The order here matters for picking a default context,
502 * keep the most common keytype at the bottom of the list
503 */
504const char *SSL_SOCK_KEYTYPE_NAMES[] = {
505 "dsa",
506 "ecdsa",
507 "rsa"
508};
yanbzhube2774d2015-12-10 15:07:30 -0500509
William Lallemandc3cd35f2017-11-28 11:04:43 +0100510static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100511static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
512
Dragan Dosen9ac98092020-05-11 15:51:45 +0200513/* Dedicated callback functions for heartbeat and clienthello.
514 */
515#ifdef TLS1_RT_HEARTBEAT
516static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
517 int content_type, const void *buf, size_t len,
518 SSL *ssl);
519#endif
520static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
521 int content_type, const void *buf, size_t len,
522 SSL *ssl);
523
William Lallemand722180a2021-06-09 16:46:12 +0200524#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200525static void ssl_init_keylog(struct connection *conn, int write_p, int version,
526 int content_type, const void *buf, size_t len,
527 SSL *ssl);
528#endif
529
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200530/* List head of all registered SSL/TLS protocol message callbacks. */
531struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
532
533/* Registers the function <func> in order to be called on SSL/TLS protocol
534 * message processing. It will return 0 if the function <func> is not set
535 * or if it fails to allocate memory.
536 */
537int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
538{
539 struct ssl_sock_msg_callback *cbk;
540
541 if (!func)
542 return 0;
543
544 cbk = calloc(1, sizeof(*cbk));
545 if (!cbk) {
546 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
547 return 0;
548 }
549
550 cbk->func = func;
551
Willy Tarreau2b718102021-04-21 07:32:39 +0200552 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200553
554 return 1;
555}
556
Dragan Dosen9ac98092020-05-11 15:51:45 +0200557/* Used to register dedicated SSL/TLS protocol message callbacks.
558 */
559static int ssl_sock_register_msg_callbacks(void)
560{
561#ifdef TLS1_RT_HEARTBEAT
562 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
563 return ERR_ABORT;
564#endif
Marcin Deranek310a2602021-07-13 19:04:24 +0200565 if (global_ssl.capture_buffer_size > 0) {
Dragan Dosen9ac98092020-05-11 15:51:45 +0200566 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
567 return ERR_ABORT;
568 }
William Lallemand722180a2021-06-09 16:46:12 +0200569#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200570 if (global_ssl.keylog > 0) {
571 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
572 return ERR_ABORT;
573 }
574#endif
575
Christopher Fauletfc633b62020-11-06 15:24:23 +0100576 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200577}
578
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200579/* Used to free all SSL/TLS protocol message callbacks that were
580 * registered by using ssl_sock_register_msg_callback().
581 */
582static void ssl_sock_unregister_msg_callbacks(void)
583{
584 struct ssl_sock_msg_callback *cbk, *cbkback;
585
586 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200587 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200588 free(cbk);
589 }
590}
591
Dragan Doseneb607fe2020-05-11 17:17:06 +0200592SSL *ssl_sock_get_ssl_object(struct connection *conn)
593{
Willy Tarreau1057bee2021-10-06 11:38:44 +0200594 if (!conn_is_ssl(conn))
Dragan Doseneb607fe2020-05-11 17:17:06 +0200595 return NULL;
596
597 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
598}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100599/*
600 * This function gives the detail of the SSL error. It is used only
601 * if the debug mode and the verbose mode are activated. It dump all
602 * the SSL error until the stack was empty.
603 */
604static forceinline void ssl_sock_dump_errors(struct connection *conn)
605{
606 unsigned long ret;
607
608 if (unlikely(global.mode & MODE_DEBUG)) {
609 while(1) {
610 ret = ERR_get_error();
611 if (ret == 0)
612 return;
Willy Tarreau566cebc2021-03-02 19:32:39 +0100613 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
614 conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100615 ERR_func_error_string(ret), ERR_reason_error_string(ret));
616 }
617 }
618}
619
yanbzhube2774d2015-12-10 15:07:30 -0500620
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200621#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200622int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000623{
624 int err_code = ERR_ABORT;
625 ENGINE *engine;
626 struct ssl_engine_list *el;
627
628 /* grab the structural reference to the engine */
629 engine = ENGINE_by_id(engine_id);
630 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100631 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000632 goto fail_get;
633 }
634
635 if (!ENGINE_init(engine)) {
636 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100637 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000638 goto fail_init;
639 }
640
641 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100642 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000643 goto fail_set_method;
644 }
645
646 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200647 if (!el)
648 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000649 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200650 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100651 nb_engines++;
652 if (global_ssl.async)
653 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000654 return 0;
655
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200656fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000657fail_set_method:
658 /* release the functional reference from ENGINE_init() */
659 ENGINE_finish(engine);
660
661fail_init:
662 /* release the structural reference from ENGINE_by_id() */
663 ENGINE_free(engine);
664
665fail_get:
666 return err_code;
667}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200668#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000669
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500670#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200671/*
672 * openssl async fd handler
673 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200674void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000675{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200676 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000677
Emeric Brun3854e012017-05-17 20:42:48 +0200678 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000679 * to poll this fd until it is requested
680 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000681 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000682 fd_cant_recv(fd);
683
684 /* crypto engine is available, let's notify the associated
685 * connection that it can pursue its processing.
686 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200687 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000688}
689
Emeric Brun3854e012017-05-17 20:42:48 +0200690/*
691 * openssl async delayed SSL_free handler
692 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200693void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000694{
695 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200696 OSSL_ASYNC_FD all_fd[32];
697 size_t num_all_fds = 0;
698 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000699
Emeric Brun3854e012017-05-17 20:42:48 +0200700 /* We suppose that the async job for a same SSL *
701 * are serialized. So if we are awake it is
702 * because the running job has just finished
703 * and we can remove all async fds safely
704 */
705 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
706 if (num_all_fds > 32) {
707 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
708 return;
709 }
710
711 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
712 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200713 fd_stop_both(all_fd[i]);
Emeric Brun3854e012017-05-17 20:42:48 +0200714
715 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000716 SSL_free(ssl);
Willy Tarreau82531f62021-10-06 12:15:18 +0200717 _HA_ATOMIC_DEC(&global.sslconns);
Willy Tarreau4781b152021-04-06 13:53:36 +0200718 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000719}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000720/*
Emeric Brun3854e012017-05-17 20:42:48 +0200721 * function used to manage a returned SSL_ERROR_WANT_ASYNC
722 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000723 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200724static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000725{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100726 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200727 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200728 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000729 size_t num_add_fds = 0;
730 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200731 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000732
733 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
734 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200735 if (num_add_fds > 32 || num_del_fds > 32) {
736 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 +0000737 return;
738 }
739
Emeric Brun3854e012017-05-17 20:42:48 +0200740 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000741
Emeric Brun3854e012017-05-17 20:42:48 +0200742 /* We remove unused fds from the fdtab */
743 for (i=0 ; i < num_del_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200744 fd_stop_both(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000745
Emeric Brun3854e012017-05-17 20:42:48 +0200746 /* We add new fds to the fdtab */
747 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200748 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000749 }
750
Emeric Brun3854e012017-05-17 20:42:48 +0200751 num_add_fds = 0;
752 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
753 if (num_add_fds > 32) {
754 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
755 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000756 }
Emeric Brun3854e012017-05-17 20:42:48 +0200757
758 /* We activate the polling for all known async fds */
759 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000760 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200761 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000762 /* To ensure that the fd cache won't be used
763 * We'll prefer to catch a real RD event
764 * because handling an EAGAIN on this fd will
765 * result in a context switch and also
766 * some engines uses a fd in blocking mode.
767 */
768 fd_cant_recv(add_fd[i]);
769 }
Emeric Brun3854e012017-05-17 20:42:48 +0200770
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000771}
772#endif
773
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200774#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP && !defined HAVE_ASN1_TIME_TO_TM)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200775/*
776 * This function returns the number of seconds elapsed
777 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
778 * date presented un ASN1_GENERALIZEDTIME.
779 *
780 * In parsing error case, it returns -1.
781 */
782static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
783{
784 long epoch;
785 char *p, *end;
786 const unsigned short month_offset[12] = {
787 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
788 };
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +0200789 unsigned long year, month;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200790
791 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
792
793 p = (char *)d->data;
794 end = p + d->length;
795
796 if (end - p < 4) return -1;
797 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
798 p += 4;
799 if (end - p < 2) return -1;
800 month = 10 * (p[0] - '0') + p[1] - '0';
801 if (month < 1 || month > 12) return -1;
802 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
803 We consider leap years and the current month (<marsh or not) */
804 epoch = ( ((year - 1970) * 365)
805 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
806 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
807 + month_offset[month-1]
808 ) * 24 * 60 * 60;
809 p += 2;
810 if (end - p < 2) return -1;
811 /* Add the number of seconds of completed days of current month */
812 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
813 p += 2;
814 if (end - p < 2) return -1;
815 /* Add the completed hours of the current day */
816 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
817 p += 2;
818 if (end - p < 2) return -1;
819 /* Add the completed minutes of the current hour */
820 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
821 p += 2;
822 if (p == end) return -1;
823 /* Test if there is available seconds */
824 if (p[0] < '0' || p[0] > '9')
825 goto nosec;
826 if (end - p < 2) return -1;
827 /* Add the seconds of the current minute */
828 epoch += 10 * (p[0] - '0') + p[1] - '0';
829 p += 2;
830 if (p == end) return -1;
831 /* Ignore seconds float part if present */
832 if (p[0] == '.') {
833 do {
834 if (++p == end) return -1;
835 } while (p[0] >= '0' && p[0] <= '9');
836 }
837
838nosec:
839 if (p[0] == 'Z') {
840 if (end - p != 1) return -1;
841 return epoch;
842 }
843 else if (p[0] == '+') {
844 if (end - p != 5) return -1;
845 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700846 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 +0200847 }
848 else if (p[0] == '-') {
849 if (end - p != 5) return -1;
850 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700851 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 +0200852 }
853
854 return -1;
855}
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200856#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200857
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200858#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
William Lallemand104a7a62019-10-14 14:14:59 +0200859/*
860 * struct alignment works here such that the key.key is the same as key_data
861 * Do not change the placement of key_data
862 */
863struct certificate_ocsp {
864 struct ebmb_node key;
865 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
Remi Tricot-Le Breton5aa1dce2021-06-10 13:51:12 +0200866 unsigned int key_length;
William Lallemand104a7a62019-10-14 14:14:59 +0200867 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200868 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200869 long expire;
870};
871
872struct ocsp_cbk_arg {
873 int is_single;
874 int single_kt;
875 union {
876 struct certificate_ocsp *s_ocsp;
877 /*
878 * m_ocsp will have multiple entries dependent on key type
879 * Entry 0 - DSA
880 * Entry 1 - ECDSA
881 * Entry 2 - RSA
882 */
883 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
884 };
885};
886
Emeric Brun1d3865b2014-06-20 15:37:32 +0200887static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200888
889/* This function starts to check if the OCSP response (in DER format) contained
890 * in chunk 'ocsp_response' is valid (else exits on error).
891 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
892 * contained in the OCSP Response and exits on error if no match.
893 * If it's a valid OCSP Response:
894 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
895 * pointed by 'ocsp'.
896 * If 'ocsp' is NULL, the function looks up into the OCSP response's
897 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
898 * from the response) and exits on error if not found. Finally, If an OCSP response is
899 * already present in the container, it will be overwritten.
900 *
901 * Note: OCSP response containing more than one OCSP Single response is not
902 * considered valid.
903 *
904 * Returns 0 on success, 1 in error case.
905 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200906static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
907 struct certificate_ocsp *ocsp,
908 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200909{
910 OCSP_RESPONSE *resp;
911 OCSP_BASICRESP *bs = NULL;
912 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200913 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200914 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200915 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200916 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200917 int reason;
918 int ret = 1;
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200919#ifdef HAVE_ASN1_TIME_TO_TM
920 struct tm nextupd_tm = {0};
921#endif
Emeric Brun4147b2e2014-06-16 18:36:30 +0200922
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200923 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
924 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200925 if (!resp) {
926 memprintf(err, "Unable to parse OCSP response");
927 goto out;
928 }
929
930 rc = OCSP_response_status(resp);
931 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
932 memprintf(err, "OCSP response status not successful");
933 goto out;
934 }
935
936 bs = OCSP_response_get1_basic(resp);
937 if (!bs) {
938 memprintf(err, "Failed to get basic response from OCSP Response");
939 goto out;
940 }
941
942 count_sr = OCSP_resp_count(bs);
943 if (count_sr > 1) {
944 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
945 goto out;
946 }
947
948 sr = OCSP_resp_get0(bs, 0);
949 if (!sr) {
950 memprintf(err, "Failed to get OCSP single response");
951 goto out;
952 }
953
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200954 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
955
Emeric Brun4147b2e2014-06-16 18:36:30 +0200956 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200957 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200958 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200959 goto out;
960 }
961
Emeric Brun13a6b482014-06-20 15:44:34 +0200962 if (!nextupd) {
963 memprintf(err, "OCSP single response: missing nextupdate");
964 goto out;
965 }
966
Emeric Brunc8b27b62014-06-19 14:16:17 +0200967 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200968 if (!rc) {
969 memprintf(err, "OCSP single response: no longer valid.");
970 goto out;
971 }
972
973 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200974 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +0200975 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
976 goto out;
977 }
978 }
979
980 if (!ocsp) {
981 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
982 unsigned char *p;
983
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200984 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200985 if (!rc) {
986 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
987 goto out;
988 }
989
990 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
991 memprintf(err, "OCSP single response: Certificate ID too long");
992 goto out;
993 }
994
995 p = key;
996 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200997 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200998 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
999 if (!ocsp) {
1000 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
1001 goto out;
1002 }
1003 }
1004
1005 /* According to comments on "chunk_dup", the
1006 previous chunk buffer will be freed */
1007 if (!chunk_dup(&ocsp->response, ocsp_response)) {
1008 memprintf(err, "OCSP response: Memory allocation error");
1009 goto out;
1010 }
1011
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001012#ifdef HAVE_ASN1_TIME_TO_TM
1013 if (ASN1_TIME_to_tm(nextupd, &nextupd_tm) == 0) {
1014 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1015 goto out;
1016 }
1017 ocsp->expire = my_timegm(&nextupd_tm) - OCSP_MAX_RESPONSE_TIME_SKEW;
1018#else
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001019 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +02001020 if (ocsp->expire < 0) {
1021 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1022 goto out;
1023 }
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001024#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001025
Emeric Brun4147b2e2014-06-16 18:36:30 +02001026 ret = 0;
1027out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001028 ERR_clear_error();
1029
Emeric Brun4147b2e2014-06-16 18:36:30 +02001030 if (bs)
1031 OCSP_BASICRESP_free(bs);
1032
1033 if (resp)
1034 OCSP_RESPONSE_free(resp);
1035
1036 return ret;
1037}
1038/*
1039 * External function use to update the OCSP response in the OCSP response's
1040 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1041 * to update in DER format.
1042 *
1043 * Returns 0 on success, 1 in error case.
1044 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001045int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001046{
1047 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1048}
1049
William Lallemand4a660132019-10-14 14:51:41 +02001050#endif
1051
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001052#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1053static 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)
1054{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001055 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001056 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001057 struct connection *conn;
1058 int head;
1059 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001060 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001061
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001062 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001063 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001064 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1065
1066 keys = ref->tlskeys;
1067 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001068
1069 if (enc) {
1070 memcpy(key_name, keys[head].name, 16);
1071
1072 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001073 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001074
Emeric Brun9e754772019-01-10 17:51:55 +01001075 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001076
Emeric Brun9e754772019-01-10 17:51:55 +01001077 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1078 goto end;
1079
Willy Tarreau9356dac2019-05-10 09:22:53 +02001080 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001081 ret = 1;
1082 }
1083 else if (ref->key_size_bits == 256 ) {
1084
1085 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1086 goto end;
1087
Willy Tarreau9356dac2019-05-10 09:22:53 +02001088 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001089 ret = 1;
1090 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001091 } else {
1092 for (i = 0; i < TLS_TICKETS_NO; i++) {
1093 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1094 goto found;
1095 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001096 ret = 0;
1097 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001098
Christopher Faulet16f45c82018-02-16 11:23:49 +01001099 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001100 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001101 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 +01001102 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1103 goto end;
1104 /* 2 for key renewal, 1 if current key is still valid */
1105 ret = i ? 2 : 1;
1106 }
1107 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001108 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 +01001109 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1110 goto end;
1111 /* 2 for key renewal, 1 if current key is still valid */
1112 ret = i ? 2 : 1;
1113 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001114 }
Emeric Brun9e754772019-01-10 17:51:55 +01001115
Christopher Faulet16f45c82018-02-16 11:23:49 +01001116 end:
1117 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1118 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001119}
1120
1121struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1122{
1123 struct tls_keys_ref *ref;
1124
1125 list_for_each_entry(ref, &tlskeys_reference, list)
1126 if (ref->filename && strcmp(filename, ref->filename) == 0)
1127 return ref;
1128 return NULL;
1129}
1130
1131struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1132{
1133 struct tls_keys_ref *ref;
1134
1135 list_for_each_entry(ref, &tlskeys_reference, list)
1136 if (ref->unique_id == unique_id)
1137 return ref;
1138 return NULL;
1139}
1140
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001141/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001142 * match existing ones, this function returns -1
1143 * else it returns 0 on success.
1144 */
1145int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001146 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001147{
Emeric Brun9e754772019-01-10 17:51:55 +01001148 if (ref->key_size_bits == 128) {
1149 if (tlskey->data != sizeof(struct tls_sess_key_128))
1150 return -1;
1151 }
1152 else if (ref->key_size_bits == 256) {
1153 if (tlskey->data != sizeof(struct tls_sess_key_256))
1154 return -1;
1155 }
1156 else
1157 return -1;
1158
Christopher Faulet16f45c82018-02-16 11:23:49 +01001159 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001160 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1161 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001162 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1163 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001164
1165 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001166}
1167
Willy Tarreau83061a82018-07-13 11:56:34 +02001168int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001169{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001170 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1171
1172 if(!ref) {
1173 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1174 return 1;
1175 }
Emeric Brun9e754772019-01-10 17:51:55 +01001176 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1177 memprintf(err, "Invalid key size");
1178 return 1;
1179 }
1180
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001181 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001182}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001183
1184/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001185 * automatic ids. It's called just after the basic checks. It returns
1186 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001187 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001188static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001189{
1190 int i = 0;
1191 struct tls_keys_ref *ref, *ref2, *ref3;
1192 struct list tkr = LIST_HEAD_INIT(tkr);
1193
1194 list_for_each_entry(ref, &tlskeys_reference, list) {
1195 if (ref->unique_id == -1) {
1196 /* Look for the first free id. */
1197 while (1) {
1198 list_for_each_entry(ref2, &tlskeys_reference, list) {
1199 if (ref2->unique_id == i) {
1200 i++;
1201 break;
1202 }
1203 }
1204 if (&ref2->list == &tlskeys_reference)
1205 break;
1206 }
1207
1208 /* Uses the unique id and increment it for the next entry. */
1209 ref->unique_id = i;
1210 i++;
1211 }
1212 }
1213
1214 /* This sort the reference list by id. */
1215 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001216 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001217 list_for_each_entry(ref3, &tkr, list) {
1218 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001219 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001220 break;
1221 }
1222 }
1223 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001224 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001225 }
1226
1227 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001228 LIST_INSERT(&tkr, &tlskeys_reference);
1229 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001230 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001231}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001232#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1233
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001234#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001235int ocsp_ex_index = -1;
1236
yanbzhube2774d2015-12-10 15:07:30 -05001237int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1238{
1239 switch (evp_keytype) {
1240 case EVP_PKEY_RSA:
1241 return 2;
1242 case EVP_PKEY_DSA:
1243 return 0;
1244 case EVP_PKEY_EC:
1245 return 1;
1246 }
1247
1248 return -1;
1249}
1250
Emeric Brun4147b2e2014-06-16 18:36:30 +02001251/*
1252 * Callback used to set OCSP status extension content in server hello.
1253 */
1254int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1255{
yanbzhube2774d2015-12-10 15:07:30 -05001256 struct certificate_ocsp *ocsp;
1257 struct ocsp_cbk_arg *ocsp_arg;
1258 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001259 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001260 EVP_PKEY *ssl_pkey;
1261 int key_type;
1262 int index;
1263
William Lallemand76b4a122020-08-04 17:41:39 +02001264 ctx = SSL_get_SSL_CTX(ssl);
1265 if (!ctx)
1266 return SSL_TLSEXT_ERR_NOACK;
1267
1268 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1269 if (!ocsp_arg)
1270 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001271
1272 ssl_pkey = SSL_get_privatekey(ssl);
1273 if (!ssl_pkey)
1274 return SSL_TLSEXT_ERR_NOACK;
1275
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001276 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001277
1278 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1279 ocsp = ocsp_arg->s_ocsp;
1280 else {
1281 /* For multiple certs per context, we have to find the correct OCSP response based on
1282 * the certificate type
1283 */
1284 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1285
1286 if (index < 0)
1287 return SSL_TLSEXT_ERR_NOACK;
1288
1289 ocsp = ocsp_arg->m_ocsp[index];
1290
1291 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001292
1293 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001294 !ocsp->response.area ||
1295 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001296 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001297 return SSL_TLSEXT_ERR_NOACK;
1298
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001299 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001300 if (!ssl_buf)
1301 return SSL_TLSEXT_ERR_NOACK;
1302
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001303 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1304 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001305
1306 return SSL_TLSEXT_ERR_OK;
1307}
1308
William Lallemand4a660132019-10-14 14:51:41 +02001309#endif
1310
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001311#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001312
1313
1314/*
1315 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1316 * used anymore. Also removes it from the tree if free'd.
1317 */
1318static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1319{
1320 if (!ocsp)
1321 return;
1322
1323 ocsp->refcount--;
1324 if (ocsp->refcount <= 0) {
1325 ebmb_delete(&ocsp->key);
1326 chunk_destroy(&ocsp->response);
1327 free(ocsp);
1328 }
1329}
1330
1331
Emeric Brun4147b2e2014-06-16 18:36:30 +02001332/*
1333 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001334 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1335 * status extension, the issuer's certificate is mandatory. It should be
1336 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001337 *
William Lallemand246c0242019-10-11 08:59:13 +02001338 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1339 * OCSP response. If file is empty or content is not a valid OCSP response,
1340 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1341 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001342 *
1343 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001344 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001345 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001346static 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 +02001347{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001348 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001349 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001350 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001351 struct certificate_ocsp *ocsp = NULL, *iocsp;
1352 char *warn = NULL;
1353 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001354 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001355
Emeric Brun4147b2e2014-06-16 18:36:30 +02001356
William Lallemand246c0242019-10-11 08:59:13 +02001357 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001358 if (!x)
1359 goto out;
1360
William Lallemand246c0242019-10-11 08:59:13 +02001361 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001362 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1363 if (chain) {
1364 /* check if one of the certificate of the chain is the issuer */
1365 for (i = 0; i < sk_X509_num(chain); i++) {
1366 X509 *ti = sk_X509_value(chain, i);
1367 if (X509_check_issued(ti, x) == X509_V_OK) {
1368 issuer = ti;
1369 break;
1370 }
1371 }
1372 }
William Lallemand246c0242019-10-11 08:59:13 +02001373 if (!issuer)
1374 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001375
1376 cid = OCSP_cert_to_id(0, x, issuer);
1377 if (!cid)
1378 goto out;
1379
1380 i = i2d_OCSP_CERTID(cid, NULL);
1381 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1382 goto out;
1383
Vincent Bernat02779b62016-04-03 13:48:43 +02001384 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001385 if (!ocsp)
1386 goto out;
1387
1388 p = ocsp->key_data;
Remi Tricot-Le Breton5aa1dce2021-06-10 13:51:12 +02001389 ocsp->key_length = i2d_OCSP_CERTID(cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001390
1391 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1392 if (iocsp == ocsp)
1393 ocsp = NULL;
1394
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001395#ifndef SSL_CTX_get_tlsext_status_cb
1396# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1397 *cb = (void (*) (void))ctx->tlsext_status_cb;
1398#endif
1399 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1400
1401 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001402 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001403 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001404
William Lallemanda560c062020-07-31 11:43:20 +02001405 cb_arg = calloc(1, sizeof(*cb_arg));
1406 if (!cb_arg)
1407 goto out;
1408
yanbzhube2774d2015-12-10 15:07:30 -05001409 cb_arg->is_single = 1;
1410 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001411 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001412
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001413 pkey = X509_get_pubkey(x);
1414 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1415 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001416
1417 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001418 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 */
1419
yanbzhube2774d2015-12-10 15:07:30 -05001420 } else {
1421 /*
1422 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1423 * Update that cb_arg with the new cert's staple
1424 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001425 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001426 struct certificate_ocsp *tmp_ocsp;
1427 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001428 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001429 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001430
William Lallemand76b4a122020-08-04 17:41:39 +02001431 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001432
1433 /*
1434 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1435 * the order of operations below matter, take care when changing it
1436 */
1437 tmp_ocsp = cb_arg->s_ocsp;
1438 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1439 cb_arg->s_ocsp = NULL;
1440 cb_arg->m_ocsp[index] = tmp_ocsp;
1441 cb_arg->is_single = 0;
1442 cb_arg->single_kt = 0;
1443
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001444 pkey = X509_get_pubkey(x);
1445 key_type = EVP_PKEY_base_id(pkey);
1446 EVP_PKEY_free(pkey);
1447
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001448 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001449 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001450 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001451 iocsp->refcount++;
1452 }
yanbzhube2774d2015-12-10 15:07:30 -05001453 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001454
1455 ret = 0;
1456
1457 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001458 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001459 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001460 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001461 }
1462
1463out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001464 if (cid)
1465 OCSP_CERTID_free(cid);
1466
1467 if (ocsp)
1468 free(ocsp);
1469
1470 if (warn)
1471 free(warn);
1472
Emeric Brun4147b2e2014-06-16 18:36:30 +02001473 return ret;
1474}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001475#endif
1476
1477#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001478static 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 +02001479{
William Lallemand4a660132019-10-14 14:51:41 +02001480 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 +02001481}
1482#endif
1483
William Lallemand4a660132019-10-14 14:51:41 +02001484
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001485#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001486
1487#define CT_EXTENSION_TYPE 18
1488
William Lallemand03c331c2020-05-13 10:10:01 +02001489int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001490
1491int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1492{
Willy Tarreau83061a82018-07-13 11:56:34 +02001493 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001494
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001495 *out = (unsigned char *) sctl->area;
1496 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001497
1498 return 1;
1499}
1500
1501int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1502{
1503 return 1;
1504}
1505
William Lallemanda17f4112019-10-10 15:16:44 +02001506static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001507{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001508 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001509
William Lallemanda17f4112019-10-10 15:16:44 +02001510 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 +01001511 goto out;
1512
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001513 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1514
1515 ret = 0;
1516
1517out:
1518 return ret;
1519}
1520
1521#endif
1522
Emeric Brune1f38db2012-09-03 20:36:47 +02001523void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1524{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001525 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001526#ifdef USE_QUIC
1527 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1528#endif /* USE_QUIC */
1529 struct ssl_sock_ctx *ctx = NULL;
1530
Emeric Brund8b2bb52014-01-28 15:43:53 +01001531 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001532 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001533
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001534 if (conn)
1535 ctx = conn->xprt_ctx;
1536#ifdef USE_QUIC
1537 else if (qc)
1538 ctx = qc->xprt_ctx;
1539#endif /* USE_QUIC */
1540 BUG_ON(!ctx);
1541
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001542#ifndef SSL_OP_NO_RENEGOTIATION
1543 /* Please note that BoringSSL defines this macro to zero so don't
1544 * change this to #if and do not assign a default value to this macro!
1545 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001546 if (where & SSL_CB_HANDSHAKE_START) {
1547 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001548 if (conn && (conn->flags & (CO_FL_WAIT_L6_CONN | CO_FL_EARLY_SSL_HS | CO_FL_EARLY_DATA)) == 0) {
Emeric Brune1f38db2012-09-03 20:36:47 +02001549 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001550 conn->err_code = CO_ER_SSL_RENEG;
1551 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001552 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001553#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001554
1555 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001556 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001557 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001558 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001559 consider that the buffering was activated,
1560 so we rise the output buffer size from 4k
1561 to 16k */
1562 write_bio = SSL_get_wbio(ssl);
1563 if (write_bio != SSL_get_rbio(ssl)) {
1564 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001565 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001566 }
1567 }
1568 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001569}
1570
Emeric Brune64aef12012-09-21 13:15:06 +02001571/* Callback is called for each certificate of the chain during a verify
1572 ok is set to 1 if preverify detect no error on current certificate.
1573 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001574int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001575{
1576 SSL *ssl;
1577 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001578 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001579 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001580 X509 *client_crt;
1581 STACK_OF(X509) *certs;
Emeric Brune64aef12012-09-21 13:15:06 +02001582
1583 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001584 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001585 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001586
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001587 ctx = conn->xprt_ctx;
1588
1589 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001590
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001591 depth = X509_STORE_CTX_get_error_depth(x_store);
1592 err = X509_STORE_CTX_get_error(x_store);
1593
Emeric Brun81c00f02012-09-21 14:31:21 +02001594 if (ok) /* no errors */
1595 return ok;
1596
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001597 /* Keep a reference to the client's certificate in order to be able to
1598 * dump some fetches values in a log even when the verification process
1599 * fails. */
1600 if (depth == 0) {
1601 X509_free(client_crt);
1602 client_crt = X509_STORE_CTX_get0_cert(x_store);
1603 if (client_crt) {
1604 X509_up_ref(client_crt);
1605 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1606 }
1607 }
1608 else {
1609 /* An error occurred on a CA certificate of the certificate
1610 * chain, we might never call this verify callback on the client
1611 * certificate's depth (which is 0) so we try to store the
1612 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001613 certs = X509_STORE_CTX_get1_chain(x_store);
1614 if (certs) {
1615 client_crt = sk_X509_value(certs, 0);
1616 if (client_crt) {
1617 X509_up_ref(client_crt);
1618 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001619 }
1620 sk_X509_pop_free(certs, X509_free);
1621 }
1622 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001623
1624 /* check if CA error needs to be ignored */
1625 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001626 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1627 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1628 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001629 }
1630
Willy Tarreau731248f2020-02-04 14:02:02 +01001631 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001632 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001633 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001634 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001635 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001636
Willy Tarreau20879a02012-12-03 16:32:10 +01001637 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001638 return 0;
1639 }
1640
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001641 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1642 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001643
Emeric Brun81c00f02012-09-21 14:31:21 +02001644 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001645 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << 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;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001703 uchar *msg;
1704 uchar *end;
1705 uchar *extensions_end;
1706 uchar *ec_start = NULL;
1707 uchar *ec_formats_start = NULL;
1708 uchar *list_end;
1709 ushort protocol_version;
1710 ushort extension_id;
1711 ushort ec_len = 0;
1712 uchar ec_formats_len = 0;
1713 int offset = 0;
1714 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001715
1716 /* This function is called for "from client" and "to server"
1717 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001718 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001719 */
1720
1721 /* "write_p" is set to 0 is the bytes are received messages,
1722 * otherwise it is set to 1.
1723 */
1724 if (write_p != 0)
1725 return;
1726
1727 /* content_type contains the type of message received or sent
1728 * according with the SSL/TLS protocol spec. This message is
1729 * encoded with one byte. The value 256 (two bytes) is used
1730 * for designing the SSL/TLS record layer. According with the
1731 * rfc6101, the expected message (other than 256) are:
1732 * - change_cipher_spec(20)
1733 * - alert(21)
1734 * - handshake(22)
1735 * - application_data(23)
1736 * - (255)
1737 * We are interessed by the handshake and specially the client
1738 * hello.
1739 */
1740 if (content_type != 22)
1741 return;
1742
1743 /* The message length is at least 4 bytes, containing the
1744 * message type and the message length.
1745 */
1746 if (len < 4)
1747 return;
1748
1749 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001750 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001751 * - hello_request(0)
1752 * - client_hello(1)
1753 * - server_hello(2)
1754 * - certificate(11)
1755 * - server_key_exchange (12)
1756 * - certificate_request(13)
1757 * - server_hello_done(14)
1758 * We are interested by the client hello.
1759 */
1760 msg = (unsigned char *)buf;
1761 if (msg[0] != 1)
1762 return;
1763
1764 /* Next three bytes are the length of the message. The total length
1765 * must be this decoded length + 4. If the length given as argument
1766 * is not the same, we abort the protocol dissector.
1767 */
1768 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1769 if (len < rec_len + 4)
1770 return;
1771 msg += 4;
1772 end = msg + rec_len;
1773 if (end < msg)
1774 return;
1775
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001776 /* Expect 2 bytes for protocol version
1777 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001778 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001779 if (msg + 2 > end)
1780 return;
1781 protocol_version = (msg[0] << 8) + msg[1];
1782 msg += 2;
1783
1784 /* Expect the random, composed by 4 bytes for the unix time and
1785 * 28 bytes for unix payload. So we jump 4 + 28.
1786 */
1787 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001788 if (msg > end)
1789 return;
1790
1791 /* Next, is session id:
1792 * if present, we have to jump by length + 1 for the size information
1793 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001794 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001795 if (msg[0] > 0)
1796 msg += msg[0];
1797 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001798 if (msg > end)
1799 return;
1800
1801 /* Next two bytes are the ciphersuite length. */
1802 if (msg + 2 > end)
1803 return;
1804 rec_len = (msg[0] << 8) + msg[1];
1805 msg += 2;
1806 if (msg + rec_len > end || msg + rec_len < msg)
1807 return;
1808
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001809 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001810 if (!capture)
1811 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001812 /* Compute the xxh64 of the ciphersuite. */
1813 capture->xxh64 = XXH64(msg, rec_len, 0);
1814
1815 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02001816 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001817 capture->ciphersuite_offset = 0;
1818 memcpy(capture->data, msg, capture->ciphersuite_len);
1819 msg += rec_len;
1820 offset += capture->ciphersuite_len;
1821
1822 /* Initialize other data */
1823 capture->protocol_version = protocol_version;
1824
1825 /* Next, compression methods:
1826 * if present, we have to jump by length + 1 for the size information
1827 * if not present, we have to jump by 1 only
1828 */
1829 if (msg[0] > 0)
1830 msg += msg[0];
1831 msg += 1;
1832 if (msg > end)
1833 goto store_capture;
1834
1835 /* We reached extensions */
1836 if (msg + 2 > end)
1837 goto store_capture;
1838 rec_len = (msg[0] << 8) + msg[1];
1839 msg += 2;
1840 if (msg + rec_len > end || msg + rec_len < msg)
1841 goto store_capture;
1842 extensions_end = msg + rec_len;
1843 capture->extensions_offset = offset;
1844
1845 /* Parse each extension */
1846 while (msg + 4 < extensions_end) {
1847 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02001848 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001849 capture->data[offset++] = msg[0];
1850 capture->data[offset++] = msg[1];
1851 capture->extensions_len += 2;
1852 }
1853 else
1854 break;
1855 extension_id = (msg[0] << 8) + msg[1];
1856 /* Length of the extension */
1857 rec_len = (msg[2] << 8) + msg[3];
1858
1859 /* Expect 2 bytes extension id + 2 bytes extension size */
1860 msg += 2 + 2;
1861 if (msg + rec_len > extensions_end || msg + rec_len < msg)
1862 goto store_capture;
1863 /* TLS Extensions
1864 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
1865 if (extension_id == 0x000a) {
1866 /* Elliptic Curves:
1867 * https://www.rfc-editor.org/rfc/rfc8422.html
1868 * https://www.rfc-editor.org/rfc/rfc7919.html */
1869 list_end = msg + rec_len;
1870 if (msg + 2 > list_end)
1871 goto store_capture;
1872 rec_len = (msg[0] << 8) + msg[1];
1873 msg += 2;
1874
1875 if (msg + rec_len > list_end || msg + rec_len < msg)
1876 goto store_capture;
1877 /* Store location/size of the list */
1878 ec_start = msg;
1879 ec_len = rec_len;
1880 }
1881 else if (extension_id == 0x000b) {
1882 /* Elliptic Curves Point Formats:
1883 * https://www.rfc-editor.org/rfc/rfc8422.html */
1884 list_end = msg + rec_len;
1885 if (msg + 1 > list_end)
1886 goto store_capture;
1887 rec_len = msg[0];
1888 msg += 1;
1889
1890 if (msg + rec_len > list_end || msg + rec_len < msg)
1891 goto store_capture;
1892 /* Store location/size of the list */
1893 ec_formats_start = msg;
1894 ec_formats_len = rec_len;
1895 }
1896 msg += rec_len;
1897 }
1898
1899 if (ec_start) {
1900 rec_len = ec_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001901 if (offset + rec_len > global_ssl.capture_buffer_size)
1902 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001903 memcpy(capture->data + offset, ec_start, rec_len);
1904 capture->ec_offset = offset;
1905 capture->ec_len = rec_len;
1906 offset += rec_len;
1907 }
1908 if (ec_formats_start) {
1909 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001910 if (offset + rec_len > global_ssl.capture_buffer_size)
1911 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001912 memcpy(capture->data + offset, ec_formats_start, rec_len);
1913 capture->ec_formats_offset = offset;
1914 capture->ec_formats_len = rec_len;
1915 offset += rec_len;
1916 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001917
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001918 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001919 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001920}
William Lallemand7d42ef52020-07-06 11:41:30 +02001921
1922
William Lallemand722180a2021-06-09 16:46:12 +02001923#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001924static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1925 int content_type, const void *buf, size_t len,
1926 SSL *ssl)
1927{
1928 struct ssl_keylog *keylog;
1929
1930 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1931 return;
1932
Willy Tarreauf208ac02021-03-22 21:10:12 +01001933 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001934 if (!keylog)
1935 return;
1936
William Lallemand7d42ef52020-07-06 11:41:30 +02001937 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1938 pool_free(pool_head_ssl_keylog, keylog);
1939 return;
1940 }
1941}
1942#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001943
Emeric Brun29f037d2014-04-25 19:05:36 +02001944/* Callback is called for ssl protocol analyse */
1945void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1946{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001947 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1948 struct ssl_sock_msg_callback *cbk;
1949
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001950 /* Try to call all callback functions that were registered by using
1951 * ssl_sock_register_msg_callback().
1952 */
1953 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1954 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1955 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001956}
1957
Bernard Spil13c53f82018-02-15 13:34:58 +01001958#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001959static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1960 const unsigned char *in, unsigned int inlen,
1961 void *arg)
1962{
1963 struct server *srv = arg;
1964
1965 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1966 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1967 return SSL_TLSEXT_ERR_OK;
1968 return SSL_TLSEXT_ERR_NOACK;
1969}
1970#endif
1971
1972#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001973/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001974 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001975 */
1976static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1977 unsigned int *len, void *arg)
1978{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001979 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001980
1981 *data = (const unsigned char *)conf->npn_str;
1982 *len = conf->npn_len;
1983 return SSL_TLSEXT_ERR_OK;
1984}
1985#endif
1986
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001987#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001988/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001989 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001990 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001991static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1992 unsigned char *outlen,
1993 const unsigned char *server,
1994 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001995{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001996 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001997#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001998 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001999#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02002000
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002001 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
2002 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01002003#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002004 if (qc)
2005 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01002006#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002007 return SSL_TLSEXT_ERR_NOACK;
2008 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002009
2010#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002011 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
2012 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002013 return SSL_TLSEXT_ERR_NOACK;
2014 }
2015#endif
2016
Willy Tarreauab861d32013-04-02 02:30:41 +02002017 return SSL_TLSEXT_ERR_OK;
2018}
2019#endif
2020
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02002021#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002022#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002023
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002024/* Configure a DNS SAN extenion on a certificate. */
2025int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
2026 int failure = 0;
2027 X509_EXTENSION *san_ext = NULL;
2028 CONF *conf = NULL;
2029 struct buffer *san_name = get_trash_chunk();
2030
2031 conf = NCONF_new(NULL);
2032 if (!conf) {
2033 failure = 1;
2034 goto cleanup;
2035 }
2036
2037 /* Build an extension based on the DNS entry above */
2038 chunk_appendf(san_name, "DNS:%s", servername);
2039 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
2040 if (!san_ext) {
2041 failure = 1;
2042 goto cleanup;
2043 }
2044
2045 /* Add the extension */
2046 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
2047 failure = 1;
2048 goto cleanup;
2049 }
2050
2051 /* Success */
2052 failure = 0;
2053
2054cleanup:
2055 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
2056 if (NULL != conf) NCONF_free(conf);
2057
2058 return failure;
2059}
2060
Christopher Faulet30548802015-06-11 13:39:32 +02002061/* Create a X509 certificate with the specified servername and serial. This
2062 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02002063static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002064ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002065{
Shimi Gersner5846c492020-08-23 13:58:12 +03002066 X509 *cacert = bind_conf->ca_sign_ckch->cert;
2067 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002068 SSL_CTX *ssl_ctx = NULL;
2069 X509 *newcrt = NULL;
2070 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002071 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002072 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002073 X509_NAME *name;
2074 const EVP_MD *digest;
2075 X509V3_CTX ctx;
2076 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002077 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002078
Christopher Faulet48a83322017-07-28 16:56:09 +02002079 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05002080#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002081 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
2082#else
2083 tmp_ssl = SSL_new(bind_conf->default_ctx);
2084 if (tmp_ssl)
2085 pkey = SSL_get_privatekey(tmp_ssl);
2086#endif
2087 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002088 goto mkcert_error;
2089
2090 /* Create the certificate */
2091 if (!(newcrt = X509_new()))
2092 goto mkcert_error;
2093
2094 /* Set version number for the certificate (X509v3) and the serial
2095 * number */
2096 if (X509_set_version(newcrt, 2L) != 1)
2097 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02002098 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002099
2100 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08002101 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
2102 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002103 goto mkcert_error;
2104
2105 /* set public key in the certificate */
2106 if (X509_set_pubkey(newcrt, pkey) != 1)
2107 goto mkcert_error;
2108
2109 /* Set issuer name from the CA */
2110 if (!(name = X509_get_subject_name(cacert)))
2111 goto mkcert_error;
2112 if (X509_set_issuer_name(newcrt, name) != 1)
2113 goto mkcert_error;
2114
2115 /* Set the subject name using the same, but the CN */
2116 name = X509_NAME_dup(name);
2117 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
2118 (const unsigned char *)servername,
2119 -1, -1, 0) != 1) {
2120 X509_NAME_free(name);
2121 goto mkcert_error;
2122 }
2123 if (X509_set_subject_name(newcrt, name) != 1) {
2124 X509_NAME_free(name);
2125 goto mkcert_error;
2126 }
2127 X509_NAME_free(name);
2128
2129 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002130 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002131 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
2132 for (i = 0; i < X509V3_EXT_SIZE; i++) {
2133 X509_EXTENSION *ext;
2134
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002135 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002136 goto mkcert_error;
2137 if (!X509_add_ext(newcrt, ext, -1)) {
2138 X509_EXTENSION_free(ext);
2139 goto mkcert_error;
2140 }
2141 X509_EXTENSION_free(ext);
2142 }
2143
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002144 /* Add SAN extension */
2145 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
2146 goto mkcert_error;
2147 }
2148
Christopher Faulet31af49d2015-06-09 17:29:50 +02002149 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002150
2151 key_type = EVP_PKEY_base_id(capkey);
2152
2153 if (key_type == EVP_PKEY_DSA)
2154 digest = EVP_sha1();
2155 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002156 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002157 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002158 digest = EVP_sha256();
2159 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002160#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002161 int nid;
2162
2163 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2164 goto mkcert_error;
2165 if (!(digest = EVP_get_digestbynid(nid)))
2166 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002167#else
2168 goto mkcert_error;
2169#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002170 }
2171
Christopher Faulet31af49d2015-06-09 17:29:50 +02002172 if (!(X509_sign(newcrt, capkey, digest)))
2173 goto mkcert_error;
2174
2175 /* Create and set the new SSL_CTX */
2176 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2177 goto mkcert_error;
2178 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2179 goto mkcert_error;
2180 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2181 goto mkcert_error;
2182 if (!SSL_CTX_check_private_key(ssl_ctx))
2183 goto mkcert_error;
2184
Shimi Gersner5846c492020-08-23 13:58:12 +03002185 /* Build chaining the CA cert and the rest of the chain, keep these order */
2186#if defined(SSL_CTX_add1_chain_cert)
2187 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2188 goto mkcert_error;
2189 }
2190
2191 if (bind_conf->ca_sign_ckch->chain) {
2192 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2193 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2194 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2195 goto mkcert_error;
2196 }
2197 }
2198 }
2199#endif
2200
Christopher Faulet31af49d2015-06-09 17:29:50 +02002201 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002202
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002203#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002204 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002205#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002206#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2207 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002208 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002209 EC_KEY *ecc;
2210 int nid;
2211
2212 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2213 goto end;
2214 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2215 goto end;
2216 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2217 EC_KEY_free(ecc);
2218 }
2219#endif
2220 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002221 return ssl_ctx;
2222
2223 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002224 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002225 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002226 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2227 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002228 return NULL;
2229}
2230
Christopher Faulet7969a332015-10-09 11:15:03 +02002231SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002232ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02002233{
Willy Tarreau07d94e42018-09-20 10:57:52 +02002234 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01002235 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002236
Olivier Houchard66ab4982019-02-26 18:37:15 +01002237 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02002238}
2239
Christopher Faulet30548802015-06-11 13:39:32 +02002240/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002241 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002242SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002243ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002244{
2245 struct lru64 *lru = NULL;
2246
2247 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002248 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002249 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002250 if (lru && lru->domain) {
2251 if (ssl)
2252 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002253 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002254 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002255 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002256 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002257 }
2258 return NULL;
2259}
2260
Emeric Brun821bb9b2017-06-15 16:37:39 +02002261/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2262 * function is not thread-safe, it should only be used to check if a certificate
2263 * exists in the lru cache (with no warranty it will not be removed by another
2264 * thread). It is kept for backward compatibility. */
2265SSL_CTX *
2266ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2267{
2268 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2269}
2270
Christopher Fauletd2cab922015-07-28 16:03:47 +02002271/* Set a certificate int the LRU cache used to store generated
2272 * certificate. Return 0 on success, otherwise -1 */
2273int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002274ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002275{
2276 struct lru64 *lru = NULL;
2277
2278 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002279 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002280 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002281 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002282 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002283 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002284 }
Christopher Faulet30548802015-06-11 13:39:32 +02002285 if (lru->domain && lru->data)
2286 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002287 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002288 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002289 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002290 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002291 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002292}
2293
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002294/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002295unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002296ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002297{
2298 return XXH32(data, len, ssl_ctx_lru_seed);
2299}
2300
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002301/* Generate a cert and immediately assign it to the SSL session so that the cert's
2302 * refcount is maintained regardless of the cert's presence in the LRU cache.
2303 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002304static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002305ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002306{
Shimi Gersner5846c492020-08-23 13:58:12 +03002307 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002308 SSL_CTX *ssl_ctx = NULL;
2309 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002310 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002311
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002312 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002313 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002314 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002315 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002316 if (lru && lru->domain)
2317 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002318 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002319 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002320 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002321 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002322 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002323 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002324 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002325 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002326 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002327 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002328 SSL_set_SSL_CTX(ssl, ssl_ctx);
2329 /* No LRU cache, this CTX will be released as soon as the session dies */
2330 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002331 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002332 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002333 return 0;
2334}
2335static int
2336ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2337{
2338 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002339 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002340
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002341 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002342 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002343 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002344 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002345 }
2346 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002347}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002348#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002349
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002350#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002351
2352static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002353{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002354#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002355 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002356 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2357#endif
2358}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002359static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2360 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002361 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2362}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002363static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002364#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002365 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002366 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2367#endif
2368}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002369static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002370#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002371 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002372 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2373#endif
2374}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002375/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002376static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2377/* Unusable in this context. */
2378static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2379static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2380static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2381static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2382static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002383#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002384
2385static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2386 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002387 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2388}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002389static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2390 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2391 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2392}
2393static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2394 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002395 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2396}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002397static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2398 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2399 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2400}
2401static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2402 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002403 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2404}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002405static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2406 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2407 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2408}
2409static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2410 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002411 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2412}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002413static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2414 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2415 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2416}
2417static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002418#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002419 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002420 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2421#endif
2422}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002423static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002424#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002425 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2426 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002427#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002428}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002429#endif
2430static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2431static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002432
William Lallemand7fd8b452020-05-07 15:20:43 +02002433struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002434 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2435 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2436 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2437 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2438 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2439 {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 +02002440};
2441
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002442static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2443{
2444 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2445 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2446 SSL_set_SSL_CTX(ssl, ctx);
2447}
2448
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002449#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002450
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002451int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002452{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002453 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002454 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002455
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002456 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2457 return SSL_TLSEXT_ERR_OK;
2458 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002459}
2460
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002461#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002462int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002463{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002464 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002465#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002466int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002467{
2468#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002469 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2470#ifdef USE_QUIC
2471 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2472#endif /* USE_QUIC */
2473 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002474 const uint8_t *extension_data;
2475 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002476 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002477
2478 char *wildp = NULL;
2479 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002480 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002481 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002482 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002483 int i;
2484
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002485 if (conn)
2486 s = __objt_listener(conn->target)->bind_conf;
2487#ifdef USE_QUIC
2488 else if (qc)
2489 s = qc->li->bind_conf;
2490#endif /* USE_QUIC */
2491 BUG_ON(!s);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002492
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002493#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002494 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002495 /* Look for the QUIC transport parameters. */
2496#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002497 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002498 &extension_data, &extension_len))
2499#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002500 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002501 &extension_data, &extension_len))
2502#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002503 {
2504 /* This is not redundant. It we only return 0 without setting
2505 * <*al>, this has as side effect to generate another TLS alert
2506 * which would be set after calling quic_set_tls_alert().
2507 */
2508 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002509 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002510 return 0;
2511 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002512
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002513 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002514 extension_data + extension_len))
2515 goto abort;
Frédéric Lécaille0faf8072021-03-18 15:05:18 +01002516
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002517 quic_mux_transport_params_update(qc->qcc);
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002518 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002519#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002520
Olivier Houchard9679ac92017-10-27 14:58:08 +02002521 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002522 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002523#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002524 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2525 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002526#else
2527 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2528#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002529 /*
2530 * The server_name extension was given too much extensibility when it
2531 * was written, so parsing the normal case is a bit complex.
2532 */
2533 size_t len;
2534 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002535 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002536 /* Extract the length of the supplied list of names. */
2537 len = (*extension_data++) << 8;
2538 len |= *extension_data++;
2539 if (len + 2 != extension_len)
2540 goto abort;
2541 /*
2542 * The list in practice only has a single element, so we only consider
2543 * the first one.
2544 */
2545 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2546 goto abort;
2547 extension_len = len - 1;
2548 /* Now we can finally pull out the byte array with the actual hostname. */
2549 if (extension_len <= 2)
2550 goto abort;
2551 len = (*extension_data++) << 8;
2552 len |= *extension_data++;
2553 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2554 || memchr(extension_data, 0, len) != NULL)
2555 goto abort;
2556 servername = extension_data;
2557 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002558 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002559#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2560 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002561 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002562 }
2563#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002564 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002565 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002566 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002567 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002568 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002569 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002570 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002571 goto abort;
2572 }
2573
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002574 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002575#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002576 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002577#else
2578 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2579#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002580 uint8_t sign;
2581 size_t len;
2582 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002583 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002584 len = (*extension_data++) << 8;
2585 len |= *extension_data++;
2586 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002587 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002588 if (len % 2 != 0)
2589 goto abort;
2590 for (; len > 0; len -= 2) {
2591 extension_data++; /* hash */
2592 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002593 switch (sign) {
2594 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002595 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002596 break;
2597 case TLSEXT_signature_ecdsa:
2598 has_ecdsa_sig = 1;
2599 break;
2600 default:
2601 continue;
2602 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002603 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002604 break;
2605 }
2606 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002607 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002608 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002609 }
2610 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002611 const SSL_CIPHER *cipher;
2612 size_t len;
2613 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002614 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002615#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002616 len = ctx->cipher_suites_len;
2617 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002618#else
2619 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2620#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002621 if (len % 2 != 0)
2622 goto abort;
2623 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002624#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002625 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002626 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002627#else
2628 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2629#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002630 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002631 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002632 break;
2633 }
2634 }
2635 }
2636
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002637 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002638 trash.area[i] = tolower(servername[i]);
2639 if (!wildp && (trash.area[i] == '.'))
2640 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002641 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002642 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002643
William Lallemand150bfa82019-09-19 17:12:49 +02002644 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002645
William Lallemand94bd3192020-08-14 14:43:35 +02002646 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2647 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002648 for (i = 0; i < 2; i++) {
2649 if (i == 0) /* lookup in full qualified names */
2650 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002651 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002652 node = ebst_lookup(&s->sni_w_ctx, wildp);
2653 else
2654 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002655
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002656 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002657
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002658 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002659 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002660 struct sni_ctx *sni, *sni_tmp;
2661 int skip = 0;
2662
2663 if (i == 1 && wildp) { /* wildcard */
2664 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2665 sni = container_of(n, struct sni_ctx, name);
2666 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002667 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002668 skip = 1;
2669 break;
2670 }
2671 }
2672 if (skip)
2673 continue;
2674 }
2675
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002676 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002677 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002678 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002679 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002680 break;
2681 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002682 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002683 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002684 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002685 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002686 if (!node_anonymous)
2687 node_anonymous = n;
2688 break;
2689 }
2690 }
2691 }
William Lallemand94bd3192020-08-14 14:43:35 +02002692 }
2693 /* Once the certificates are found, select them depending on what is
2694 * supported in the client and by key_signature priority order: EDSA >
2695 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002696 if (has_ecdsa_sig && node_ecdsa)
2697 node = node_ecdsa;
2698 else if (has_rsa_sig && node_rsa)
2699 node = node_rsa;
2700 else if (node_anonymous)
2701 node = node_anonymous;
2702 else if (node_ecdsa)
2703 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2704 else
2705 node = node_rsa; /* no rsa signature case (far far away) */
2706
William Lallemand94bd3192020-08-14 14:43:35 +02002707 if (node) {
2708 /* switch ctx */
2709 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2710 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2711 if (conf) {
2712 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2713 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2714 if (conf->early_data)
2715 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002716 }
William Lallemand94bd3192020-08-14 14:43:35 +02002717 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2718 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002719 }
William Lallemand150bfa82019-09-19 17:12:49 +02002720
William Lallemand02010472019-10-18 11:02:19 +02002721 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002722#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002723 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002724 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002725 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002726 }
2727#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002728 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002729 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002730 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002731 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002732 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002733 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002734 }
William Lallemand7980dff2021-11-18 17:46:26 +01002735
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002736 /* We are about to raise an handshake error so the servername extension
2737 * callback will never be called and the SNI will never be stored in the
2738 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2739 * in such a case, we store the SNI ourselves as an ex_data information
2740 * in the SSL context.
2741 */
2742 {
2743 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2744 if (client_sni) {
2745 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2746 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2747 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2748 }
2749 }
2750
William Lallemand7980dff2021-11-18 17:46:26 +01002751 /* other cases fallback on abort, if strict-sni is set but no node was found */
2752
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002753 abort:
2754 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002755 if (conn)
2756 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002757#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002758 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002759#else
2760 *al = SSL_AD_UNRECOGNIZED_NAME;
2761 return 0;
2762#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002763
2764allow_early:
2765#ifdef OPENSSL_IS_BORINGSSL
2766 if (allow_early)
2767 SSL_set_early_data_enabled(ssl, 1);
2768#else
2769 if (!allow_early)
2770 SSL_set_max_early_data(ssl, 0);
2771#endif
2772 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002773}
2774
William Lallemand002e2062021-11-18 15:25:16 +01002775#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002776
Emeric Brunfc0421f2012-09-07 17:30:07 +02002777/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2778 * warning when no match is found, which implies the default (first) cert
2779 * will keep being used.
2780 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002781static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002782{
2783 const char *servername;
2784 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002785 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002786 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002787 int i;
2788 (void)al; /* shut gcc stupid warning */
2789
2790 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002791 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002792#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002793 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2794 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002795#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002796 if (s->strict_sni)
2797 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002798 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002799 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002800 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002801 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002802 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002803
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002804 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002805 if (!servername[i])
2806 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002807 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002808 if (!wildp && (trash.area[i] == '.'))
2809 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002810 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002811 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002812
William Lallemand150bfa82019-09-19 17:12:49 +02002813 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002814 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002815 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002816 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2817 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002818 if (!container_of(n, struct sni_ctx, name)->neg) {
2819 node = n;
2820 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002821 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002822 }
2823 if (!node && wildp) {
2824 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002825 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2826 /* lookup a not neg filter */
2827 if (!container_of(n, struct sni_ctx, name)->neg) {
2828 node = n;
2829 break;
2830 }
2831 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002832 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002833 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002834#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002835 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2836 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002837 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002838 return SSL_TLSEXT_ERR_OK;
2839 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002840#endif
William Lallemand21724f02019-11-04 17:56:13 +01002841 if (s->strict_sni) {
2842 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002843 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002844 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002845 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002846 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002847 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002848 }
2849
2850 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002851 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002852 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002853 return SSL_TLSEXT_ERR_OK;
2854}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002855#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002856#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2857
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002858#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002859
2860static DH * ssl_get_dh_1024(void)
2861{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002862 static unsigned char dh1024_p[]={
2863 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2864 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2865 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2866 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2867 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2868 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2869 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2870 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2871 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2872 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2873 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2874 };
2875 static unsigned char dh1024_g[]={
2876 0x02,
2877 };
2878
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002879 BIGNUM *p;
2880 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002881 DH *dh = DH_new();
2882 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002883 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2884 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002885
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002886 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002887 DH_free(dh);
2888 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002889 } else {
2890 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002891 }
2892 }
2893 return dh;
2894}
2895
2896static DH *ssl_get_dh_2048(void)
2897{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002898 static unsigned char dh2048_p[]={
2899 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2900 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2901 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2902 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2903 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2904 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2905 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2906 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2907 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2908 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2909 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2910 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2911 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2912 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2913 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2914 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2915 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2916 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2917 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2918 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2919 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2920 0xB7,0x1F,0x77,0xF3,
2921 };
2922 static unsigned char dh2048_g[]={
2923 0x02,
2924 };
2925
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002926 BIGNUM *p;
2927 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002928 DH *dh = DH_new();
2929 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002930 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2931 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002932
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002933 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002934 DH_free(dh);
2935 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002936 } else {
2937 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002938 }
2939 }
2940 return dh;
2941}
2942
2943static DH *ssl_get_dh_4096(void)
2944{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002945 static unsigned char dh4096_p[]={
2946 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2947 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2948 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2949 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2950 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2951 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2952 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2953 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2954 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2955 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2956 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2957 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2958 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2959 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2960 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2961 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2962 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2963 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2964 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2965 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2966 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2967 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2968 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2969 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2970 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2971 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2972 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2973 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2974 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2975 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2976 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2977 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2978 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2979 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2980 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2981 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2982 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2983 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2984 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2985 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2986 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2987 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2988 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002989 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002990 static unsigned char dh4096_g[]={
2991 0x02,
2992 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002993
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002994 BIGNUM *p;
2995 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002996 DH *dh = DH_new();
2997 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002998 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2999 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02003000
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003001 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003002 DH_free(dh);
3003 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003004 } else {
3005 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003006 }
3007 }
3008 return dh;
3009}
3010
3011/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01003012 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003013static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
3014{
3015 DH *dh = NULL;
3016 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003017 int type;
3018
3019 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003020
3021 /* The keylen supplied by OpenSSL can only be 512 or 1024.
3022 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
3023 */
3024 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
3025 keylen = EVP_PKEY_bits(pkey);
3026 }
3027
Willy Tarreauef934602016-12-22 23:12:01 +01003028 if (keylen > global_ssl.default_dh_param) {
3029 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003030 }
3031
Remi Gacogned3a341a2015-05-29 16:26:17 +02003032 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02003033 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003034 }
3035 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02003036 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003037 }
3038 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02003039 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003040 }
3041
3042 return dh;
3043}
3044
Remi Gacogne47783ef2015-05-29 15:53:22 +02003045static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003046{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003047 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003048 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003049
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003050 if (in == NULL)
3051 goto end;
3052
Remi Gacogne47783ef2015-05-29 15:53:22 +02003053 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003054 goto end;
3055
Remi Gacogne47783ef2015-05-29 15:53:22 +02003056 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
3057
3058end:
3059 if (in)
3060 BIO_free(in);
3061
Emeric Brune1b4ed42018-08-16 15:14:12 +02003062 ERR_clear_error();
3063
Remi Gacogne47783ef2015-05-29 15:53:22 +02003064 return dh;
3065}
3066
3067int ssl_sock_load_global_dh_param_from_file(const char *filename)
3068{
3069 global_dh = ssl_sock_get_dh_from_file(filename);
3070
3071 if (global_dh) {
3072 return 0;
3073 }
3074
3075 return -1;
3076}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003077#endif
3078
William Lallemand9117de92019-10-04 00:29:42 +02003079/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003080static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003081 struct bind_conf *s, struct ssl_bind_conf *conf,
3082 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003083{
3084 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003085 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003086
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003087 if (*name == '!') {
3088 neg = 1;
3089 name++;
3090 }
3091 if (*name == '*') {
3092 wild = 1;
3093 name++;
3094 }
3095 /* !* filter is a nop */
3096 if (neg && wild)
3097 return order;
3098 if (*name) {
3099 int j, len;
3100 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003101 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003102 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003103 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003104 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003105 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003106
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003107 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003108 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003109 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003110 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003111 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003112 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003113 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003114 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003115 sc->order = order++;
3116 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003117 sc->wild = wild;
3118 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003119 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003120 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003121 }
3122 return order;
3123}
3124
William Lallemand6af03992019-07-23 15:00:54 +02003125/*
William Lallemand1d29c742019-10-04 00:53:29 +02003126 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3127 * This function can't return an error.
3128 *
3129 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3130 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003131void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003132{
3133
3134 struct sni_ctx *sc0, *sc0b, *sc1;
3135 struct ebmb_node *node;
3136
3137 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3138
3139 /* ignore if sc0 was already inserted in a tree */
3140 if (sc0->name.node.leaf_p)
3141 continue;
3142
3143 /* Check for duplicates. */
3144 if (sc0->wild)
3145 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3146 else
3147 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3148
3149 for (; node; node = ebmb_next_dup(node)) {
3150 sc1 = ebmb_entry(node, struct sni_ctx, name);
3151 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3152 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3153 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003154 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003155 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003156 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003157 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003158 }
3159 }
3160
3161 /* if duplicate, ignore the insertion */
3162 if (!sc0)
3163 continue;
3164
3165 if (sc0->wild)
3166 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3167 else
3168 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003169 }
William Lallemand21724f02019-11-04 17:56:13 +01003170
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003171 /* replace the default_ctx if required with the instance's ctx. */
3172 if (ckch_inst->is_default) {
3173 SSL_CTX_free(bind_conf->default_ctx);
3174 SSL_CTX_up_ref(ckch_inst->ctx);
3175 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003176 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003177 }
3178}
3179
3180/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003181 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003182 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003183struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003184
William Lallemand2954c472020-03-06 21:54:13 +01003185/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003186struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003187
Emeric Brun7a883362019-10-17 13:27:40 +02003188/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003189 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003190 * DH parameter is loaded into the SSL_CTX and if there is no
3191 * DH parameter available in ckchs nor in global, the default
3192 * DH parameters are applied on the SSL_CTX.
3193 * Returns a bitfield containing the flags:
3194 * ERR_FATAL in any fatal error case
3195 * ERR_ALERT if a reason of the error is availabine in err
3196 * ERR_WARN if a warning is available into err
3197 * The value 0 means there is no error nor warning and
3198 * the operation succeed.
3199 */
William Lallemandfa892222019-07-23 16:06:08 +02003200#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02003201static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
3202 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003203{
Emeric Brun7a883362019-10-17 13:27:40 +02003204 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02003205 DH *dh = NULL;
3206
William Lallemanda8c73742019-07-31 18:31:34 +02003207 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02003208 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02003209 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
3210 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3211 err && *err ? *err : "", path);
3212#if defined(SSL_CTX_set_dh_auto)
3213 SSL_CTX_set_dh_auto(ctx, 1);
3214 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3215 err && *err ? *err : "");
3216#else
3217 memprintf(err, "%s, DH ciphers won't be available.\n",
3218 err && *err ? *err : "");
3219#endif
3220 ret |= ERR_WARN;
3221 goto end;
3222 }
William Lallemandfa892222019-07-23 16:06:08 +02003223
3224 if (ssl_dh_ptr_index >= 0) {
3225 /* store a pointer to the DH params to avoid complaining about
3226 ssl-default-dh-param not being set for this SSL_CTX */
3227 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3228 }
3229 }
3230 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003231 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
3232 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3233 err && *err ? *err : "", path);
3234#if defined(SSL_CTX_set_dh_auto)
3235 SSL_CTX_set_dh_auto(ctx, 1);
3236 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3237 err && *err ? *err : "");
3238#else
3239 memprintf(err, "%s, DH ciphers won't be available.\n",
3240 err && *err ? *err : "");
3241#endif
3242 ret |= ERR_WARN;
3243 goto end;
3244 }
William Lallemandfa892222019-07-23 16:06:08 +02003245 }
3246 else {
3247 /* Clear openssl global errors stack */
3248 ERR_clear_error();
3249
Willy Tarreau6d27a922020-11-05 19:38:05 +01003250 if (global_ssl.default_dh_param && global_ssl.default_dh_param <= 1024) {
William Lallemandfa892222019-07-23 16:06:08 +02003251 /* we are limited to DH parameter of 1024 bits anyway */
3252 if (local_dh_1024 == NULL)
3253 local_dh_1024 = ssl_get_dh_1024();
3254
Emeric Brun7a883362019-10-17 13:27:40 +02003255 if (local_dh_1024 == NULL) {
3256 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3257 err && *err ? *err : "", path);
3258 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02003259 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02003260 }
William Lallemandfa892222019-07-23 16:06:08 +02003261
Emeric Bruna9363eb2019-10-17 14:53:03 +02003262 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
3263 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3264 err && *err ? *err : "", path);
3265#if defined(SSL_CTX_set_dh_auto)
3266 SSL_CTX_set_dh_auto(ctx, 1);
3267 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3268 err && *err ? *err : "");
3269#else
3270 memprintf(err, "%s, DH ciphers won't be available.\n",
3271 err && *err ? *err : "");
3272#endif
3273 ret |= ERR_WARN;
3274 goto end;
3275 }
William Lallemandfa892222019-07-23 16:06:08 +02003276 }
3277 else {
3278 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
3279 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003280 }
3281
William Lallemandf9568fc2019-10-16 18:27:58 +02003282end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003283 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003284 return ret;
3285}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003286#endif
William Lallemandfa892222019-07-23 16:06:08 +02003287
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003288
3289/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003290 * Returns a bitfield containing the flags:
3291 * ERR_FATAL in any fatal error case
3292 * ERR_ALERT if the reason of the error is available in err
3293 * ERR_WARN if a warning is available into err
3294 * The value 0 means there is no error nor warning and
3295 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003296 */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003297static int ssl_sock_load_cert_chain(const char *path, const struct cert_key_and_chain *ckch,
3298 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003299{
Emeric Bruna96b5822019-10-17 13:25:14 +02003300 int errcode = 0;
3301
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003302 if (find_chain == NULL) {
3303 errcode |= ERR_FATAL;
3304 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003305 }
3306
3307 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3308 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3309 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003310 errcode |= ERR_ALERT | ERR_FATAL;
3311 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003312 }
3313
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003314 if (ckch->chain) {
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003315 *find_chain = ckch->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003316 } else {
3317 /* Find Certificate Chain in global */
3318 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003319 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003320 if (issuer)
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003321 *find_chain = issuer->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003322 }
William Lallemand85888572020-02-27 14:48:35 +01003323
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003324 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003325 /* always put a null chain stack in the SSL_CTX so it does not
3326 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003327 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003328 }
3329
William Lallemandf187ce62020-06-02 18:27:20 +02003330 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003331#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003332 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand935d8292020-08-12 20:02:10 +02003333 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3334 err && *err ? *err : "", path);
3335 errcode |= ERR_ALERT | ERR_FATAL;
3336 goto end;
3337 }
William Lallemandf187ce62020-06-02 18:27:20 +02003338#else
3339 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003340 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02003341 STACK_OF(X509) *chain;
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003342 chain = X509_chain_up_ref(*find_chain);
William Lallemandf187ce62020-06-02 18:27:20 +02003343 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003344 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003345 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3346 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003347 X509_free(ca);
3348 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003349 errcode |= ERR_ALERT | ERR_FATAL;
3350 goto end;
3351 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003352 }
William Lallemandf187ce62020-06-02 18:27:20 +02003353#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003354
William Lallemand9a1d8392020-08-10 17:28:23 +02003355#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003356 /* remove the Root CA from the SSL_CTX if the option is activated */
3357 if (global_ssl.skip_self_issued_ca) {
3358 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3359 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3360 err && *err ? *err : "", path);
3361 errcode |= ERR_ALERT | ERR_FATAL;
3362 goto end;
3363 }
3364 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003365#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003366
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003367end:
3368 return errcode;
3369}
3370
3371
3372/* Loads the info in ckch into ctx
3373 * Returns a bitfield containing the flags:
3374 * ERR_FATAL in any fatal error case
3375 * ERR_ALERT if the reason of the error is available in err
3376 * ERR_WARN if a warning is available into err
3377 * The value 0 means there is no error nor warning and
3378 * the operation succeed.
3379 */
3380static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3381{
3382 int errcode = 0;
3383 STACK_OF(X509) *find_chain = NULL;
3384
3385 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3386 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3387 err && *err ? *err : "", path);
3388 errcode |= ERR_ALERT | ERR_FATAL;
3389 return errcode;
3390 }
3391
3392 /* Load certificate chain */
3393 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3394 if (errcode & ERR_CODE)
3395 goto end;
3396
William Lallemandfa892222019-07-23 16:06:08 +02003397#ifndef OPENSSL_NO_DH
3398 /* store a NULL pointer to indicate we have not yet loaded
3399 a custom DH param file */
3400 if (ssl_dh_ptr_index >= 0) {
3401 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3402 }
3403
Emeric Brun7a883362019-10-17 13:27:40 +02003404 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3405 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003406 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3407 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003408 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003409 }
3410#endif
3411
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003412#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003413 if (sctl_ex_index >= 0 && ckch->sctl) {
3414 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3415 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003416 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003417 errcode |= ERR_ALERT | ERR_FATAL;
3418 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003419 }
3420 }
3421#endif
3422
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003423#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003424 /* Load OCSP Info into context */
3425 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003426 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003427 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",
3428 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003429 errcode |= ERR_ALERT | ERR_FATAL;
3430 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003431 }
3432 }
William Lallemand246c0242019-10-11 08:59:13 +02003433#endif
3434
Emeric Bruna96b5822019-10-17 13:25:14 +02003435 end:
3436 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003437}
3438
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003439
3440/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3441 * Returns a bitfield containing the flags:
3442 * ERR_FATAL in any fatal error case
3443 * ERR_ALERT if the reason of the error is available in err
3444 * ERR_WARN if a warning is available into err
3445 * The value 0 means there is no error nor warning and
3446 * the operation succeed.
3447 */
3448static int ssl_sock_put_srv_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch,
3449 SSL_CTX *ctx, char **err)
3450{
3451 int errcode = 0;
3452 STACK_OF(X509) *find_chain = NULL;
3453
3454 /* Load the private key */
3455 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3456 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3457 err && *err ? *err : "", path);
3458 errcode |= ERR_ALERT | ERR_FATAL;
3459 }
3460
3461 /* Load certificate chain */
3462 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3463 if (errcode & ERR_CODE)
3464 goto end;
3465
3466 if (SSL_CTX_check_private_key(ctx) <= 0) {
3467 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3468 err && *err ? *err : "", path);
3469 errcode |= ERR_ALERT | ERR_FATAL;
3470 }
3471
3472end:
3473 return errcode;
3474}
3475
3476
William Lallemand614ca0d2019-10-07 13:52:11 +02003477/*
3478 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003479 *
3480 * Returns a bitfield containing the flags:
3481 * ERR_FATAL in any fatal error case
3482 * ERR_ALERT if the reason of the error is available in err
3483 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003484 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003485int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003486 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003487{
William Lallemandc9402072019-05-15 15:33:54 +02003488 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003489 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003490 int order = 0;
3491 X509_NAME *xname;
3492 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003493 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003494 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003495#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3496 STACK_OF(GENERAL_NAME) *names;
3497#endif
William Lallemand36b84632019-07-18 19:28:17 +02003498 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003499 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003500 int errcode = 0;
3501
3502 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003503
William Lallemande3af8fb2019-10-08 11:36:53 +02003504 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003505 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003506
William Lallemande3af8fb2019-10-08 11:36:53 +02003507 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003508
William Lallemandc9402072019-05-15 15:33:54 +02003509 ctx = SSL_CTX_new(SSLv23_server_method());
3510 if (!ctx) {
3511 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3512 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003513 errcode |= ERR_ALERT | ERR_FATAL;
3514 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003515 }
3516
Emeric Bruna96b5822019-10-17 13:25:14 +02003517 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3518 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003519 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003520
3521 ckch_inst = ckch_inst_new();
3522 if (!ckch_inst) {
3523 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3524 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003525 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003526 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003527 }
3528
William Lallemand36b84632019-07-18 19:28:17 +02003529 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003530 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003531 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003532 switch(EVP_PKEY_base_id(pkey)) {
3533 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003534 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003535 break;
3536 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003537 kinfo.sig = TLSEXT_signature_ecdsa;
3538 break;
3539 case EVP_PKEY_DSA:
3540 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003541 break;
3542 }
3543 EVP_PKEY_free(pkey);
3544 }
3545
Emeric Brun50bcecc2013-04-22 13:05:23 +02003546 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003547 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003548 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 +02003549 if (order < 0) {
3550 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003551 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003552 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003553 }
3554 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003555 }
3556 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003557#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003558 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003559 if (names) {
3560 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3561 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3562 if (name->type == GEN_DNS) {
3563 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003564 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003565 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003566 if (order < 0) {
3567 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003568 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003569 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003570 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003571 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003572 }
3573 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003574 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003575 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003576#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003577 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003578 i = -1;
3579 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3580 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003581 ASN1_STRING *value;
3582
3583 value = X509_NAME_ENTRY_get_data(entry);
3584 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003585 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003586 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003587 if (order < 0) {
3588 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003589 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003590 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003591 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003592 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003593 }
3594 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003595 /* we must not free the SSL_CTX anymore below, since it's already in
3596 * the tree, so it will be discovered and cleaned in time.
3597 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003598
Emeric Brunfc0421f2012-09-07 17:30:07 +02003599#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003600 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003601 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3602 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003603 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003604 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003605 }
3606#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003607 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003608 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003609 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003610 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003611 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003612 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003613 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003614
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003615 /* Always keep a reference to the newly constructed SSL_CTX in the
3616 * instance. This way if the instance has no SNIs, the SSL_CTX will
3617 * still be linked. */
3618 SSL_CTX_up_ref(ctx);
3619 ckch_inst->ctx = ctx;
3620
William Lallemand9117de92019-10-04 00:29:42 +02003621 /* everything succeed, the ckch instance can be used */
3622 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003623 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003624 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003625
William Lallemand02e19a52020-04-08 16:11:26 +02003626 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3627
Emeric Brun054563d2019-10-17 13:16:58 +02003628 *ckchi = ckch_inst;
3629 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003630
3631error:
3632 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003633 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003634 if (ckch_inst->is_default)
3635 SSL_CTX_free(ctx);
3636
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003637 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003638 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003639 }
William Lallemandd9199372019-10-04 15:37:05 +02003640 SSL_CTX_free(ctx);
3641
Emeric Brun054563d2019-10-17 13:16:58 +02003642 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003643}
3644
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003645
3646/*
3647 * This function allocate a ckch_inst that will be used on the backend side
3648 * (server line)
3649 *
3650 * Returns a bitfield containing the flags:
3651 * ERR_FATAL in any fatal error case
3652 * ERR_ALERT if the reason of the error is available in err
3653 * ERR_WARN if a warning is available into err
3654 */
3655int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003656 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003657{
3658 SSL_CTX *ctx;
3659 struct cert_key_and_chain *ckch;
3660 struct ckch_inst *ckch_inst = NULL;
3661 int errcode = 0;
3662
3663 *ckchi = NULL;
3664
3665 if (!ckchs || !ckchs->ckch)
3666 return ERR_FATAL;
3667
3668 ckch = ckchs->ckch;
3669
3670 ctx = SSL_CTX_new(SSLv23_client_method());
3671 if (!ctx) {
3672 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3673 err && *err ? *err : "", path);
3674 errcode |= ERR_ALERT | ERR_FATAL;
3675 goto error;
3676 }
3677
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003678 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, ckch, ctx, err);
3679 if (errcode & ERR_CODE)
3680 goto error;
3681
3682 ckch_inst = ckch_inst_new();
3683 if (!ckch_inst) {
3684 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3685 err && *err ? *err : "", path);
3686 errcode |= ERR_ALERT | ERR_FATAL;
3687 goto error;
3688 }
3689
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003690 /* everything succeed, the ckch instance can be used */
3691 ckch_inst->bind_conf = NULL;
3692 ckch_inst->ssl_conf = NULL;
3693 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003694 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003695 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003696
3697 *ckchi = ckch_inst;
3698 return errcode;
3699
3700error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003701 SSL_CTX_free(ctx);
3702
3703 return errcode;
3704}
3705
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003706/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003707static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3708 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003709 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003710{
Emeric Brun054563d2019-10-17 13:16:58 +02003711 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003712
3713 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003714 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 +02003715
Emeric Brun054563d2019-10-17 13:16:58 +02003716 if (errcode & ERR_CODE)
3717 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003718
William Lallemand24bde432020-03-09 16:48:43 +01003719 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003720
3721 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003722 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003723 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003724}
3725
William Lallemanddb26e2b2021-01-26 12:01:46 +01003726/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3727 * fill the SSL_CTX of the server.
3728 *
3729 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003730static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003731 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003732{
3733 int errcode = 0;
3734
3735 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003736 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003737
3738 if (errcode & ERR_CODE)
3739 return errcode;
3740
William Lallemanddb26e2b2021-01-26 12:01:46 +01003741 (*ckch_inst)->server = server;
3742 /* Keep the reference to the SSL_CTX in the server. */
3743 SSL_CTX_up_ref((*ckch_inst)->ctx);
3744 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003745 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003746 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003747 return errcode;
3748}
3749
William Lallemand6be66ec2020-03-06 22:26:32 +01003750
William Lallemand4c68bba2020-03-30 18:45:10 +02003751
3752
3753/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3754 * done once. Zero is returned if the operation fails. No error is returned
3755 * if the random is said as not implemented, because we expect that openssl
3756 * will use another method once needed.
3757 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02003758int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02003759{
3760 unsigned char random;
3761 static int random_initialized = 0;
3762
3763 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3764 random_initialized = 1;
3765
3766 return random_initialized;
3767}
3768
William Lallemand2954c472020-03-06 21:54:13 +01003769/* Load a crt-list file, this is done in 2 parts:
3770 * - store the content of the file in a crtlist structure with crtlist_entry structures
3771 * - generate the instances by iterating on entries in the crtlist struct
3772 *
3773 * Nothing is locked there, this function is used in the configuration parser.
3774 *
3775 * Returns a set of ERR_* flags possibly with an error in <err>.
3776 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003777int 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 +01003778{
3779 struct crtlist *crtlist = NULL;
3780 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003781 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003782 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003783 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003784 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003785
William Lallemand79d31ec2020-03-25 15:10:49 +01003786 bind_conf_node = malloc(sizeof(*bind_conf_node));
3787 if (!bind_conf_node) {
3788 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3789 cfgerr |= ERR_FATAL | ERR_ALERT;
3790 goto error;
3791 }
3792 bind_conf_node->next = NULL;
3793 bind_conf_node->bind_conf = bind_conf;
3794
William Lallemand41ca9302020-04-08 13:15:18 +02003795 /* strip trailing slashes, including first one */
3796 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3797 *end = 0;
3798
William Lallemand2954c472020-03-06 21:54:13 +01003799 /* look for an existing crtlist or create one */
3800 eb = ebst_lookup(&crtlists_tree, file);
3801 if (eb) {
3802 crtlist = ebmb_entry(eb, struct crtlist, node);
3803 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003804 /* load a crt-list OR a directory */
3805 if (dir)
3806 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3807 else
3808 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3809
William Lallemand2954c472020-03-06 21:54:13 +01003810 if (!(cfgerr & ERR_CODE))
3811 ebst_insert(&crtlists_tree, &crtlist->node);
3812 }
3813
3814 if (cfgerr & ERR_CODE) {
3815 cfgerr |= ERR_FATAL | ERR_ALERT;
3816 goto error;
3817 }
3818
3819 /* generates ckch instance from the crtlist_entry */
3820 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3821 struct ckch_store *store;
3822 struct ckch_inst *ckch_inst = NULL;
3823
3824 store = entry->node.key;
3825 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3826 if (cfgerr & ERR_CODE) {
3827 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3828 goto error;
3829 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003830 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003831 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003832 }
William Lallemand2954c472020-03-06 21:54:13 +01003833
William Lallemand79d31ec2020-03-25 15:10:49 +01003834 /* add the bind_conf to the list */
3835 bind_conf_node->next = crtlist->bind_conf;
3836 crtlist->bind_conf = bind_conf_node;
3837
William Lallemand2954c472020-03-06 21:54:13 +01003838 return cfgerr;
3839error:
3840 {
William Lallemand49398312020-03-30 17:01:33 +02003841 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003842 struct ckch_inst *inst, *s_inst;
3843
William Lallemand49398312020-03-30 17:01:33 +02003844 lastentry = entry; /* which entry we tried to generate last */
3845 if (lastentry) {
3846 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3847 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3848 break;
3849
3850 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003851
William Lallemand49398312020-03-30 17:01:33 +02003852 /* this was not generated for this bind_conf, skip */
3853 if (inst->bind_conf != bind_conf)
3854 continue;
3855
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003856 /* free the sni_ctx and instance */
3857 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003858 }
William Lallemand2954c472020-03-06 21:54:13 +01003859 }
William Lallemand2954c472020-03-06 21:54:13 +01003860 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003861 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003862 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003863 return cfgerr;
3864}
3865
William Lallemand06b22a82020-03-16 14:45:55 +01003866/* Returns a set of ERR_* flags possibly with an error in <err>. */
3867int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3868{
3869 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003870 int cfgerr = 0;
3871 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003872 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003873 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003874
3875 if ((ckchs = ckchs_lookup(path))) {
3876 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003877 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3878 found++;
3879 } else if (stat(path, &buf) == 0) {
3880 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003881 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003882 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003883 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003884 cfgerr |= ERR_ALERT | ERR_FATAL;
3885 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003886 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003887 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003888 }
3889 } else {
3890 /* stat failed, could be a bundle */
3891 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003892 char fp[MAXPATHLEN+1] = {0};
3893 int n = 0;
3894
3895 /* Load all possible certs and keys in separate ckch_store */
3896 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3897 struct stat buf;
3898 int ret;
3899
3900 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3901 if (ret > sizeof(fp))
3902 continue;
3903
3904 if ((ckchs = ckchs_lookup(fp))) {
3905 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003906 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003907 } else {
3908 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003909 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003910 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003911 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003912 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003913 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3914 }
3915 }
3916 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003917#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3918 if (found) {
3919 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3920 err && *err ? *err : "", path);
3921 cfgerr |= ERR_ALERT | ERR_FATAL;
3922 }
3923#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003924 }
3925 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003926 if (!found) {
3927 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3928 err && *err ? *err : "", path, strerror(errno));
3929 cfgerr |= ERR_ALERT | ERR_FATAL;
3930 }
William Lallemand06b22a82020-03-16 14:45:55 +01003931
3932 return cfgerr;
3933}
3934
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003935
3936/* Create a full ssl context and ckch instance that will be used for a specific
3937 * backend server (server configuration line).
3938 * Returns a set of ERR_* flags possibly with an error in <err>.
3939 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003940int ssl_sock_load_srv_cert(char *path, struct server *server, int create_if_none, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003941{
3942 struct stat buf;
3943 int cfgerr = 0;
3944 struct ckch_store *ckchs;
3945 int found = 0; /* did we found a file to load ? */
3946
3947 if ((ckchs = ckchs_lookup(path))) {
3948 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01003949 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003950 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003951 } else {
3952 if (!create_if_none) {
3953 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
3954 err && *err ? *err : "", path);
3955 cfgerr |= ERR_ALERT | ERR_FATAL;
3956 goto out;
3957 }
3958
3959 if (stat(path, &buf) == 0) {
3960 /* We do not manage directories on backend side. */
3961 if (S_ISDIR(buf.st_mode) == 0) {
3962 ++found;
3963 ckchs = ckchs_load_cert_file(path, err);
3964 if (!ckchs)
3965 cfgerr |= ERR_ALERT | ERR_FATAL;
3966 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
3967 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003968 }
3969 }
3970 if (!found) {
3971 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3972 err && *err ? *err : "", path, strerror(errno));
3973 cfgerr |= ERR_ALERT | ERR_FATAL;
3974 }
3975
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003976out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003977 return cfgerr;
3978}
3979
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003980/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003981static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003982ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003983{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003984 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003985 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003986 SSL_OP_ALL | /* all known workarounds for bugs */
3987 SSL_OP_NO_SSLv2 |
3988 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003989 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003990 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003991 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003992 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003993 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003994 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003995 SSL_MODE_ENABLE_PARTIAL_WRITE |
3996 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003997 SSL_MODE_RELEASE_BUFFERS |
3998 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003999 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004000 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004001 int flags = MC_SSL_O_ALL;
4002 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004003 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004004
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004005 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004006 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004007
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004008 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004009 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4010 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4011 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004012 else
4013 flags = conf_ssl_methods->flags;
4014
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004015 min = conf_ssl_methods->min;
4016 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004017
4018 /* default minimum is TLSV12, */
4019 if (!min) {
4020 if (!max || (max >= default_min_ver)) {
4021 min = default_min_ver;
4022 } else {
4023 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). "
4024 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4025 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4026 min = max;
4027 }
4028 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004029 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004030 if (min)
4031 flags |= (methodVersions[min].flag - 1);
4032 if (max)
4033 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004034 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004035 min = max = CONF_TLSV_NONE;
4036 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004037 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004038 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004039 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004040 if (min) {
4041 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004042 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4043 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4044 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4045 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004046 hole = 0;
4047 }
4048 max = i;
4049 }
4050 else {
4051 min = max = i;
4052 }
4053 }
4054 else {
4055 if (min)
4056 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004057 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004058 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004059 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4060 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004061 cfgerr += 1;
4062 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004063 /* save real min/max in bind_conf */
4064 conf_ssl_methods->min = min;
4065 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004066
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004067#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004068 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004069 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004070 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004071 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004072 else
William Lallemandd0712f32020-06-11 17:34:00 +02004073 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4074 /* clear every version flags in case SSL_CTX_new()
4075 * returns an SSL_CTX with disabled versions */
4076 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4077
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004078 if (flags & methodVersions[i].flag)
4079 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004080
4081 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004082#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004083 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004084 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4085 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004086#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004087
4088 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4089 options |= SSL_OP_NO_TICKET;
4090 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4091 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004092
4093#ifdef SSL_OP_NO_RENEGOTIATION
4094 options |= SSL_OP_NO_RENEGOTIATION;
4095#endif
4096
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004097 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004098
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004099#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004100 if (global_ssl.async)
4101 mode |= SSL_MODE_ASYNC;
4102#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004103 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004104 if (global_ssl.life_time)
4105 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004106
4107#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
4108#ifdef OPENSSL_IS_BORINGSSL
4109 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4110 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05004111#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004112 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004113 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004114 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4115 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004116#else
4117 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004118#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004119 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004120#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004121 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004122}
4123
William Lallemand4f45bb92017-10-30 20:08:51 +01004124
4125static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4126{
4127 if (first == block) {
4128 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4129 if (first->len > 0)
4130 sh_ssl_sess_tree_delete(sh_ssl_sess);
4131 }
4132}
4133
4134/* return first block from sh_ssl_sess */
4135static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4136{
4137 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4138
4139}
4140
4141/* store a session into the cache
4142 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4143 * data: asn1 encoded session
4144 * data_len: asn1 encoded session length
4145 * Returns 1 id session was stored (else 0)
4146 */
4147static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4148{
4149 struct shared_block *first;
4150 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4151
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004152 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004153 if (!first) {
4154 /* Could not retrieve enough free blocks to store that session */
4155 return 0;
4156 }
4157
4158 /* STORE the key in the first elem */
4159 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4160 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4161 first->len = sizeof(struct sh_ssl_sess_hdr);
4162
4163 /* it returns the already existing node
4164 or current node if none, never returns null */
4165 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4166 if (oldsh_ssl_sess != sh_ssl_sess) {
4167 /* NOTE: Row couldn't be in use because we lock read & write function */
4168 /* release the reserved row */
4169 shctx_row_dec_hot(ssl_shctx, first);
4170 /* replace the previous session already in the tree */
4171 sh_ssl_sess = oldsh_ssl_sess;
4172 /* ignore the previous session data, only use the header */
4173 first = sh_ssl_sess_first_block(sh_ssl_sess);
4174 shctx_row_inc_hot(ssl_shctx, first);
4175 first->len = sizeof(struct sh_ssl_sess_hdr);
4176 }
4177
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004178 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004179 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004180 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004181 }
4182
4183 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004184
4185 return 1;
4186}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004187
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004188/* SSL callback used when a new session is created while connecting to a server */
4189static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4190{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004191 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004192 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004193
Willy Tarreau07d94e42018-09-20 10:57:52 +02004194 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004195
William Lallemand3ce6eed2021-02-08 10:43:44 +01004196 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4197 * one cache per thread, it only prevents to flush it from the CLI in
4198 * another thread */
4199
Olivier Houcharde6060c52017-11-16 17:42:52 +01004200 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4201 int len;
4202 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004203 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004204
Olivier Houcharde6060c52017-11-16 17:42:52 +01004205 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004206 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004207 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004208 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4209 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4210 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004211 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4212 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004213 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4214 }
4215 if (s->ssl_ctx.reused_sess[tid].ptr) {
4216 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4217 &ptr);
4218 }
William Lallemande18d4e82021-11-17 02:59:21 +01004219
4220 if (s->ssl_ctx.reused_sess[tid].sni) {
4221 /* if the new sni is empty or isn' t the same as the old one */
4222 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4223 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4224 if (sni)
4225 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4226 }
4227 } else if (sni) {
4228 /* if there wasn't an old sni but there is a new one */
4229 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4230 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004231 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004232 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004233 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004234 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004235 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004236 }
4237
4238 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004239}
4240
Olivier Houcharde6060c52017-11-16 17:42:52 +01004241
William Lallemanded0b5ad2017-10-30 19:36:36 +01004242/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004243int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004244{
4245 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4246 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4247 unsigned char *p;
4248 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004249 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004250 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004251
4252 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004253 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004254 * note: SSL_SESSION_set1_id is using
4255 * a memcpy so we need to use a different pointer
4256 * than sid_data or sid_ctx_data to avoid valgrind
4257 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004258 */
4259
4260 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004261
4262 /* copy value in an other buffer */
4263 memcpy(encid, sid_data, sid_length);
4264
4265 /* pad with 0 */
4266 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4267 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4268
4269 /* force length to zero to avoid ASN1 encoding */
4270 SSL_SESSION_set1_id(sess, encid, 0);
4271
4272 /* force length to zero to avoid ASN1 encoding */
4273 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004274
4275 /* check if buffer is large enough for the ASN1 encoded session */
4276 data_len = i2d_SSL_SESSION(sess, NULL);
4277 if (data_len > SHSESS_MAX_DATA_LEN)
4278 goto err;
4279
4280 p = encsess;
4281
4282 /* process ASN1 session encoding before the lock */
4283 i2d_SSL_SESSION(sess, &p);
4284
William Lallemanded0b5ad2017-10-30 19:36:36 +01004285
William Lallemanda3c77cf2017-10-30 23:44:40 +01004286 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004287 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004288 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004289 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004290err:
4291 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004292 SSL_SESSION_set1_id(sess, encid, sid_length);
4293 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004294
4295 return 0; /* do not increment session reference count */
4296}
4297
4298/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004299SSL_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 +01004300{
William Lallemand4f45bb92017-10-30 20:08:51 +01004301 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004302 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4303 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004304 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004305 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004306
Willy Tarreau4c19e992021-06-15 16:39:22 +02004307 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004308
4309 /* allow the session to be freed automatically by openssl */
4310 *do_copy = 0;
4311
4312 /* tree key is zeros padded sessionid */
4313 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4314 memcpy(tmpkey, key, key_len);
4315 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4316 key = tmpkey;
4317 }
4318
4319 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004320 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004321
4322 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004323 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4324 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004325 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004326 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004327 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004328 return NULL;
4329 }
4330
William Lallemand4f45bb92017-10-30 20:08:51 +01004331 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4332 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004333
William Lallemand4f45bb92017-10-30 20:08:51 +01004334 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 +01004335
William Lallemanda3c77cf2017-10-30 23:44:40 +01004336 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004337
4338 /* decode ASN1 session */
4339 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004340 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004341 /* Reset session id and session id contenxt */
4342 if (sess) {
4343 SSL_SESSION_set1_id(sess, key, key_len);
4344 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4345 }
4346
4347 return sess;
4348}
4349
William Lallemand4f45bb92017-10-30 20:08:51 +01004350
William Lallemanded0b5ad2017-10-30 19:36:36 +01004351/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004352void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004353{
William Lallemand4f45bb92017-10-30 20:08:51 +01004354 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004355 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4356 unsigned int sid_length;
4357 const unsigned char *sid_data;
4358 (void)ctx;
4359
4360 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4361 /* tree key is zeros padded sessionid */
4362 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4363 memcpy(tmpkey, sid_data, sid_length);
4364 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4365 sid_data = tmpkey;
4366 }
4367
William Lallemanda3c77cf2017-10-30 23:44:40 +01004368 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004369
4370 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004371 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4372 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004373 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004374 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004375 }
4376
4377 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004378 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004379}
4380
4381/* Set session cache mode to server and disable openssl internal cache.
4382 * Set shared cache callbacks on an ssl context.
4383 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004384void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004385{
4386 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4387
4388 if (!ssl_shctx) {
4389 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4390 return;
4391 }
4392
4393 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4394 SSL_SESS_CACHE_NO_INTERNAL |
4395 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4396
4397 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004398 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4399 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4400 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004401}
William Lallemand7d42ef52020-07-06 11:41:30 +02004402
4403/*
4404 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4405 *
4406 * The format is:
4407 * * <Label> <space> <ClientRandom> <space> <Secret>
4408 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4409 */
4410
William Lallemand722180a2021-06-09 16:46:12 +02004411#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004412void SSL_CTX_keylog(const SSL *ssl, const char *line)
4413{
4414 struct ssl_keylog *keylog;
4415 char *lastarg = NULL;
4416 char *dst = NULL;
4417
4418 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4419 if (!keylog)
4420 return;
4421
4422 lastarg = strrchr(line, ' ');
4423 if (lastarg == NULL || ++lastarg == NULL)
4424 return;
4425
4426 dst = pool_alloc(pool_head_ssl_keylog_str);
4427 if (!dst)
4428 return;
4429
4430 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4431 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4432
4433 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4434 if (keylog->client_random)
4435 goto error;
4436 keylog->client_random = dst;
4437
4438 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4439 if (keylog->client_early_traffic_secret)
4440 goto error;
4441 keylog->client_early_traffic_secret = dst;
4442
4443 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4444 if(keylog->client_handshake_traffic_secret)
4445 goto error;
4446 keylog->client_handshake_traffic_secret = dst;
4447
4448 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4449 if (keylog->server_handshake_traffic_secret)
4450 goto error;
4451 keylog->server_handshake_traffic_secret = dst;
4452
4453 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4454 if (keylog->client_traffic_secret_0)
4455 goto error;
4456 keylog->client_traffic_secret_0 = dst;
4457
4458 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4459 if (keylog->server_traffic_secret_0)
4460 goto error;
4461 keylog->server_traffic_secret_0 = dst;
4462
4463 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4464 if (keylog->early_exporter_secret)
4465 goto error;
4466 keylog->early_exporter_secret = dst;
4467
4468 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4469 if (keylog->exporter_secret)
4470 goto error;
4471 keylog->exporter_secret = dst;
4472 } else {
4473 goto error;
4474 }
4475
4476 return;
4477
4478error:
4479 pool_free(pool_head_ssl_keylog_str, dst);
4480
4481 return;
4482}
4483#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004484
William Lallemand8b453912019-11-21 15:48:10 +01004485/*
4486 * This function applies the SSL configuration on a SSL_CTX
4487 * It returns an error code and fills the <err> buffer
4488 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004489static int ssl_sock_prepare_ctx(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf, SSL_CTX *ctx, char **err)
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004490{
4491 struct proxy *curproxy = bind_conf->frontend;
4492 int cfgerr = 0;
4493 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004494 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004495 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004496#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004497 const char *conf_ciphersuites;
4498#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004499 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004500
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004501 if (ssl_conf) {
4502 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4503 int i, min, max;
4504 int flags = MC_SSL_O_ALL;
4505
4506 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004507 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4508 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004509 if (min)
4510 flags |= (methodVersions[min].flag - 1);
4511 if (max)
4512 flags |= ~((methodVersions[max].flag << 1) - 1);
4513 min = max = CONF_TLSV_NONE;
4514 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4515 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4516 if (min)
4517 max = i;
4518 else
4519 min = max = i;
4520 }
4521 /* save real min/max */
4522 conf_ssl_methods->min = min;
4523 conf_ssl_methods->max = max;
4524 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004525 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4526 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004527 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004528 }
4529 }
4530
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004531 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004532 case SSL_SOCK_VERIFY_NONE:
4533 verify = SSL_VERIFY_NONE;
4534 break;
4535 case SSL_SOCK_VERIFY_OPTIONAL:
4536 verify = SSL_VERIFY_PEER;
4537 break;
4538 case SSL_SOCK_VERIFY_REQUIRED:
4539 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4540 break;
4541 }
4542 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4543 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004544 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 +01004545 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 +01004546 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 +01004547 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004548 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004549 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004550 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004551 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004552 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004553 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004554 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4555 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4556 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4557 cfgerr |= ERR_ALERT | ERR_FATAL;
4558 }
4559 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004560 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004561 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 +02004562 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004563 }
Emeric Brun850efd52014-01-29 12:24:34 +01004564 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004565 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4566 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004567 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004568 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004569#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004570 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004571 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4572
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004573 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004574 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4575 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004576 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004577 }
Emeric Brun561e5742012-10-02 15:20:55 +02004578 else {
4579 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4580 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004581 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004582#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004583 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004584 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004585#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004586 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004587 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004588 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4589 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004590 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004591 }
4592 }
4593#endif
4594
William Lallemand4f45bb92017-10-30 20:08:51 +01004595 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004596 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4597 if (conf_ciphers &&
4598 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004599 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4600 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004601 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004602 }
4603
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004604#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004605 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4606 if (conf_ciphersuites &&
4607 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004608 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4609 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004610 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004611 }
4612#endif
4613
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004614#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004615 /* If tune.ssl.default-dh-param has not been set,
4616 neither has ssl-default-dh-file and no static DH
4617 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004618 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004619 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004620 (ssl_dh_ptr_index == -1 ||
4621 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004622 /* default to dh-param 2048 */
4623 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004624 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004625
Willy Tarreauef934602016-12-22 23:12:01 +01004626 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004627 if (local_dh_1024 == NULL) {
4628 local_dh_1024 = ssl_get_dh_1024();
4629 }
Willy Tarreauef934602016-12-22 23:12:01 +01004630 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004631 if (local_dh_2048 == NULL) {
4632 local_dh_2048 = ssl_get_dh_2048();
4633 }
Willy Tarreauef934602016-12-22 23:12:01 +01004634 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004635 if (local_dh_4096 == NULL) {
4636 local_dh_4096 = ssl_get_dh_4096();
4637 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004638 }
4639 }
4640 }
4641#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004642
Emeric Brunfc0421f2012-09-07 17:30:07 +02004643 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004644#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004645 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004646#endif
William Lallemand722180a2021-06-09 16:46:12 +02004647#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004648 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
4649#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004650
Bernard Spil13c53f82018-02-15 13:34:58 +01004651#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004652 ssl_conf_cur = NULL;
4653 if (ssl_conf && ssl_conf->npn_str)
4654 ssl_conf_cur = ssl_conf;
4655 else if (bind_conf->ssl_conf.npn_str)
4656 ssl_conf_cur = &bind_conf->ssl_conf;
4657 if (ssl_conf_cur)
4658 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004659#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004660#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004661 ssl_conf_cur = NULL;
4662 if (ssl_conf && ssl_conf->alpn_str)
4663 ssl_conf_cur = ssl_conf;
4664 else if (bind_conf->ssl_conf.alpn_str)
4665 ssl_conf_cur = &bind_conf->ssl_conf;
4666 if (ssl_conf_cur)
4667 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004668#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004669#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004670 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4671 if (conf_curves) {
4672 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004673 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4674 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004675 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004676 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004677 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004678 }
4679#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004680#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004681 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004682 int i;
4683 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004684#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004685 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004686 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4687 NULL);
4688
4689 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004690 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004691 return cfgerr;
4692 }
4693#else
4694 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4695 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4696 ECDHE_DEFAULT_CURVE);
4697#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004698
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004699 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004700 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004701 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4702 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004703 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004704 }
4705 else {
4706 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4707 EC_KEY_free(ecdh);
4708 }
4709 }
4710#endif
4711
Emeric Brunfc0421f2012-09-07 17:30:07 +02004712 return cfgerr;
4713}
4714
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004715
4716/*
4717 * Prepare the SSL_CTX based on the bind line configuration.
4718 * Since the CA file loading is made depending on the verify option of the bind
4719 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4720 * If we want to create a link between the CA file entry and the corresponding
4721 * ckch instance (for CA file hot update), it needs to be done after
4722 * ssl_sock_prepare_ctx.
4723 * Returns 0 in case of success.
4724 */
4725int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4726 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4727{
4728 int errcode = 0;
4729
4730 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4731 if (!errcode && ckch_inst)
4732 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4733
4734 return errcode;
4735}
4736
Evan Broderbe554312013-06-27 00:05:25 -07004737static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4738{
4739 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4740 size_t prefixlen, suffixlen;
4741
4742 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004743 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004744 return 1;
4745
Evan Broderbe554312013-06-27 00:05:25 -07004746 /* The rest of this logic is based on RFC 6125, section 6.4.3
4747 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4748
Emeric Bruna848dae2013-10-08 11:27:28 +02004749 pattern_wildcard = NULL;
4750 pattern_left_label_end = pattern;
4751 while (*pattern_left_label_end != '.') {
4752 switch (*pattern_left_label_end) {
4753 case 0:
4754 /* End of label not found */
4755 return 0;
4756 case '*':
4757 /* If there is more than one wildcards */
4758 if (pattern_wildcard)
4759 return 0;
4760 pattern_wildcard = pattern_left_label_end;
4761 break;
4762 }
4763 pattern_left_label_end++;
4764 }
4765
4766 /* If it's not trivial and there is no wildcard, it can't
4767 * match */
4768 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004769 return 0;
4770
4771 /* Make sure all labels match except the leftmost */
4772 hostname_left_label_end = strchr(hostname, '.');
4773 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004774 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004775 return 0;
4776
4777 /* Make sure the leftmost label of the hostname is long enough
4778 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004779 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004780 return 0;
4781
4782 /* Finally compare the string on either side of the
4783 * wildcard */
4784 prefixlen = pattern_wildcard - pattern;
4785 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004786 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4787 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004788 return 0;
4789
4790 return 1;
4791}
4792
4793static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4794{
4795 SSL *ssl;
4796 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004797 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004798 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004799 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004800
4801 int depth;
4802 X509 *cert;
4803 STACK_OF(GENERAL_NAME) *alt_names;
4804 int i;
4805 X509_NAME *cert_subject;
4806 char *str;
4807
4808 if (ok == 0)
4809 return ok;
4810
4811 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004812 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004813 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004814
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004815 /* We're checking if the provided hostnames match the desired one. The
4816 * desired hostname comes from the SNI we presented if any, or if not
4817 * provided then it may have been explicitly stated using a "verifyhost"
4818 * directive. If neither is set, we don't care about the name so the
4819 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004820 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004821 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004822 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004823 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004824 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004825 if (!servername)
4826 return ok;
4827 }
Evan Broderbe554312013-06-27 00:05:25 -07004828
4829 /* We only need to verify the CN on the actual server cert,
4830 * not the indirect CAs */
4831 depth = X509_STORE_CTX_get_error_depth(ctx);
4832 if (depth != 0)
4833 return ok;
4834
4835 /* At this point, the cert is *not* OK unless we can find a
4836 * hostname match */
4837 ok = 0;
4838
4839 cert = X509_STORE_CTX_get_current_cert(ctx);
4840 /* It seems like this might happen if verify peer isn't set */
4841 if (!cert)
4842 return ok;
4843
4844 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4845 if (alt_names) {
4846 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4847 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4848 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004849#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004850 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4851#else
Evan Broderbe554312013-06-27 00:05:25 -07004852 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004853#endif
Evan Broderbe554312013-06-27 00:05:25 -07004854 ok = ssl_sock_srv_hostcheck(str, servername);
4855 OPENSSL_free(str);
4856 }
4857 }
4858 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004859 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004860 }
4861
4862 cert_subject = X509_get_subject_name(cert);
4863 i = -1;
4864 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4865 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004866 ASN1_STRING *value;
4867 value = X509_NAME_ENTRY_get_data(entry);
4868 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004869 ok = ssl_sock_srv_hostcheck(str, servername);
4870 OPENSSL_free(str);
4871 }
4872 }
4873
Willy Tarreau71d058c2017-07-26 20:09:56 +02004874 /* report the mismatch and indicate if SNI was used or not */
4875 if (!ok && !conn->err_code)
4876 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004877 return ok;
4878}
4879
Emeric Brun94324a42012-10-11 14:00:19 +02004880/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004881int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004882{
4883 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01004884 SSL_CTX *ctx;
Willy Tarreaufce03112015-01-15 21:32:40 +01004885 /* Automatic memory computations need to know we use SSL there */
4886 global.ssl_used_backend = 1;
4887
4888 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004889 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004890 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004891 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02004892 cfgerr++;
4893 return cfgerr;
4894 }
4895 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004896 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004897 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004898
William Lallemand2c776f12021-12-28 18:47:17 +01004899 if (srv->ssl_ctx.client_crt) {
4900 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
4901 char *err = NULL;
4902 int err_code = 0;
4903
4904 /* If there is a crt keyword there, the SSL_CTX will be created here. */
4905 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
4906 if (err_code != ERR_NONE) {
4907 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
4908 ha_warning("%s", err);
4909 else
4910 ha_alert("%s", err);
4911
4912 if (err_code & (ERR_FATAL|ERR_ABORT))
4913 cfgerr++;
4914 }
4915 ha_free(&err);
4916 }
4917
4918 ctx = srv->ssl_ctx.ctx;
4919
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004920 /* The context will be uninitialized if there wasn't any "cert" option
4921 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004922 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004923 ctx = SSL_CTX_new(SSLv23_client_method());
4924 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004925 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004926 cfgerr++;
4927 return cfgerr;
4928 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004929
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004930 srv->ssl_ctx.ctx = ctx;
4931 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004932
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004933 cfgerr += ssl_sock_prep_srv_ctx_and_inst(srv, srv->ssl_ctx.ctx, srv->ssl_ctx.inst);
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004934
4935 return cfgerr;
4936}
4937
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004938/* Initialize an SSL context that will be used on the backend side.
4939 * Returns an error count.
4940 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004941static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004942{
4943 struct proxy *curproxy = srv->proxy;
4944 int cfgerr = 0;
4945 long options =
4946 SSL_OP_ALL | /* all known workarounds for bugs */
4947 SSL_OP_NO_SSLv2 |
4948 SSL_OP_NO_COMPRESSION;
4949 long mode =
4950 SSL_MODE_ENABLE_PARTIAL_WRITE |
4951 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4952 SSL_MODE_RELEASE_BUFFERS |
4953 SSL_MODE_SMALL_BUFFERS;
4954 int verify = SSL_VERIFY_NONE;
4955 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4956 int i, min, max, hole;
4957 int flags = MC_SSL_O_ALL;
4958
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004959 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004960 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
4961 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004962 else
4963 flags = conf_ssl_methods->flags;
4964
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004965 /* Real min and max should be determinate with configuration and openssl's capabilities */
4966 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004967 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004968 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004969 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004970
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004971 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004972 min = max = CONF_TLSV_NONE;
4973 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004974 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004975 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004976 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004977 if (min) {
4978 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02004979 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01004980 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4981 proxy_type_str(curproxy), curproxy->id, srv->id,
4982 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004983 hole = 0;
4984 }
4985 max = i;
4986 }
4987 else {
4988 min = max = i;
4989 }
4990 }
4991 else {
4992 if (min)
4993 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004994 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004995 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02004996 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004997 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004998 cfgerr += 1;
4999 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005000
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005001#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005002 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005003 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005004 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005005 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005006 else
5007 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5008 if (flags & methodVersions[i].flag)
5009 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005010#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005011 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005012 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5013 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005014#endif
5015
5016 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5017 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005018 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005019
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005020#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005021 if (global_ssl.async)
5022 mode |= SSL_MODE_ASYNC;
5023#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005024 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005025
Emeric Brun850efd52014-01-29 12:24:34 +01005026 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5027 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005028 switch (srv->ssl_ctx.verify) {
5029 case SSL_SOCK_VERIFY_NONE:
5030 verify = SSL_VERIFY_NONE;
5031 break;
5032 case SSL_SOCK_VERIFY_REQUIRED:
5033 verify = SSL_VERIFY_PEER;
5034 break;
5035 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005036 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005037 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005038 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005039 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005040 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005041 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005042 ha_alert("unable to set CA file '%s'.\n",
5043 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005044 cfgerr++;
5045 }
5046 }
Emeric Brun850efd52014-01-29 12:24:34 +01005047 else {
5048 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005049 ha_alert("verify is enabled by default but no CA file specified. If you're running on a LAN where you're certain to trust the server's certificate, please set an explicit 'verify none' statement on the 'server' line, or use 'ssl-server-verify none' in the global section to disable server-side verifications by default.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005050 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005051 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005052 cfgerr++;
5053 }
Emeric Brunef42d922012-10-11 16:11:36 +02005054#ifdef X509_V_FLAG_CRL_CHECK
5055 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005056 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005057
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005058 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005059 ha_alert("unable to configure CRL file '%s'.\n",
5060 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005061 cfgerr++;
5062 }
5063 else {
5064 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5065 }
5066 }
5067#endif
5068 }
5069
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005070 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5071 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005072 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005073 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005074 ha_alert("unable to set SSL cipher list to '%s'.\n",
5075 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005076 cfgerr++;
5077 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005078
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005079#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005080 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005081 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005082 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5083 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005084 cfgerr++;
5085 }
5086#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005087#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5088 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005089 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005090#endif
5091#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5092 if (srv->ssl_ctx.alpn_str)
5093 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5094#endif
5095
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005096
5097 return cfgerr;
5098}
5099
5100/*
5101 * Prepare the frontend's SSL_CTX based on the server line configuration.
5102 * Since the CA file loading is made depending on the verify option of the
5103 * server line, the link between the SSL_CTX and the CA file tree entry is
5104 * made here.
5105 * If we want to create a link between the CA file entry and the corresponding
5106 * ckch instance (for CA file hot update), it needs to be done after
5107 * ssl_sock_prepare_srv_ssl_ctx.
5108 * Returns an error count.
5109 */
5110int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5111 struct ckch_inst *ckch_inst)
5112{
5113 int cfgerr = 0;
5114
5115 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5116 if (!cfgerr && ckch_inst)
5117 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005118
5119 return cfgerr;
5120}
5121
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005122
Frédéric Lécailleec216522020-11-23 14:33:30 +01005123/*
5124 * Create an initial CTX used to start the SSL connections.
5125 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5126 * Returns 0 if succeeded, or something >0 if not.
5127 */
5128#ifdef USE_QUIC
5129static int ssl_initial_ctx(struct bind_conf *bind_conf)
5130{
5131 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5132 return ssl_quic_initial_ctx(bind_conf);
5133 else
5134 return ssl_sock_initial_ctx(bind_conf);
5135}
5136#else
5137static int ssl_initial_ctx(struct bind_conf *bind_conf)
5138{
5139 return ssl_sock_initial_ctx(bind_conf);
5140}
5141#endif
5142
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005143/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005144 * be NULL, in which case nothing is done. Returns the number of errors
5145 * encountered.
5146 */
Willy Tarreau03209342016-12-22 17:08:28 +01005147int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005148{
5149 struct ebmb_node *node;
5150 struct sni_ctx *sni;
5151 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005152 int errcode = 0;
5153 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005154
Willy Tarreaufce03112015-01-15 21:32:40 +01005155 /* Automatic memory computations need to know we use SSL there */
5156 global.ssl_used_frontend = 1;
5157
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005158 /* Create initial_ctx used to start the ssl connection before do switchctx */
5159 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005160 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005161 /* It should not be necessary to call this function, but it's
5162 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005163 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005164 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5165 }
5166 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005167 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, bind_conf->default_inst, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005168 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005169
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005170 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005171 while (node) {
5172 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005173 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005174 /* only initialize the CTX on its first occurrence and
5175 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005176 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5177 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005178 node = ebmb_next(node);
5179 }
5180
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005181 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005182 while (node) {
5183 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005184 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005185 /* only initialize the CTX on its first occurrence and
5186 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005187 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005188 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005189 node = ebmb_next(node);
5190 }
William Lallemand8b453912019-11-21 15:48:10 +01005191
5192 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005193 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005194 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005195 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005196 err++;
5197 }
5198
5199 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005200 return err;
5201}
5202
Willy Tarreau55d37912016-12-21 23:38:39 +01005203/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5204 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5205 * alerts are directly emitted since the rest of the stack does it below.
5206 */
5207int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5208{
5209 struct proxy *px = bind_conf->frontend;
5210 int alloc_ctx;
5211 int err;
5212
5213 if (!bind_conf->is_ssl) {
5214 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005215 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5216 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005217 }
5218 return 0;
5219 }
5220 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005221 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005222 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5223 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005224 }
5225 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005226 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5227 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005228 return -1;
5229 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005230 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005231 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005232 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005233 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005234 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005235 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005236 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5237 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");
5238 else
5239 ha_alert("Unable to allocate SSL session cache.\n");
5240 return -1;
5241 }
5242 /* free block callback */
5243 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5244 /* init the root tree within the extra space */
5245 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5246 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005247 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005248 err = 0;
5249 /* initialize all certificate contexts */
5250 err += ssl_sock_prepare_all_ctx(bind_conf);
5251
5252 /* initialize CA variables if the certificates generation is enabled */
5253 err += ssl_sock_load_ca(bind_conf);
5254
5255 return -err;
5256}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005257
William Lallemand231610a2021-12-30 11:25:43 +01005258/* release ssl context allocated for servers. Most of the field free here
5259 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005260void ssl_sock_free_srv_ctx(struct server *srv)
5261{
Olivier Houchardc7566002018-11-20 23:33:50 +01005262#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005263 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005264#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005265#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005266 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005267#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005268 if (srv->ssl_ctx.reused_sess) {
5269 int i;
5270
William Lallemande18d4e82021-11-17 02:59:21 +01005271 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005272 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005273 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5274 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005275 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005276 }
5277
Willy Tarreaue709e822021-02-26 21:06:32 +01005278 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005279 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005280 srv->ssl_ctx.ctx = NULL;
5281 }
William Lallemand231610a2021-12-30 11:25:43 +01005282
5283 ha_free(&srv->ssl_ctx.ca_file);
5284 ha_free(&srv->ssl_ctx.crl_file);
5285 ha_free(&srv->ssl_ctx.client_crt);
5286 ha_free(&srv->ssl_ctx.verify_host);
5287#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5288 ha_free(&srv->sni_expr);
5289#endif
5290 ha_free(&srv->ssl_ctx.ciphers);
5291#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5292 ha_free(&srv->ssl_ctx.ciphersuites);
5293#endif
William Lallemande69563f2021-12-30 14:45:19 +01005294 /* If there is a certificate we must unlink the ckch instance */
5295 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005296}
5297
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005298/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005299 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5300 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005301void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005302{
5303 struct ebmb_node *node, *back;
5304 struct sni_ctx *sni;
5305
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005306 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005307 while (node) {
5308 sni = ebmb_entry(node, struct sni_ctx, name);
5309 back = ebmb_next(node);
5310 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005311 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005312 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005313 free(sni);
5314 node = back;
5315 }
5316
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005317 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005318 while (node) {
5319 sni = ebmb_entry(node, struct sni_ctx, name);
5320 back = ebmb_next(node);
5321 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005322 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005323 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005324 free(sni);
5325 node = back;
5326 }
William Lallemandb2408692020-06-24 09:54:29 +02005327
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005328 SSL_CTX_free(bind_conf->initial_ctx);
5329 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005330 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005331 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005332 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005333 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005334}
William Lallemandb2408692020-06-24 09:54:29 +02005335
5336
5337void ssl_sock_deinit()
5338{
5339 crtlist_deinit(); /* must be free'd before the ckchs */
5340 ckch_deinit();
5341}
5342REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005343
Willy Tarreau795cdab2016-12-22 17:30:54 +01005344/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5345void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5346{
5347 ssl_sock_free_ca(bind_conf);
5348 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005349 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005350 free(bind_conf->ca_sign_file);
5351 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005352 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005353 free(bind_conf->keys_ref->filename);
5354 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005355 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005356 free(bind_conf->keys_ref);
5357 }
5358 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005359 bind_conf->ca_sign_pass = NULL;
5360 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005361}
5362
Christopher Faulet31af49d2015-06-09 17:29:50 +02005363/* Load CA cert file and private key used to generate certificates */
5364int
Willy Tarreau03209342016-12-22 17:08:28 +01005365ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005366{
Willy Tarreau03209342016-12-22 17:08:28 +01005367 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03005368 struct cert_key_and_chain *ckch = NULL;
5369 int ret = 0;
5370 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005371
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02005372 if (!bind_conf->generate_certs)
Shimi Gersner5846c492020-08-23 13:58:12 +03005373 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005374
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005375#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005376 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005377 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005378 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005379 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005380 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005381#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005382
Christopher Faulet31af49d2015-06-09 17:29:50 +02005383 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005384 ha_alert("Proxy '%s': cannot enable certificate generation, "
5385 "no CA certificate File configured at [%s:%d].\n",
5386 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005387 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005388 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005389
Shimi Gersner5846c492020-08-23 13:58:12 +03005390 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02005391 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03005392 if (!ckch) {
5393 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5394 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5395 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005396 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005397
5398 /* Try to parse file */
5399 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
5400 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5401 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005402 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005403 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005404 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005405
5406 /* Fail if missing cert or pkey */
5407 if ((!ckch->cert) || (!ckch->key)) {
5408 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5409 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5410 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005411 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005412
Shimi Gersner5846c492020-08-23 13:58:12 +03005413 /* Final assignment to bind */
5414 bind_conf->ca_sign_ckch = ckch;
5415 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005416
Shimi Gersner5846c492020-08-23 13:58:12 +03005417 failed:
5418 if (ckch) {
5419 ssl_sock_free_cert_key_and_chain_contents(ckch);
5420 free(ckch);
5421 }
5422
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005423 bind_conf->generate_certs = 0;
Shimi Gersner5846c492020-08-23 13:58:12 +03005424 ret++;
5425 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005426}
5427
5428/* Release CA cert and private key used to generate certificated */
5429void
5430ssl_sock_free_ca(struct bind_conf *bind_conf)
5431{
Shimi Gersner5846c492020-08-23 13:58:12 +03005432 if (bind_conf->ca_sign_ckch) {
5433 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005434 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005435 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005436}
5437
Emeric Brun46591952012-05-18 15:47:34 +02005438/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005439 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5440 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5441 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5442 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005443 * 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 +01005444 * as parameters to this function.
5445 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5446 * CO_ER_SSL_NO_MEM.
5447 */
5448int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5449 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5450{
5451 int retry = 1;
5452
5453 retry:
5454 /* Alloc a new SSL session. */
5455 *ssl = SSL_new(ssl_ctx);
5456 if (!*ssl) {
5457 if (!retry--)
5458 goto err;
5459
5460 pool_gc(NULL);
5461 goto retry;
5462 }
5463
5464 *bio = BIO_new(bio_meth);
5465 if (!*bio) {
5466 SSL_free(*ssl);
5467 *ssl = NULL;
5468 if (!retry--)
5469 goto err;
5470
5471 pool_gc(NULL);
5472 goto retry;
5473 }
5474
5475 BIO_set_data(*bio, ctx);
5476 SSL_set_bio(*ssl, *bio, *bio);
5477
5478 /* set connection pointer. */
5479 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5480 SSL_free(*ssl);
5481 *ssl = NULL;
5482 if (!retry--)
5483 goto err;
5484
5485 pool_gc(NULL);
5486 goto retry;
5487 }
5488
5489 return 0;
5490
5491 err:
5492 conn->err_code = CO_ER_SSL_NO_MEM;
5493 return -1;
5494}
5495
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005496/* This function is called when all the XPRT have been initialized. We can
5497 * now attempt to start the SSL handshake.
5498 */
5499static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5500{
5501 struct ssl_sock_ctx *ctx = xprt_ctx;
5502
5503 if (ctx->xprt->start) {
5504 int ret;
5505
5506 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5507 if (ret < 0)
5508 return ret;
5509 }
5510 tasklet_wakeup(ctx->wait_event.tasklet);
5511
5512 return 0;
5513}
5514
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005515/*
Emeric Brun46591952012-05-18 15:47:34 +02005516 * This function is called if SSL * context is not yet allocated. The function
5517 * is designed to be called before any other data-layer operation and sets the
5518 * handshake flag on the connection. It is safe to call it multiple times.
5519 * It returns 0 on success and -1 in error case.
5520 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005521static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005522{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005523 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005524 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005525 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005526 return 0;
5527
Olivier Houchard66ab4982019-02-26 18:37:15 +01005528 ctx = pool_alloc(ssl_sock_ctx_pool);
5529 if (!ctx) {
5530 conn->err_code = CO_ER_SSL_NO_MEM;
5531 return -1;
5532 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005533 ctx->wait_event.tasklet = tasklet_new();
5534 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005535 conn->err_code = CO_ER_SSL_NO_MEM;
5536 pool_free(ssl_sock_ctx_pool, ctx);
5537 return -1;
5538 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005539 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5540 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005541 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005542 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005543 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005544 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005545 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005546 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005547 ctx->xprt_st = 0;
5548 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005549 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005550
5551 /* Only work with sockets for now, this should be adapted when we'll
5552 * add QUIC support.
5553 */
5554 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005555 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005556 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5557 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005558 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005559
Willy Tarreau82531f62021-10-06 12:15:18 +02005560 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005561 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005562 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005563 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005564
Emeric Brun46591952012-05-18 15:47:34 +02005565 /* If it is in client mode initiate SSL session
5566 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005567 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005568 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5569 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005570 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005571
Olivier Houchard66ab4982019-02-26 18:37:15 +01005572 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005573 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005574 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5575 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5576 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 +01005577 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005578 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005579 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005580 } else if (sess) {
5581 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005582 }
5583 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005584 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005585
Emeric Brun46591952012-05-18 15:47:34 +02005586 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005587 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005588
Willy Tarreau82531f62021-10-06 12:15:18 +02005589 _HA_ATOMIC_INC(&global.sslconns);
5590 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005591 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005592 return 0;
5593 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005594 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005595 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005596
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005597 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5598 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005599 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005600
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005601#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005602 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005603 b_alloc(&ctx->early_buf);
5604 SSL_set_max_early_data(ctx->ssl,
5605 /* Only allow early data if we managed to allocate
5606 * a buffer.
5607 */
5608 (!b_is_null(&ctx->early_buf)) ?
5609 global.tune.bufsize - global.tune.maxrewrite : 0);
5610 }
5611#endif
5612
Olivier Houchard66ab4982019-02-26 18:37:15 +01005613 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005614
Emeric Brun46591952012-05-18 15:47:34 +02005615 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005616 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005617#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005618 if (bc->ssl_conf.early_data)
5619 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005620#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005621
Willy Tarreau82531f62021-10-06 12:15:18 +02005622 _HA_ATOMIC_INC(&global.sslconns);
5623 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005624 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005625 return 0;
5626 }
5627 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005628 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005629err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005630 if (ctx && ctx->wait_event.tasklet)
5631 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005632 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005633 return -1;
5634}
5635
5636
5637/* This is the callback which is used when an SSL handshake is pending. It
5638 * updates the FD status if it wants some polling before being called again.
5639 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5640 * otherwise it returns non-zero and removes itself from the connection's
5641 * flags (the bit is provided in <flag> by the caller).
5642 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005643static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005644{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005645 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005646 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005647 struct ssl_counters *counters = NULL;
5648 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005649 struct listener *li;
5650 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005651 socklen_t lskerr;
5652 int skerr;
5653
Emeric Brun46591952012-05-18 15:47:34 +02005654
Willy Tarreau3c728722014-01-23 13:50:42 +01005655 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005656 return 0;
5657
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005658 /* get counters */
5659 switch (obj_type(conn->target)) {
5660 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005661 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005662 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5663 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5664 &ssl_stats_module);
5665 break;
5666
5667 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005668 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005669 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5670 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5671 &ssl_stats_module);
5672 break;
5673
5674 default:
5675 break;
5676 }
5677
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005678 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005679 goto out_error;
5680
Willy Tarreau06300382021-02-02 15:42:25 +01005681 /* don't start calculating a handshake on a dead connection */
5682 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5683 goto out_error;
5684
5685 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5686 * status from the lower layers, so let's check the FD directly. Ideally
5687 * the xprt layers should provide some status indicating their knowledge
5688 * of shutdowns or error.
5689 */
5690 skerr = 0;
5691 lskerr = sizeof(skerr);
5692 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5693 skerr != 0)
5694 goto out_error;
5695
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005696#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005697 /*
5698 * Check if we have early data. If we do, we have to read them
5699 * before SSL_do_handshake() is called, And there's no way to
5700 * detect early data, except to try to read them
5701 */
5702 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005703 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005704
Olivier Houchard54907bb2019-12-19 15:02:39 +01005705 while (1) {
5706 ret = SSL_read_early_data(ctx->ssl,
5707 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5708 &read_data);
5709 if (ret == SSL_READ_EARLY_DATA_ERROR)
5710 goto check_error;
5711 if (read_data > 0) {
5712 conn->flags |= CO_FL_EARLY_DATA;
5713 b_add(&ctx->early_buf, read_data);
5714 }
5715 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5716 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5717 if (!b_data(&ctx->early_buf))
5718 b_free(&ctx->early_buf);
5719 break;
5720 }
5721 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005722 }
5723#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005724 /* If we use SSL_do_handshake to process a reneg initiated by
5725 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5726 * Usually SSL_write and SSL_read are used and process implicitly
5727 * the reneg handshake.
5728 * Here we use SSL_peek as a workaround for reneg.
5729 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005730 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005731 char c;
5732
Olivier Houchard66ab4982019-02-26 18:37:15 +01005733 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005734 if (ret <= 0) {
5735 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005736 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005737
Emeric Brun674b7432012-11-08 19:21:55 +01005738 if (ret == SSL_ERROR_WANT_WRITE) {
5739 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005740 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005741 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005742 return 0;
5743 }
5744 else if (ret == SSL_ERROR_WANT_READ) {
5745 /* handshake may have been completed but we have
5746 * no more data to read.
5747 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005748 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005749 ret = 1;
5750 goto reneg_ok;
5751 }
5752 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005753 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005754 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005755 return 0;
5756 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005757#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005758 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005759 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005760 return 0;
5761 }
5762#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005763 else if (ret == SSL_ERROR_SYSCALL) {
5764 /* if errno is null, then connection was successfully established */
5765 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5766 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005767 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005768#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5769 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005770 conn->err_code = CO_ER_SSL_HANDSHAKE;
5771#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005772 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005773#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005774 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005775 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005776 empty_handshake = state == TLS_ST_BEFORE;
5777#else
Lukas Tribus49799162019-07-08 14:29:15 +02005778 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5779 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005780#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005781 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005782 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005783 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005784 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5785 else
5786 conn->err_code = CO_ER_SSL_EMPTY;
5787 }
5788 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005789 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005790 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5791 else
5792 conn->err_code = CO_ER_SSL_ABORT;
5793 }
5794 }
5795 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005796 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005797 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005798 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005799 conn->err_code = CO_ER_SSL_HANDSHAKE;
5800 }
Lukas Tribus49799162019-07-08 14:29:15 +02005801#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005802 }
Emeric Brun674b7432012-11-08 19:21:55 +01005803 goto out_error;
5804 }
5805 else {
5806 /* Fail on all other handshake errors */
5807 /* Note: OpenSSL may leave unread bytes in the socket's
5808 * buffer, causing an RST to be emitted upon close() on
5809 * TCP sockets. We first try to drain possibly pending
5810 * data to avoid this as much as possible.
5811 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005812 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005813 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005814 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005815 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005816 goto out_error;
5817 }
5818 }
5819 /* read some data: consider handshake completed */
5820 goto reneg_ok;
5821 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005822 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005823check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005824 if (ret != 1) {
5825 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005826 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005827
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005828 if (!ctx->error_code)
5829 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02005830
Emeric Brun46591952012-05-18 15:47:34 +02005831 if (ret == SSL_ERROR_WANT_WRITE) {
5832 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005833 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005834 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005835 return 0;
5836 }
5837 else if (ret == SSL_ERROR_WANT_READ) {
5838 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005839 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005840 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5841 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005842 return 0;
5843 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005844#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005845 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005846 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005847 return 0;
5848 }
5849#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005850 else if (ret == SSL_ERROR_SYSCALL) {
5851 /* if errno is null, then connection was successfully established */
5852 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5853 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005854 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005855#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5856 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005857 conn->err_code = CO_ER_SSL_HANDSHAKE;
5858#else
5859 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005860#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005861 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005862 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005863 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005864#else
Lukas Tribus49799162019-07-08 14:29:15 +02005865 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5866 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005867#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005868 if (empty_handshake) {
5869 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005870 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005871 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5872 else
5873 conn->err_code = CO_ER_SSL_EMPTY;
5874 }
5875 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005876 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005877 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5878 else
5879 conn->err_code = CO_ER_SSL_ABORT;
5880 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005881 }
5882 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005883 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005884 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5885 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005886 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005887 }
Lukas Tribus49799162019-07-08 14:29:15 +02005888#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005889 }
Willy Tarreau89230192012-09-28 20:22:13 +02005890 goto out_error;
5891 }
Emeric Brun46591952012-05-18 15:47:34 +02005892 else {
5893 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005894 /* Note: OpenSSL may leave unread bytes in the socket's
5895 * buffer, causing an RST to be emitted upon close() on
5896 * TCP sockets. We first try to drain possibly pending
5897 * data to avoid this as much as possible.
5898 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005899 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005900 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005901 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005902 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005903 goto out_error;
5904 }
5905 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005906#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005907 else {
5908 /*
5909 * If the server refused the early data, we have to send a
5910 * 425 to the client, as we no longer have the data to sent
5911 * them again.
5912 */
5913 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005914 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005915 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5916 goto out_error;
5917 }
5918 }
5919 }
5920#endif
5921
Emeric Brun46591952012-05-18 15:47:34 +02005922
Emeric Brun674b7432012-11-08 19:21:55 +01005923reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005924
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005925#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005926 /* ASYNC engine API doesn't support moving read/write
5927 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005928 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005929 */
5930 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005931 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005932#endif
Emeric Brun46591952012-05-18 15:47:34 +02005933 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005934 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005935 if (objt_server(conn->target)) {
5936 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5937 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5938 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005939 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005940 else {
5941 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5942 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5943 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5944 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005945
Willy Tarreau42995282020-11-06 13:19:18 +01005946 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01005947 HA_ATOMIC_INC(&counters->sess);
5948 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01005949 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005950 }
Willy Tarreau42995282020-11-06 13:19:18 +01005951 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01005952 HA_ATOMIC_INC(&counters->reused_sess);
5953 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02005954 }
5955
5956 /* The connection is now established at both layers, it's time to leave */
5957 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5958 return 1;
5959
5960 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005961 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005962 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005963 ERR_clear_error();
5964
Emeric Brun9fa89732012-10-04 17:09:56 +02005965 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01005966 if (objt_server(conn->target)) {
5967 struct server *s = __objt_server(conn->target);
5968 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
5969 * one cache per thread, it only prevents to flush it from the CLI in
5970 * another thread */
5971
5972 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005973 if (s->ssl_ctx.reused_sess[tid].ptr)
5974 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005975 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02005976 }
5977
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005978 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01005979 HA_ATOMIC_INC(&counters->failed_handshake);
5980 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005981 }
5982
Emeric Brun46591952012-05-18 15:47:34 +02005983 /* Fail on all other handshake errors */
5984 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005985 if (!conn->err_code)
5986 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005987 return 0;
5988}
5989
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005990/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5991 * event subscriber <es> is not allowed to change from a previous call as long
5992 * as at least one event is still subscribed. The <event_type> must only be a
5993 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5994 * unless the transport layer was already released.
5995 */
5996static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005997{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005998 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005999
Olivier Houchard0ff28652019-06-24 18:57:39 +02006000 if (!ctx)
6001 return -1;
6002
Willy Tarreau113d52b2020-01-10 09:20:26 +01006003 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006004 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006005
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006006 ctx->subs = es;
6007 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006008
6009 /* we may have to subscribe to lower layers for new events */
6010 event_type &= ~ctx->wait_event.events;
6011 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6012 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006013 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006014}
6015
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006016/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6017 * The <es> pointer is not allowed to differ from the one passed to the
6018 * subscribe() call. It always returns zero.
6019 */
6020static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006021{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006022 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006023
Willy Tarreau113d52b2020-01-10 09:20:26 +01006024 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006025 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006026
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006027 es->events &= ~event_type;
6028 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006029 ctx->subs = NULL;
6030
6031 /* If we subscribed, and we're not doing the handshake,
6032 * then we subscribed because the upper layer asked for it,
6033 * as the upper layer is no longer interested, we can
6034 * unsubscribe too.
6035 */
6036 event_type &= ctx->wait_event.events;
6037 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6038 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006039
6040 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006041}
6042
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006043/* The connection has been taken over, so destroy the old tasklet and create
6044 * a new one. The original thread ID must be passed into orig_tid
6045 * It should be called with the takeover lock for the old thread held.
6046 * Returns 0 on success, and -1 on failure
6047 */
6048static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6049{
6050 struct ssl_sock_ctx *ctx = xprt_ctx;
6051 struct tasklet *tl = tasklet_new();
6052
6053 if (!tl)
6054 return -1;
6055
6056 ctx->wait_event.tasklet->context = NULL;
6057 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6058 ctx->wait_event.tasklet = tl;
6059 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6060 ctx->wait_event.tasklet->context = ctx;
6061 return 0;
6062}
6063
Willy Tarreau41491682021-03-02 17:29:56 +01006064/* notify the next xprt that the connection is about to become idle and that it
6065 * may be stolen at any time after the function returns and that any tasklet in
6066 * the chain must be careful before dereferencing its context.
6067 */
6068static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6069{
6070 struct ssl_sock_ctx *ctx = xprt_ctx;
6071
6072 if (!ctx || !ctx->wait_event.tasklet)
6073 return;
6074
6075 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6076 if (ctx->xprt)
6077 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6078}
6079
6080/* notify the next xprt that the connection is not idle anymore and that it may
6081 * not be stolen before the next xprt_set_idle().
6082 */
6083static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6084{
6085 struct ssl_sock_ctx *ctx = xprt_ctx;
6086
6087 if (!ctx || !ctx->wait_event.tasklet)
6088 return;
6089
6090 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6091 if (ctx->xprt)
6092 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6093}
6094
Olivier Houchard2e055482019-05-27 19:50:12 +02006095/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6096 * Returns 0 on success, and non-zero on failure.
6097 */
6098static 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)
6099{
6100 struct ssl_sock_ctx *ctx = xprt_ctx;
6101
6102 if (oldxprt_ops != NULL)
6103 *oldxprt_ops = ctx->xprt;
6104 if (oldxprt_ctx != NULL)
6105 *oldxprt_ctx = ctx->xprt_ctx;
6106 ctx->xprt = toadd_ops;
6107 ctx->xprt_ctx = toadd_ctx;
6108 return 0;
6109}
6110
Olivier Houchard5149b592019-05-23 17:47:36 +02006111/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6112 * return 0, otherwise just call the remove_xprt method from the underlying
6113 * XPRT.
6114 */
6115static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6116{
6117 struct ssl_sock_ctx *ctx = xprt_ctx;
6118
6119 if (ctx->xprt_ctx == toremove_ctx) {
6120 ctx->xprt_ctx = newctx;
6121 ctx->xprt = newops;
6122 return 0;
6123 }
6124 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6125}
6126
Willy Tarreau144f84a2021-03-02 16:09:26 +01006127struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006128{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006129 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006130 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006131 struct connection *conn;
6132 int conn_in_list;
6133 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006134
Willy Tarreau41491682021-03-02 17:29:56 +01006135 if (state & TASK_F_USR1) {
6136 /* the tasklet was idling on an idle connection, it might have
6137 * been stolen, let's be careful!
6138 */
6139 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6140 if (tl->context == NULL) {
6141 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6142 tasklet_free(tl);
6143 return NULL;
6144 }
6145 conn = ctx->conn;
6146 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6147 if (conn_in_list)
6148 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006149 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006150 } else {
6151 conn = ctx->conn;
6152 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006153 }
Willy Tarreau41491682021-03-02 17:29:56 +01006154
Olivier Houchardea8dd942019-05-20 14:02:16 +02006155 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006156 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006157 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006158 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6159 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006160 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006161 }
6162 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006163 /* If we had an error, or the handshake is done and I/O is available,
6164 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006165 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006166 * we can't be sure conn_fd_handler() will be called again.
6167 */
6168 if ((ctx->conn->flags & CO_FL_ERROR) ||
6169 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006170 int woke = 0;
6171
6172 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006173 if (ctx->subs) {
6174 tasklet_wakeup(ctx->subs->tasklet);
6175 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006176 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006177 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006178 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006179
Olivier Houchardea8dd942019-05-20 14:02:16 +02006180 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006181 * upper layers know. If we have no mux, create it,
6182 * and once we have a mux, call its wake method if we didn't
6183 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006184 */
6185 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006186 if (!ctx->conn->mux)
6187 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006188 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006189 ret = ctx->conn->mux->wake(ctx->conn);
6190 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006191 }
6192 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006193#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006194 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006195 else if (b_data(&ctx->early_buf) && ctx->subs &&
6196 ctx->subs->events & SUB_RETRY_RECV) {
6197 tasklet_wakeup(ctx->subs->tasklet);
6198 ctx->subs->events &= ~SUB_RETRY_RECV;
6199 if (!ctx->subs->events)
6200 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006201 }
6202#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006203leave:
6204 if (!ret && conn_in_list) {
6205 struct server *srv = objt_server(conn->target);
6206
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006207 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006208 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006209 ebmb_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006210 else
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006211 ebmb_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006212 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006213 }
Willy Tarreau74163142021-03-13 11:30:19 +01006214 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006215}
6216
Emeric Brun46591952012-05-18 15:47:34 +02006217/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006218 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006219 * buffer wraps, in which case a second call may be performed. The connection's
6220 * flags are updated with whatever special event is detected (error, read0,
6221 * empty). The caller is responsible for taking care of those events and
6222 * avoiding the call if inappropriate. The function does not call the
6223 * connection's polling update function, so the caller is responsible for this.
6224 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006225static 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 +02006226{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006227 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006228 ssize_t ret;
6229 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006230
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006231 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006232 goto out_error;
6233
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006234#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006235 if (b_data(&ctx->early_buf)) {
6236 try = b_contig_space(buf);
6237 if (try > b_data(&ctx->early_buf))
6238 try = b_data(&ctx->early_buf);
6239 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6240 b_add(buf, try);
6241 b_del(&ctx->early_buf, try);
6242 if (b_data(&ctx->early_buf) == 0)
6243 b_free(&ctx->early_buf);
6244 return try;
6245 }
6246#endif
6247
Willy Tarreau911db9b2020-01-23 16:27:54 +01006248 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006249 /* a handshake was requested */
6250 return 0;
6251
Emeric Brun46591952012-05-18 15:47:34 +02006252 /* read the largest possible block. For this, we perform only one call
6253 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6254 * in which case we accept to do it once again. A new attempt is made on
6255 * EINTR too.
6256 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006257 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006258
Willy Tarreau591d4452018-06-15 17:21:00 +02006259 try = b_contig_space(buf);
6260 if (!try)
6261 break;
6262
Willy Tarreauabf08d92014-01-14 11:31:27 +01006263 if (try > count)
6264 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006265
Olivier Houchard66ab4982019-02-26 18:37:15 +01006266 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006267
Emeric Brune1f38db2012-09-03 20:36:47 +02006268 if (conn->flags & CO_FL_ERROR) {
6269 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006270 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006271 }
Emeric Brun46591952012-05-18 15:47:34 +02006272 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006273 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006274 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006275 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006276 }
Emeric Brun46591952012-05-18 15:47:34 +02006277 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006278 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006279 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006280 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006281 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006282 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006283#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006284 /* Async mode can be re-enabled, because we're leaving data state.*/
6285 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006286 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006287#endif
Emeric Brun46591952012-05-18 15:47:34 +02006288 break;
6289 }
6290 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006291 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006292 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6293 SUB_RETRY_RECV,
6294 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006295 /* handshake is running, and it may need to re-enable read */
6296 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006297#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006298 /* Async mode can be re-enabled, because we're leaving data state.*/
6299 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006300 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006301#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006302 break;
6303 }
Emeric Brun46591952012-05-18 15:47:34 +02006304 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006305 } else if (ret == SSL_ERROR_ZERO_RETURN)
6306 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006307 else if (ret == SSL_ERROR_SSL) {
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006308 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
6309 if (!ctx->error_code)
6310 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006311 conn->err_code = CO_ERR_SSL_FATAL;
6312 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006313 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6314 * stack before shutting down the connection for
6315 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006316 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
6317 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006318 /* otherwise it's a real error */
6319 goto out_error;
6320 }
6321 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006322 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006323 return done;
6324
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006325 clear_ssl_error:
6326 /* Clear openssl global errors stack */
6327 ssl_sock_dump_errors(conn);
6328 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006329 read0:
6330 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006331 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006332
Emeric Brun46591952012-05-18 15:47:34 +02006333 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006334 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006335 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006336 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006337 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006338 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006339}
6340
6341
Willy Tarreau787db9a2018-06-14 18:31:46 +02006342/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6343 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6344 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006345 * Only one call to send() is performed, unless the buffer wraps, in which case
6346 * a second call may be performed. The connection's flags are updated with
6347 * whatever special event is detected (error, empty). The caller is responsible
6348 * for taking care of those events and avoiding the call if inappropriate. The
6349 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006350 * is responsible for this. The buffer's output is not adjusted, it's up to the
6351 * caller to take care of this. It's up to the caller to update the buffer's
6352 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006353 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006354static 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 +02006355{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006356 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006357 ssize_t ret;
6358 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006359
6360 done = 0;
6361
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006362 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006363 goto out_error;
6364
Willy Tarreau911db9b2020-01-23 16:27:54 +01006365 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006366 /* a handshake was requested */
6367 return 0;
6368
6369 /* send the largest possible block. For this we perform only one call
6370 * to send() unless the buffer wraps and we exactly fill the first hunk,
6371 * in which case we accept to do it once again.
6372 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006373 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006374#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006375 size_t written_data;
6376#endif
6377
Willy Tarreau787db9a2018-06-14 18:31:46 +02006378 try = b_contig_data(buf, done);
6379 if (try > count)
6380 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006381
Willy Tarreau7bed9452014-02-02 02:00:24 +01006382 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006383 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006384 global_ssl.max_record && try > global_ssl.max_record) {
6385 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006386 }
6387 else {
6388 /* we need to keep the information about the fact that
6389 * we're not limiting the upcoming send(), because if it
6390 * fails, we'll have to retry with at least as many data.
6391 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006392 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006393 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006394
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006395#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006396 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006397 unsigned int max_early;
6398
Olivier Houchard522eea72017-11-03 16:27:47 +01006399 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006400 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006401 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006402 if (SSL_get0_session(ctx->ssl))
6403 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006404 else
6405 max_early = 0;
6406 }
6407
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006408 if (try + ctx->sent_early_data > max_early) {
6409 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006410 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006411 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006412 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006413 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006414 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006415 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006416 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006417 if (ret == 1) {
6418 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006419 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006420 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006421 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006422 /* Initiate the handshake, now */
6423 tasklet_wakeup(ctx->wait_event.tasklet);
6424 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006425
Olivier Houchardc2aae742017-09-22 18:26:28 +02006426 }
6427
6428 } else
6429#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006430 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006431
Emeric Brune1f38db2012-09-03 20:36:47 +02006432 if (conn->flags & CO_FL_ERROR) {
6433 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006434 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006435 }
Emeric Brun46591952012-05-18 15:47:34 +02006436 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006437 /* A send succeeded, so we can consider ourself connected */
6438 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006439 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006440 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006441 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006442 }
6443 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006444 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006445
Emeric Brun46591952012-05-18 15:47:34 +02006446 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006447 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006448 /* handshake is running, and it may need to re-enable write */
6449 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006450 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006451#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006452 /* Async mode can be re-enabled, because we're leaving data state.*/
6453 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006454 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006455#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006456 break;
6457 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006458
Emeric Brun46591952012-05-18 15:47:34 +02006459 break;
6460 }
6461 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006462 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006463 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006464 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6465 SUB_RETRY_RECV,
6466 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006467#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006468 /* Async mode can be re-enabled, because we're leaving data state.*/
6469 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006470 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006471#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006472 break;
6473 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006474 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006475 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
6476 if (!ctx->error_code)
6477 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006478 conn->err_code = CO_ERR_SSL_FATAL;
6479 }
Emeric Brun46591952012-05-18 15:47:34 +02006480 goto out_error;
6481 }
6482 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006483 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006484 return done;
6485
6486 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006487 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006488 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006489 ERR_clear_error();
6490
Emeric Brun46591952012-05-18 15:47:34 +02006491 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006492 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006493}
6494
Willy Tarreau832e2422021-05-13 10:11:03 +02006495void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006496
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006497 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006498
Olivier Houchardea8dd942019-05-20 14:02:16 +02006499
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006500 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006501 if (ctx->wait_event.events != 0)
6502 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6503 ctx->wait_event.events,
6504 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006505 if (ctx->subs) {
6506 ctx->subs->events = 0;
6507 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006508 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006509
Olivier Houchard692c1d02019-05-23 18:41:47 +02006510 if (ctx->xprt->close)
6511 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006512#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006513 if (global_ssl.async) {
6514 OSSL_ASYNC_FD all_fd[32], afd;
6515 size_t num_all_fds = 0;
6516 int i;
6517
Olivier Houchard66ab4982019-02-26 18:37:15 +01006518 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006519 if (num_all_fds > 32) {
6520 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6521 return;
6522 }
6523
Olivier Houchard66ab4982019-02-26 18:37:15 +01006524 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006525
6526 /* If an async job is pending, we must try to
6527 to catch the end using polling before calling
6528 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006529 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006530 for (i=0 ; i < num_all_fds ; i++) {
6531 /* switch on an handler designed to
6532 * handle the SSL_free
6533 */
6534 afd = all_fd[i];
6535 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006536 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006537 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006538 /* To ensure that the fd cache won't be used
6539 * and we'll catch a real RD event.
6540 */
6541 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006542 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006543 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006544 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006545 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006546 return;
6547 }
Emeric Brun3854e012017-05-17 20:42:48 +02006548 /* Else we can remove the fds from the fdtab
6549 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006550 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006551 * because the fd is owned by the engine.
6552 * the engine is responsible to close
6553 */
6554 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +02006555 fd_stop_both(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006556 }
6557#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006558 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006559 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006560 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006561 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006562 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006563 }
Emeric Brun46591952012-05-18 15:47:34 +02006564}
6565
6566/* This function tries to perform a clean shutdown on an SSL connection, and in
6567 * any case, flags the connection as reusable if no handshake was in progress.
6568 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006569static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006570{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006571 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006572
Willy Tarreau911db9b2020-01-23 16:27:54 +01006573 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006574 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006575 if (!clean)
6576 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006577 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006578 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006579 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006580 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006581 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006582 ERR_clear_error();
6583 }
Emeric Brun46591952012-05-18 15:47:34 +02006584}
6585
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006586
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006587/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006588int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6589{
6590 struct ssl_sock_ctx *ctx;
6591 X509 *crt;
6592
Willy Tarreau1057bee2021-10-06 11:38:44 +02006593 if (!conn_is_ssl(conn))
William Lallemandd4f946c2019-12-05 10:26:40 +01006594 return 0;
6595
6596 ctx = conn->xprt_ctx;
6597
6598 crt = SSL_get_certificate(ctx->ssl);
6599 if (!crt)
6600 return 0;
6601
6602 return cert_get_pkey_algo(crt, out);
6603}
6604
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006605/* used for ppv2 cert signature (can be used for logging) */
6606const char *ssl_sock_get_cert_sig(struct connection *conn)
6607{
Christopher Faulet82004142019-09-10 10:12:03 +02006608 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006609
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006610 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6611 X509 *crt;
6612
Willy Tarreau1057bee2021-10-06 11:38:44 +02006613 if (!conn_is_ssl(conn))
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006614 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006615 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006616 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006617 if (!crt)
6618 return NULL;
6619 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6620 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6621}
6622
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006623/* used for ppv2 authority */
6624const char *ssl_sock_get_sni(struct connection *conn)
6625{
6626#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006627 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006628
Willy Tarreau1057bee2021-10-06 11:38:44 +02006629 if (!conn_is_ssl(conn))
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006630 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006631 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006632 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006633#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006634 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006635#endif
6636}
6637
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006638/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006639const char *ssl_sock_get_cipher_name(struct connection *conn)
6640{
Christopher Faulet82004142019-09-10 10:12:03 +02006641 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006642
Willy Tarreau1057bee2021-10-06 11:38:44 +02006643 if (!conn_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006644 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006645 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006646 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006647}
6648
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006649/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006650const char *ssl_sock_get_proto_version(struct connection *conn)
6651{
Christopher Faulet82004142019-09-10 10:12:03 +02006652 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006653
Willy Tarreau1057bee2021-10-06 11:38:44 +02006654 if (!conn_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006655 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006656 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006657 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006658}
6659
Olivier Houchardab28a322018-12-21 19:45:40 +01006660void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6661{
6662#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02006663 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006664
Willy Tarreau1057bee2021-10-06 11:38:44 +02006665 if (!conn_is_ssl(conn))
Olivier Houcharde488ea82019-06-28 14:10:33 +02006666 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006667 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006668 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006669#endif
6670}
6671
Willy Tarreau119a4082016-12-22 21:58:38 +01006672/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6673 * to disable SNI.
6674 */
Willy Tarreau63076412015-07-10 11:33:32 +02006675void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6676{
6677#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006678 struct ssl_sock_ctx *ctx;
William Lallemande18d4e82021-11-17 02:59:21 +01006679 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006680 char *prev_name;
6681
Willy Tarreau1057bee2021-10-06 11:38:44 +02006682 if (!conn_is_ssl(conn))
Willy Tarreau63076412015-07-10 11:33:32 +02006683 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006684
6685 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6686 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6687
Christopher Faulet82004142019-09-10 10:12:03 +02006688 ctx = conn->xprt_ctx;
William Lallemande18d4e82021-11-17 02:59:21 +01006689 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006690
Willy Tarreau119a4082016-12-22 21:58:38 +01006691 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006692 * new connection will present a new SNI. compare with the SNI
6693 * previously stored in the reused_sess */
6694 /* the RWLOCK is used to ensure that we are not trying to flush the
6695 * cache from the CLI */
6696
6697 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6698 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006699 if ((!prev_name && hostname) ||
6700 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006701 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006702 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006703
Olivier Houchard66ab4982019-02-26 18:37:15 +01006704 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006705#endif
6706}
6707
Emeric Brun0abf8362014-06-24 18:26:41 +02006708/* Extract peer certificate's common name into the chunk dest
6709 * Returns
6710 * the len of the extracted common name
6711 * or 0 if no CN found in DN
6712 * or -1 on error case (i.e. no peer certificate)
6713 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006714int ssl_sock_get_remote_common_name(struct connection *conn,
6715 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006716{
Christopher Faulet82004142019-09-10 10:12:03 +02006717 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04006718 X509 *crt = NULL;
6719 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006720 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006721 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006722 .area = (char *)&find_cn,
6723 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006724 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006725 int result = -1;
David Safb76832014-05-08 23:42:08 -04006726
Willy Tarreau1057bee2021-10-06 11:38:44 +02006727 if (!conn_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02006728 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02006729 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006730
6731 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006732 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006733 if (!crt)
6734 goto out;
6735
6736 name = X509_get_subject_name(crt);
6737 if (!name)
6738 goto out;
David Safb76832014-05-08 23:42:08 -04006739
Emeric Brun0abf8362014-06-24 18:26:41 +02006740 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6741out:
David Safb76832014-05-08 23:42:08 -04006742 if (crt)
6743 X509_free(crt);
6744
6745 return result;
6746}
6747
Dave McCowan328fb582014-07-30 10:39:13 -04006748/* returns 1 if client passed a certificate for this session, 0 if not */
6749int ssl_sock_get_cert_used_sess(struct connection *conn)
6750{
Christopher Faulet82004142019-09-10 10:12:03 +02006751 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006752 X509 *crt = NULL;
6753
Willy Tarreau1057bee2021-10-06 11:38:44 +02006754 if (!conn_is_ssl(conn))
Dave McCowan328fb582014-07-30 10:39:13 -04006755 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006756 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006757
6758 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006759 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006760 if (!crt)
6761 return 0;
6762
6763 X509_free(crt);
6764 return 1;
6765}
6766
6767/* returns 1 if client passed a certificate for this connection, 0 if not */
6768int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006769{
Christopher Faulet82004142019-09-10 10:12:03 +02006770 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006771
Willy Tarreau1057bee2021-10-06 11:38:44 +02006772 if (!conn_is_ssl(conn))
David Safb76832014-05-08 23:42:08 -04006773 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006774 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006775 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006776}
6777
6778/* returns result from SSL verify */
6779unsigned int ssl_sock_get_verify_result(struct connection *conn)
6780{
Christopher Faulet82004142019-09-10 10:12:03 +02006781 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006782
Willy Tarreau1057bee2021-10-06 11:38:44 +02006783 if (!conn_is_ssl(conn))
David Safb76832014-05-08 23:42:08 -04006784 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006785 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006786 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006787}
6788
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006789/* Returns the application layer protocol name in <str> and <len> when known.
6790 * Zero is returned if the protocol name was not found, otherwise non-zero is
6791 * returned. The string is allocated in the SSL context and doesn't have to be
6792 * freed by the caller. NPN is also checked if available since older versions
6793 * of openssl (1.0.1) which are more common in field only support this one.
6794 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01006795int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006796{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006797#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6798 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006799 struct ssl_sock_ctx *ctx = xprt_ctx;
6800 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006801 return 0;
6802
6803 *str = NULL;
6804
6805#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006806 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006807 if (*str)
6808 return 1;
6809#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006810#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006811 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006812 if (*str)
6813 return 1;
6814#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006815#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006816 return 0;
6817}
6818
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006819/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006820int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006821{
6822 X509 *ca;
6823 X509_NAME *name = NULL;
6824 ASN1_OCTET_STRING *skid = NULL;
6825 STACK_OF(X509) *chain = NULL;
6826 struct issuer_chain *issuer;
6827 struct eb64_node *node;
6828 char *path;
6829 u64 key;
6830 int ret = 0;
6831
6832 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6833 if (chain == NULL) {
6834 chain = sk_X509_new_null();
6835 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6836 name = X509_get_subject_name(ca);
6837 }
6838 if (!sk_X509_push(chain, ca)) {
6839 X509_free(ca);
6840 goto end;
6841 }
6842 }
6843 if (!chain) {
6844 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6845 goto end;
6846 }
6847 if (!skid) {
6848 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6849 goto end;
6850 }
6851 if (!name) {
6852 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6853 goto end;
6854 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006855 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006856 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006857 issuer = container_of(node, typeof(*issuer), node);
6858 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6859 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6860 goto end;
6861 }
6862 }
6863 issuer = calloc(1, sizeof *issuer);
6864 path = strdup(fp);
6865 if (!issuer || !path) {
6866 free(issuer);
6867 free(path);
6868 goto end;
6869 }
6870 issuer->node.key = key;
6871 issuer->path = path;
6872 issuer->chain = chain;
6873 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006874 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006875 ret = 1;
6876 end:
6877 if (skid)
6878 ASN1_OCTET_STRING_free(skid);
6879 if (chain)
6880 sk_X509_pop_free(chain, X509_free);
6881 return ret;
6882}
6883
William Lallemandda8584c2020-05-14 10:14:37 +02006884 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006885{
6886 AUTHORITY_KEYID *akid;
6887 struct issuer_chain *issuer = NULL;
6888
6889 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006890 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006891 struct eb64_node *node;
6892 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006893 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006894 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6895 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6896 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6897 issuer = ti;
6898 break;
6899 }
6900 }
6901 AUTHORITY_KEYID_free(akid);
6902 }
6903 return issuer;
6904}
6905
William Lallemanddad31052020-05-14 17:47:32 +02006906void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006907{
6908 struct eb64_node *node, *back;
6909 struct issuer_chain *issuer;
6910
William Lallemande0f3fd52020-02-25 14:53:06 +01006911 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006912 while (node) {
6913 issuer = container_of(node, typeof(*issuer), node);
6914 back = eb64_next(node);
6915 eb64_delete(node);
6916 free(issuer->path);
6917 sk_X509_pop_free(issuer->chain, X509_free);
6918 free(issuer);
6919 node = back;
6920 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006921}
6922
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006923#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006924static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006925 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006926
Emeric Brun3854e012017-05-17 20:42:48 +02006927 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006928 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006929 err_code = ERR_ABORT;
6930 }
6931 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006932}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006933#endif
6934
Willy Tarreaude5675a2021-01-20 14:41:29 +01006935/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006936 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006937 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006938static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006939{
6940 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006941 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006942
6943 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006944 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006945
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006946 if (sctx->conn != conn) {
6947 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6948 ret = 1;
6949 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01006950 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6951
6952 if (sctx->xprt) {
6953 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6954 if (sctx->xprt_ctx)
6955 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6956 }
6957
6958 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006959
6960 /* as soon as a shutdown is reported the lower layer unregisters its
6961 * subscriber, so the situations below are transient and rare enough to
6962 * be reported as suspicious. In any case they shouldn't last.
6963 */
6964 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
6965 ret = 1;
6966 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
6967 ret = 1;
6968
Willy Tarreaude5675a2021-01-20 14:41:29 +01006969 chunk_appendf(&trash, " .subs=%p", sctx->subs);
6970 if (sctx->subs) {
6971 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006972 if (sctx->subs->tasklet->calls >= 1000000)
6973 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006974 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
6975 sctx->subs->tasklet->calls,
6976 sctx->subs->tasklet->context);
6977 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
6978 chunk_appendf(&trash, ")");
6979 }
6980 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
6981 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006982 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006983}
6984
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006985#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02006986/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006987 * each reference. The variable <ref> must point to the current node's list
6988 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02006989 */
William Lallemand32af2032016-10-29 18:09:35 +02006990static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006991struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02006992{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006993 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006994 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02006995
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006996 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006997 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006998 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02006999
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007000 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007001}
7002
7003static inline
7004struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7005{
7006 int id;
7007 char *error;
7008
7009 /* If the reference starts by a '#', this is numeric id. */
7010 if (reference[0] == '#') {
7011 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7012 id = strtol(reference + 1, &error, 10);
7013 if (*error != '\0')
7014 return NULL;
7015
7016 /* Perform the unique id lookup. */
7017 return tlskeys_ref_lookupid(id);
7018 }
7019
7020 /* Perform the string lookup. */
7021 return tlskeys_ref_lookup(reference);
7022}
7023#endif
7024
7025
7026#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7027
7028static int cli_io_handler_tlskeys_files(struct appctx *appctx);
7029
7030static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
7031 return cli_io_handler_tlskeys_files(appctx);
7032}
7033
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007034/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
7035 * (next index to be dumped), and cli.p0 (next key reference).
7036 */
William Lallemand32af2032016-10-29 18:09:35 +02007037static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
7038
7039 struct stream_interface *si = appctx->owner;
7040
7041 switch (appctx->st2) {
7042 case STAT_ST_INIT:
7043 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007044 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02007045 * later and restart at the state "STAT_ST_INIT".
7046 */
7047 chunk_reset(&trash);
7048
7049 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
7050 chunk_appendf(&trash, "# id secret\n");
7051 else
7052 chunk_appendf(&trash, "# id (file)\n");
7053
Willy Tarreau06d80a92017-10-19 14:32:15 +02007054 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01007055 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02007056 return 0;
7057 }
7058
William Lallemand32af2032016-10-29 18:09:35 +02007059 /* Now, we start the browsing of the references lists.
7060 * Note that the following call to LIST_ELEM return bad pointer. The only
7061 * available field of this pointer is <list>. It is used with the function
7062 * tlskeys_list_get_next() for retruning the first available entry
7063 */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007064 if (appctx->ctx.cli.p0 == NULL)
7065 appctx->ctx.cli.p0 = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007066
7067 appctx->st2 = STAT_ST_LIST;
7068 /* fall through */
7069
7070 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007071 while (appctx->ctx.cli.p0) {
7072 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02007073
7074 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007075 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007076 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007077
7078 if (appctx->ctx.cli.i1 == 0)
7079 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7080
William Lallemand32af2032016-10-29 18:09:35 +02007081 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007082 int head;
7083
7084 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7085 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007086 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007087 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007088
7089 chunk_reset(t2);
7090 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007091 if (ref->key_size_bits == 128) {
7092 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
7093 sizeof(struct tls_sess_key_128),
7094 t2->area, t2->size);
7095 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
7096 t2->area);
7097 }
7098 else if (ref->key_size_bits == 256) {
7099 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
7100 sizeof(struct tls_sess_key_256),
7101 t2->area, t2->size);
7102 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
7103 t2->area);
7104 }
7105 else {
7106 /* This case should never happen */
7107 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
7108 }
William Lallemand32af2032016-10-29 18:09:35 +02007109
Willy Tarreau06d80a92017-10-19 14:32:15 +02007110 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007111 /* let's try again later from this stream. We add ourselves into
7112 * this stream's users so that it can remove us upon termination.
7113 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007114 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01007115 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02007116 return 0;
7117 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007118 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02007119 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007120 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007121 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007122 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02007123 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007124 /* let's try again later from this stream. We add ourselves into
7125 * this stream's users so that it can remove us upon termination.
7126 */
Willy Tarreaudb398432018-11-15 11:08:52 +01007127 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02007128 return 0;
7129 }
7130
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007131 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007132 break;
7133
7134 /* get next list entry and check the end of the list */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007135 appctx->ctx.cli.p0 = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007136 }
7137
7138 appctx->st2 = STAT_ST_FIN;
7139 /* fall through */
7140
7141 default:
7142 appctx->st2 = STAT_ST_FIN;
7143 return 1;
7144 }
7145 return 0;
7146}
7147
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007148/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007149static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007150{
William Lallemand32af2032016-10-29 18:09:35 +02007151 /* no parameter, shows only file list */
7152 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007153 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02007154 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007155 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007156 }
7157
7158 if (args[2][0] == '*') {
7159 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007160 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02007161 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007162 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02007163 if (!appctx->ctx.cli.p0)
7164 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007165 }
William Lallemand32af2032016-10-29 18:09:35 +02007166 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007167 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007168}
7169
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007170static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007171{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007172 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007173 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007174
William Lallemand32af2032016-10-29 18:09:35 +02007175 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007176 if (!*args[3] || !*args[4])
7177 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 +02007178
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007179 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02007180 if (!ref)
7181 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007182
Willy Tarreau1c913e42018-08-22 05:26:57 +02007183 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007184 if (ret < 0)
7185 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01007186
Willy Tarreau1c913e42018-08-22 05:26:57 +02007187 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02007188 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7189 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007190
Willy Tarreau9d008692019-08-09 11:21:01 +02007191 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007192}
William Lallemandd4f946c2019-12-05 10:26:40 +01007193#endif
William Lallemand419e6342020-04-08 12:05:39 +02007194
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007195static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007196{
7197#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
7198 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007199 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007200
7201 if (!payload)
7202 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02007203
7204 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007205 if (!*payload)
7206 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007207
7208 /* remove \r and \n from the payload */
7209 for (i = 0, j = 0; payload[i]; i++) {
7210 if (payload[i] == '\r' || payload[i] == '\n')
7211 continue;
7212 payload[j++] = payload[i];
7213 }
7214 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007215
Willy Tarreau1c913e42018-08-22 05:26:57 +02007216 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007217 if (ret < 0)
7218 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007219
Willy Tarreau1c913e42018-08-22 05:26:57 +02007220 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02007221 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02007222 if (err)
7223 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
7224 else
7225 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007226 }
Willy Tarreau9d008692019-08-09 11:21:01 +02007227
7228 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007229#else
Willy Tarreau9d008692019-08-09 11:21:01 +02007230 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 +02007231#endif
7232
Elliot Otchet71f82972020-01-15 08:12:14 -05007233}
7234
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007235
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007236#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007237static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx);
7238#endif
7239
7240/* parsing function for 'show ssl ocsp-response [id]' */
7241static int cli_parse_show_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
7242{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007243#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007244 if (*args[3]) {
7245 struct certificate_ocsp *ocsp = NULL;
7246 char *key = NULL;
7247 int key_length = 0;
7248
7249 if (strlen(args[3]) > OCSP_MAX_CERTID_ASN1_LENGTH*2) {
7250 return cli_err(appctx, "'show ssl ocsp-response' received a too big key.\n");
7251 }
7252
7253 if (parse_binary(args[3], &key, &key_length, NULL)) {
7254
7255 char full_key[OCSP_MAX_CERTID_ASN1_LENGTH] = {};
7256 memcpy(full_key, key, key_length);
7257
7258 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, full_key, OCSP_MAX_CERTID_ASN1_LENGTH);
7259 }
7260 if (key)
7261 ha_free(&key);
7262
7263 if (!ocsp) {
7264 return cli_err(appctx, "Certificate ID does not match any certificate.\n");
7265 }
7266
7267 appctx->ctx.cli.p0 = ocsp;
7268 appctx->io_handler = cli_io_handler_show_ocspresponse_detail;
7269 }
7270
7271 return 0;
7272
7273#else
7274 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7275#endif
7276}
7277
7278
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007279#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007280/*
7281 * This function dumps the details of an OCSP_CERTID. It is based on
7282 * ocsp_certid_print in OpenSSL.
7283 */
7284static inline int ocsp_certid_print(BIO *bp, OCSP_CERTID *certid, int indent)
7285{
7286 ASN1_OCTET_STRING *piNameHash = NULL;
7287 ASN1_OCTET_STRING *piKeyHash = NULL;
7288 ASN1_INTEGER *pSerial = NULL;
7289
7290 if (OCSP_id_get0_info(&piNameHash, NULL, &piKeyHash, &pSerial, certid)) {
7291
7292 BIO_printf(bp, "%*sCertificate ID:\n", indent, "");
7293 indent += 2;
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007294 BIO_printf(bp, "%*sIssuer Name Hash: ", indent, "");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007295 i2a_ASN1_STRING(bp, piNameHash, 0);
7296 BIO_printf(bp, "\n%*sIssuer Key Hash: ", indent, "");
7297 i2a_ASN1_STRING(bp, piKeyHash, 0);
7298 BIO_printf(bp, "\n%*sSerial Number: ", indent, "");
7299 i2a_ASN1_INTEGER(bp, pSerial);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007300 }
7301 return 1;
7302}
7303#endif
7304
7305/*
7306 * IO handler of "show ssl ocsp-response". The command taking a specific ID
7307 * is managed in cli_io_handler_show_ocspresponse_detail.
7308 */
7309static int cli_io_handler_show_ocspresponse(struct appctx *appctx)
7310{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007311#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007312 struct buffer *trash = alloc_trash_chunk();
7313 struct buffer *tmp = NULL;
7314 struct ebmb_node *node;
7315 struct stream_interface *si = appctx->owner;
7316 struct certificate_ocsp *ocsp = NULL;
7317 BIO *bio = NULL;
7318 int write = -1;
7319
7320 if (trash == NULL)
7321 return 1;
7322
7323 tmp = alloc_trash_chunk();
7324 if (!tmp)
7325 goto end;
7326
7327 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7328 goto end;
7329
7330 if (!appctx->ctx.cli.p0) {
7331 chunk_appendf(trash, "# Certificate IDs\n");
7332 node = ebmb_first(&cert_ocsp_tree);
7333 } else {
7334 node = &((struct certificate_ocsp *)appctx->ctx.cli.p0)->key;
7335 }
7336
7337 while (node) {
7338 OCSP_CERTID *certid = NULL;
7339 const unsigned char *p = NULL;
7340 int i;
7341
7342 ocsp = ebmb_entry(node, struct certificate_ocsp, key);
7343
7344 /* Dump the key in hexadecimal */
7345 chunk_appendf(trash, "Certificate ID key : ");
7346 for (i = 0; i < ocsp->key_length; ++i) {
7347 chunk_appendf(trash, "%02x", ocsp->key_data[i]);
7348 }
7349 chunk_appendf(trash, "\n");
7350
7351 p = ocsp->key_data;
7352
7353 /* Decode the certificate ID (serialized into the key). */
7354 d2i_OCSP_CERTID(&certid, &p, ocsp->key_length);
7355
7356 /* Dump the CERTID info */
7357 ocsp_certid_print(bio, certid, 1);
7358 write = BIO_read(bio, tmp->area, tmp->size-1);
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007359 /* strip trailing LFs */
7360 while (write > 0 && tmp->area[write-1] == '\n')
7361 write--;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007362 tmp->area[write] = '\0';
7363
7364 chunk_appendf(trash, "%s\n", tmp->area);
7365
7366 node = ebmb_next(node);
7367 if (ci_putchk(si_ic(si), trash) == -1) {
7368 si_rx_room_blk(si);
7369 goto yield;
7370 }
7371 }
7372
7373end:
7374 appctx->ctx.cli.p0 = NULL;
7375 if (trash)
7376 free_trash_chunk(trash);
7377 if (tmp)
7378 free_trash_chunk(tmp);
7379 if (bio)
7380 BIO_free(bio);
7381 return 1;
7382
7383yield:
7384
7385 if (trash)
7386 free_trash_chunk(trash);
7387 if (tmp)
7388 free_trash_chunk(tmp);
7389 if (bio)
7390 BIO_free(bio);
7391 appctx->ctx.cli.p0 = ocsp;
7392 return 0;
7393#else
7394 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7395#endif
7396}
7397
7398
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007399#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007400/*
7401 * Dump the details about an OCSP response in DER format stored in
7402 * <ocsp_response> into buffer <out>.
7403 * Returns 0 in case of success.
7404 */
7405int ssl_ocsp_response_print(struct buffer *ocsp_response, struct buffer *out)
7406{
7407 BIO *bio = NULL;
7408 int write = -1;
7409 OCSP_RESPONSE *resp;
7410 const unsigned char *p;
7411
7412 if (!ocsp_response)
7413 return -1;
7414
7415 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7416 return -1;
7417
7418 p = (const unsigned char*)ocsp_response->area;
7419
7420 resp = d2i_OCSP_RESPONSE(NULL, &p, ocsp_response->data);
7421 if (!resp) {
7422 chunk_appendf(out, "Unable to parse OCSP response");
7423 return -1;
7424 }
7425
7426 if (OCSP_RESPONSE_print(bio, resp, 0) != 0) {
7427 write = BIO_read(bio, out->area, out->size - 1);
7428 out->area[write] = '\0';
7429 out->data = write;
7430 }
7431
7432 if (bio)
7433 BIO_free(bio);
7434
7435 return 0;
7436}
7437
7438/*
7439 * Dump the details of the OCSP response of ID <ocsp_certid> into buffer <out>.
7440 * Returns 0 in case of success.
7441 */
7442int ssl_get_ocspresponse_detail(unsigned char *ocsp_certid, struct buffer *out)
7443{
7444 struct certificate_ocsp *ocsp;
7445
7446 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, ocsp_certid, OCSP_MAX_CERTID_ASN1_LENGTH);
7447 if (!ocsp)
7448 return -1;
7449
7450 return ssl_ocsp_response_print(&ocsp->response, out);
7451}
7452
7453
7454/* IO handler of details "show ssl ocsp-response <id>". */
7455static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx)
7456{
7457 struct buffer *trash = alloc_trash_chunk();
7458 struct certificate_ocsp *ocsp = NULL;
7459 struct stream_interface *si = appctx->owner;
7460
7461 ocsp = appctx->ctx.cli.p0;
7462
7463 if (trash == NULL)
7464 return 1;
7465
7466 ssl_ocsp_response_print(&ocsp->response, trash);
7467
7468 if (ci_putchk(si_ic(si), trash) == -1) {
7469 si_rx_room_blk(si);
7470 goto yield;
7471 }
7472 appctx->ctx.cli.p0 = NULL;
7473 if (trash)
7474 free_trash_chunk(trash);
7475 return 1;
7476
7477yield:
7478 if (trash)
7479 free_trash_chunk(trash);
7480
7481 return 0;
7482}
7483#endif
7484
William Lallemand32af2032016-10-29 18:09:35 +02007485/* register cli keywords */
7486static struct cli_kw_list cli_kws = {{ },{
7487#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007488 { { "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 },
7489 { { "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 +02007490#endif
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007491 { { "set", "ssl", "ocsp-response", NULL }, "set ssl ocsp-response <resp|payload> : update a certificate's OCSP Response from a base64-encode DER", cli_parse_set_ocspresponse, NULL },
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007492
7493 { { "show", "ssl", "ocsp-response", NULL },"show ssl ocsp-response [id] : display the IDs of the OCSP responses used in memory, or the details of a single OCSP response", cli_parse_show_ocspresponse, cli_io_handler_show_ocspresponse, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02007494 { { NULL }, NULL, NULL, NULL }
7495}};
7496
Willy Tarreau0108d902018-11-25 19:14:37 +01007497INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007498
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007499/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007500struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007501 .snd_buf = ssl_sock_from_buf,
7502 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007503 .subscribe = ssl_subscribe,
7504 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007505 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007506 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007507 .rcv_pipe = NULL,
7508 .snd_pipe = NULL,
7509 .shutr = NULL,
7510 .shutw = ssl_sock_shutw,
7511 .close = ssl_sock_close,
7512 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007513 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007514 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007515 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007516 .prepare_srv = ssl_sock_prepare_srv_ctx,
7517 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007518 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007519 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007520 .set_idle = ssl_set_idle,
7521 .set_used = ssl_set_used,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007522 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007523 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007524};
7525
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007526enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7527 struct session *sess, struct stream *s, int flags)
7528{
7529 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007530 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007531
7532 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007533 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007534
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007535 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007536 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007537 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007538 s->req.flags |= CF_READ_NULL;
7539 return ACT_RET_YIELD;
7540 }
7541 }
7542 return (ACT_RET_CONT);
7543}
7544
7545static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7546{
7547 rule->action_ptr = ssl_action_wait_for_hs;
7548
7549 return ACT_RET_PRS_OK;
7550}
7551
7552static struct action_kw_list http_req_actions = {ILH, {
7553 { "wait-for-handshake", ssl_parse_wait_for_hs },
7554 { /* END */ }
7555}};
7556
Willy Tarreau0108d902018-11-25 19:14:37 +01007557INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7558
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007559#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007560
7561static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7562{
7563 if (ptr) {
7564 chunk_destroy(ptr);
7565 free(ptr);
7566 }
7567}
7568
7569#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007570
7571#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7572static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7573{
7574 struct ocsp_cbk_arg *ocsp_arg;
7575
7576 if (ptr) {
7577 ocsp_arg = ptr;
7578
7579 if (ocsp_arg->is_single) {
7580 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
7581 ocsp_arg->s_ocsp = NULL;
7582 } else {
7583 int i;
7584
7585 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
7586 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
7587 ocsp_arg->m_ocsp[i] = NULL;
7588 }
7589 }
7590 free(ocsp_arg);
7591 }
7592}
7593#endif
7594
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007595static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7596{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007597 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007598}
William Lallemand7d42ef52020-07-06 11:41:30 +02007599
William Lallemand722180a2021-06-09 16:46:12 +02007600#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007601static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7602{
7603 struct ssl_keylog *keylog;
7604
7605 if (!ptr)
7606 return;
7607
7608 keylog = ptr;
7609
7610 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7611 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7612 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7613 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7614 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7615 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7616 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7617 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7618
7619 pool_free(pool_head_ssl_keylog, ptr);
7620}
7621#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007622
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007623static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7624{
7625 if (!ptr)
7626 return;
7627
7628 X509_free((X509*)ptr);
7629}
7630
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007631static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7632{
7633 pool_free(ssl_sock_client_sni_pool, ptr);
7634}
7635
Emeric Brun46591952012-05-18 15:47:34 +02007636__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02007637static void __ssl_sock_init(void)
7638{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007639#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007640 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007641 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007642#endif
Emeric Brun46591952012-05-18 15:47:34 +02007643
Willy Tarreauef934602016-12-22 23:12:01 +01007644 if (global_ssl.listen_default_ciphers)
7645 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7646 if (global_ssl.connect_default_ciphers)
7647 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007648#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007649 if (global_ssl.listen_default_ciphersuites)
7650 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7651 if (global_ssl.connect_default_ciphersuites)
7652 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7653#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007654
Willy Tarreau13e14102016-12-22 20:25:26 +01007655 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007656#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007657 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007658#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007659#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007660 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007661 n = sk_SSL_COMP_num(cm);
7662 while (n--) {
7663 (void) sk_SSL_COMP_pop(cm);
7664 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007665#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007666
Willy Tarreau5db847a2019-05-09 14:13:35 +02007667#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007668 ssl_locking_init();
7669#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007670#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007671 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7672#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007673
7674#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7675 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7676#endif
7677
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007678 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007679 ssl_capture_ptr_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_capture_free_func);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01007680#ifdef USE_QUIC
7681 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7682#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02007683#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007684 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7685#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007686 ssl_client_crt_ref_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_clt_crt_free_func);
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007687 ssl_client_sni_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_clt_sni_free_func);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007688#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007689 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007690 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007691#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007692#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7693 hap_register_post_check(tlskeys_finalize_config);
7694#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007695
7696 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7697 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7698
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007699 hap_register_post_deinit(ssl_free_global_issuers);
7700
Willy Tarreau80713382018-11-26 10:19:54 +01007701#ifndef OPENSSL_NO_DH
7702 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7703 hap_register_post_deinit(ssl_free_dh);
7704#endif
7705#ifndef OPENSSL_NO_ENGINE
7706 hap_register_post_deinit(ssl_free_engines);
7707#endif
7708 /* Load SSL string for the verbose & debug mode. */
7709 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02007710 ha_meth = BIO_meth_new(0x666, "ha methods");
7711 BIO_meth_set_write(ha_meth, ha_ssl_write);
7712 BIO_meth_set_read(ha_meth, ha_ssl_read);
7713 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7714 BIO_meth_set_create(ha_meth, ha_ssl_new);
7715 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7716 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7717 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007718
7719 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007720
Dragan Dosen9ac98092020-05-11 15:51:45 +02007721 /* Try to register dedicated SSL/TLS protocol message callbacks for
7722 * heartbleed attack (CVE-2014-0160) and clienthello.
7723 */
7724 hap_register_post_check(ssl_sock_register_msg_callbacks);
7725
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007726 /* Try to free all callbacks that were registered by using
7727 * ssl_sock_register_msg_callback().
7728 */
7729 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007730}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007731
Willy Tarreau80713382018-11-26 10:19:54 +01007732/* Compute and register the version string */
7733static void ssl_register_build_options()
7734{
7735 char *ptr = NULL;
7736 int i;
7737
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007738 memprintf(&ptr, "Built with OpenSSL version : "
7739#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007740 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007741#else /* OPENSSL_IS_BORINGSSL */
7742 OPENSSL_VERSION_TEXT
7743 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007744 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007745 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007746#endif
7747 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007748#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007749 "no (library version too old)"
7750#elif defined(OPENSSL_NO_TLSEXT)
7751 "no (disabled via OPENSSL_NO_TLSEXT)"
7752#else
7753 "yes"
7754#endif
7755 "", ptr);
7756
7757 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7758#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7759 "yes"
7760#else
7761#ifdef OPENSSL_NO_TLSEXT
7762 "no (because of OPENSSL_NO_TLSEXT)"
7763#else
7764 "no (version might be too old, 0.9.8f min needed)"
7765#endif
7766#endif
7767 "", ptr);
7768
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007769 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7770 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7771 if (methodVersions[i].option)
7772 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007773
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007774 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007775}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007776
Willy Tarreau80713382018-11-26 10:19:54 +01007777INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007778
Emeric Brun46591952012-05-18 15:47:34 +02007779
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007780#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007781void ssl_free_engines(void) {
7782 struct ssl_engine_list *wl, *wlb;
7783 /* free up engine list */
7784 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7785 ENGINE_finish(wl->e);
7786 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007787 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007788 free(wl);
7789 }
7790}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007791#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007792
Remi Gacogned3a23c32015-05-28 16:39:47 +02007793#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007794void ssl_free_dh(void) {
7795 if (local_dh_1024) {
7796 DH_free(local_dh_1024);
7797 local_dh_1024 = NULL;
7798 }
7799 if (local_dh_2048) {
7800 DH_free(local_dh_2048);
7801 local_dh_2048 = NULL;
7802 }
7803 if (local_dh_4096) {
7804 DH_free(local_dh_4096);
7805 local_dh_4096 = NULL;
7806 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007807 if (global_dh) {
7808 DH_free(global_dh);
7809 global_dh = NULL;
7810 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007811}
7812#endif
7813
7814__attribute__((destructor))
7815static void __ssl_sock_deinit(void)
7816{
7817#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007818 if (ssl_ctx_lru_tree) {
7819 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007820 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007821 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007822#endif
7823
Willy Tarreau5db847a2019-05-09 14:13:35 +02007824#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007825 ERR_remove_state(0);
7826 ERR_free_strings();
7827
7828 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007829#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007830
Willy Tarreau5db847a2019-05-09 14:13:35 +02007831#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007832 CRYPTO_cleanup_all_ex_data();
7833#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007834 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007835}
7836
William Dauchyf6370442020-11-14 19:25:33 +01007837
Emeric Brun46591952012-05-18 15:47:34 +02007838/*
7839 * Local variables:
7840 * c-indent-level: 8
7841 * c-basic-offset: 8
7842 * End:
7843 */