blob: c725f1ff2909568663f01764b7d137d198a7b4f1 [file] [log] [blame]
yanbzhu08ce6ab2015-12-02 13:01:29 -05001
Emeric Brun46591952012-05-18 15:47:34 +02002/*
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02003 * SSL/TLS transport layer over SOCK_STREAM sockets
Emeric Brun46591952012-05-18 15:47:34 +02004 *
5 * Copyright (C) 2012 EXCELIANCE, Emeric Brun <ebrun@exceliance.fr>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 *
Willy Tarreau69845df2012-09-10 09:43:09 +020012 * Acknowledgement:
13 * We'd like to specially thank the Stud project authors for a very clean
14 * and well documented code which helped us understand how the OpenSSL API
15 * ought to be used in non-blocking mode. This is one difficult part which
16 * is not easy to get from the OpenSSL doc, and reading the Stud code made
17 * it much more obvious than the examples in the OpenSSL package. Keep up
18 * the good works, guys !
19 *
20 * Stud is an extremely efficient and scalable SSL/TLS proxy which combines
21 * particularly well with haproxy. For more info about this project, visit :
22 * https://github.com/bumptech/stud
23 *
Emeric Brun46591952012-05-18 15:47:34 +020024 */
25
Willy Tarreau8d164dc2019-05-10 09:35:00 +020026/* Note: do NOT include openssl/xxx.h here, do it in openssl-compat.h */
Emeric Brun46591952012-05-18 15:47:34 +020027#define _GNU_SOURCE
Emeric Brunfc0421f2012-09-07 17:30:07 +020028#include <ctype.h>
29#include <dirent.h>
Emeric Brun46591952012-05-18 15:47:34 +020030#include <errno.h>
31#include <fcntl.h>
32#include <stdio.h>
33#include <stdlib.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020034#include <string.h>
35#include <unistd.h>
Emeric Brun46591952012-05-18 15:47:34 +020036
37#include <sys/socket.h>
38#include <sys/stat.h>
39#include <sys/types.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020040#include <netdb.h>
Emeric Brun46591952012-05-18 15:47:34 +020041#include <netinet/tcp.h>
42
Willy Tarreaub2551052020-06-09 09:07:15 +020043#include <import/ebpttree.h>
44#include <import/ebsttree.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020045#include <import/lru.h>
46#include <import/xxhash.h>
47
Willy Tarreaub2551052020-06-09 09:07:15 +020048#include <haproxy/api.h>
49#include <haproxy/arg.h>
50#include <haproxy/base64.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020051#include <haproxy/channel.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020052#include <haproxy/chunk.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020053#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020054#include <haproxy/connection.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020055#include <haproxy/dynbuf.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020056#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020057#include <haproxy/fd.h>
58#include <haproxy/freq_ctr.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020059#include <haproxy/frontend.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020060#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020061#include <haproxy/http_rules.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020062#include <haproxy/log.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020063#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020064#include <haproxy/pattern-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020065#include <haproxy/proto_tcp.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020066#include <haproxy/proxy.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020067#include <haproxy/server.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020068#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020069#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020070#include <haproxy/ssl_crtlist.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020071#include <haproxy/ssl_sock.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020072#include <haproxy/ssl_utils.h>
Amaury Denoyelle9963fa72020-11-03 17:10:00 +010073#include <haproxy/stats.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020074#include <haproxy/stream-t.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020075#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020076#include <haproxy/task.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020077#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020078#include <haproxy/time.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020079#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020080#include <haproxy/vars.h>
Frédéric Lécailleec216522020-11-23 14:33:30 +010081#include <haproxy/xprt_quic.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
Willy Tarreau71b734c2014-01-28 15:19:44 +010095int sslconns = 0;
96int totalsslconns = 0;
Emeric Brunece0c332017-12-06 13:51:49 +010097int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +020098
William Lallemande0f3fd52020-02-25 14:53:06 +010099static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
100
William Lallemand7fd8b452020-05-07 15:20:43 +0200101struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100102#ifdef LISTEN_DEFAULT_CIPHERS
103 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
104#endif
105#ifdef CONNECT_DEFAULT_CIPHERS
106 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
107#endif
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +0500108#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200109 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200110 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
111#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100112 .listen_default_ssloptions = BC_SSL_O_NONE,
113 .connect_default_ssloptions = SRV_SSL_O_NONE,
114
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200115 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
116 .listen_default_sslmethods.min = CONF_TLSV_NONE,
117 .listen_default_sslmethods.max = CONF_TLSV_NONE,
118 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
119 .connect_default_sslmethods.min = CONF_TLSV_NONE,
120 .connect_default_sslmethods.max = CONF_TLSV_NONE,
121
Willy Tarreauef934602016-12-22 23:12:01 +0100122#ifdef DEFAULT_SSL_MAX_RECORD
123 .max_record = DEFAULT_SSL_MAX_RECORD,
124#endif
125 .default_dh_param = SSL_DEFAULT_DH_PARAM,
126 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Thierry FOURNIER5bf77322017-02-25 12:45:22 +0100127 .capture_cipherlist = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100128 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200129 .extra_files_noext = 0,
William Lallemandca5cf0a2021-06-09 16:46:12 +0200130#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200131 .keylog = 0
132#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100133};
134
Olivier Houcharda8955d52019-04-07 22:00:38 +0200135static BIO_METHOD *ha_meth;
136
Olivier Houchard66ab4982019-02-26 18:37:15 +0100137DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
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/*
Emmanuel Hocdetb270e812019-11-21 19:09:31 +0100319 * deduplicate cafile (and crlfile)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200320 */
321struct cafile_entry {
322 X509_STORE *ca_store;
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200323 STACK_OF(X509_NAME) *ca_list;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200324 struct ebmb_node node;
325 char path[0];
326};
327
328static struct eb_root cafile_tree = EB_ROOT_UNIQUE;
329
330static X509_STORE* ssl_store_get0_locations_file(char *path)
331{
332 struct ebmb_node *eb;
333
334 eb = ebst_lookup(&cafile_tree, path);
335 if (eb) {
336 struct cafile_entry *ca_e;
337 ca_e = ebmb_entry(eb, struct cafile_entry, node);
338 return ca_e->ca_store;
339 }
340 return NULL;
341}
342
Remi Tricot-Le Bretonfb00f312021-03-23 16:41:53 +0100343int ssl_store_load_locations_file(char *path, int create_if_none)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200344{
Remi Tricot-Le Bretonfb00f312021-03-23 16:41:53 +0100345 X509_STORE *store = ssl_store_get0_locations_file(path);
346
347 /* If this function is called by the CLI, we should not call the
348 * X509_STORE_load_locations function because it performs forbidden disk
349 * accesses. */
350 if (!store && create_if_none) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200351 struct cafile_entry *ca_e;
Remi Tricot-Le Bretonfb00f312021-03-23 16:41:53 +0100352 store = X509_STORE_new();
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200353 if (X509_STORE_load_locations(store, path, NULL)) {
354 int pathlen;
355 pathlen = strlen(path);
356 ca_e = calloc(1, sizeof(*ca_e) + pathlen + 1);
357 if (ca_e) {
358 memcpy(ca_e->path, path, pathlen + 1);
359 ca_e->ca_store = store;
360 ebst_insert(&cafile_tree, &ca_e->node);
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200361 }
Remi Tricot-Le Bretonfb00f312021-03-23 16:41:53 +0100362 } else {
363 X509_STORE_free(store);
364 store = NULL;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200365 }
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200366 }
Remi Tricot-Le Bretonfb00f312021-03-23 16:41:53 +0100367 return (store != NULL);
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200368}
369
370/* mimic what X509_STORE_load_locations do with store_ctx */
371static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
372{
373 X509_STORE *store;
374 store = ssl_store_get0_locations_file(path);
375 if (store_ctx && store) {
376 int i;
377 X509_OBJECT *obj;
378 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
379 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
380 obj = sk_X509_OBJECT_value(objs, i);
381 switch (X509_OBJECT_get_type(obj)) {
382 case X509_LU_X509:
383 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
384 break;
385 case X509_LU_CRL:
386 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
387 break;
388 default:
389 break;
390 }
391 }
392 return 1;
393 }
394 return 0;
395}
396
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500397/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200398static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
399{
400 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
401 return ssl_set_cert_crl_file(store_ctx, path);
402}
403
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200404/*
405 Extract CA_list from CA_file already in tree.
406 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
407 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
408*/
409static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
410{
411 struct ebmb_node *eb;
412 struct cafile_entry *ca_e;
413
414 eb = ebst_lookup(&cafile_tree, path);
415 if (!eb)
416 return NULL;
417 ca_e = ebmb_entry(eb, struct cafile_entry, node);
418
419 if (ca_e->ca_list == NULL) {
420 int i;
421 unsigned long key;
422 struct eb_root ca_name_tree = EB_ROOT;
423 struct eb64_node *node, *back;
424 struct {
425 struct eb64_node node;
426 X509_NAME *xname;
427 } *ca_name;
428 STACK_OF(X509_OBJECT) *objs;
429 STACK_OF(X509_NAME) *skn;
430 X509 *x;
431 X509_NAME *xn;
432
433 skn = sk_X509_NAME_new_null();
434 /* take x509 from cafile_tree */
435 objs = X509_STORE_get0_objects(ca_e->ca_store);
436 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
437 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
438 if (!x)
439 continue;
440 xn = X509_get_subject_name(x);
441 if (!xn)
442 continue;
443 /* Check for duplicates. */
444 key = X509_NAME_hash(xn);
445 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
446 node && ca_name == NULL;
447 node = eb64_next(node)) {
448 ca_name = container_of(node, typeof(*ca_name), node);
449 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
450 ca_name = NULL;
451 }
452 /* find a duplicate */
453 if (ca_name)
454 continue;
455 ca_name = calloc(1, sizeof *ca_name);
456 xn = X509_NAME_dup(xn);
457 if (!ca_name ||
458 !xn ||
459 !sk_X509_NAME_push(skn, xn)) {
460 free(ca_name);
461 X509_NAME_free(xn);
462 sk_X509_NAME_pop_free(skn, X509_NAME_free);
463 sk_X509_NAME_free(skn);
464 skn = NULL;
465 break;
466 }
467 ca_name->node.key = key;
468 ca_name->xname = xn;
469 eb64_insert(&ca_name_tree, &ca_name->node);
470 }
471 ca_e->ca_list = skn;
472 /* remove temporary ca_name tree */
473 node = eb64_first(&ca_name_tree);
474 while (node) {
475 ca_name = container_of(node, typeof(*ca_name), node);
476 back = eb64_next(node);
477 eb64_delete(node);
478 free(ca_name);
479 node = back;
480 }
481 }
482 return ca_e->ca_list;
483}
484
Willy Tarreauff882702021-04-10 17:23:00 +0200485struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200486int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100487int ssl_app_data_index = -1;
Willy Tarreauef934602016-12-22 23:12:01 +0100488
William Lallemandca5cf0a2021-06-09 16:46:12 +0200489#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200490int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200491struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
492struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200493#endif
494
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200495#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
496struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
497#endif
498
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200499#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200500unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000501struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
502struct ssl_engine_list {
503 struct list list;
504 ENGINE *e;
505};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200506#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000507
Remi Gacogne8de54152014-07-15 11:36:40 +0200508#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200509static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200510static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200511static DH *local_dh_1024 = NULL;
512static DH *local_dh_2048 = NULL;
513static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100514static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200515#endif /* OPENSSL_NO_DH */
516
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100517#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200518/* X509V3 Extensions that will be added on generated certificates */
519#define X509V3_EXT_SIZE 5
520static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
521 "basicConstraints",
522 "nsComment",
523 "subjectKeyIdentifier",
524 "authorityKeyIdentifier",
525 "keyUsage",
526};
527static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
528 "CA:FALSE",
529 "\"OpenSSL Generated Certificate\"",
530 "hash",
531 "keyid,issuer:always",
532 "nonRepudiation,digitalSignature,keyEncipherment"
533};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200534/* LRU cache to store generated certificate */
535static struct lru64_head *ssl_ctx_lru_tree = NULL;
536static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200537static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100538__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200539
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200540#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
541
yanbzhube2774d2015-12-10 15:07:30 -0500542/* The order here matters for picking a default context,
543 * keep the most common keytype at the bottom of the list
544 */
545const char *SSL_SOCK_KEYTYPE_NAMES[] = {
546 "dsa",
547 "ecdsa",
548 "rsa"
549};
yanbzhube2774d2015-12-10 15:07:30 -0500550
William Lallemandc3cd35f2017-11-28 11:04:43 +0100551static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100552static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
553
Dragan Dosen9ac98092020-05-11 15:51:45 +0200554/* Dedicated callback functions for heartbeat and clienthello.
555 */
556#ifdef TLS1_RT_HEARTBEAT
557static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
558 int content_type, const void *buf, size_t len,
559 SSL *ssl);
560#endif
561static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
562 int content_type, const void *buf, size_t len,
563 SSL *ssl);
564
William Lallemandca5cf0a2021-06-09 16:46:12 +0200565#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200566static void ssl_init_keylog(struct connection *conn, int write_p, int version,
567 int content_type, const void *buf, size_t len,
568 SSL *ssl);
569#endif
570
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200571/* List head of all registered SSL/TLS protocol message callbacks. */
572struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
573
574/* Registers the function <func> in order to be called on SSL/TLS protocol
575 * message processing. It will return 0 if the function <func> is not set
576 * or if it fails to allocate memory.
577 */
578int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
579{
580 struct ssl_sock_msg_callback *cbk;
581
582 if (!func)
583 return 0;
584
585 cbk = calloc(1, sizeof(*cbk));
586 if (!cbk) {
587 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
588 return 0;
589 }
590
591 cbk->func = func;
592
Willy Tarreau2b718102021-04-21 07:32:39 +0200593 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200594
595 return 1;
596}
597
Dragan Dosen9ac98092020-05-11 15:51:45 +0200598/* Used to register dedicated SSL/TLS protocol message callbacks.
599 */
600static int ssl_sock_register_msg_callbacks(void)
601{
602#ifdef TLS1_RT_HEARTBEAT
603 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
604 return ERR_ABORT;
605#endif
606 if (global_ssl.capture_cipherlist > 0) {
607 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
608 return ERR_ABORT;
609 }
William Lallemandca5cf0a2021-06-09 16:46:12 +0200610#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200611 if (global_ssl.keylog > 0) {
612 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
613 return ERR_ABORT;
614 }
615#endif
616
Christopher Fauletfc633b62020-11-06 15:24:23 +0100617 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200618}
619
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200620/* Used to free all SSL/TLS protocol message callbacks that were
621 * registered by using ssl_sock_register_msg_callback().
622 */
623static void ssl_sock_unregister_msg_callbacks(void)
624{
625 struct ssl_sock_msg_callback *cbk, *cbkback;
626
627 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200628 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200629 free(cbk);
630 }
631}
632
Dragan Doseneb607fe2020-05-11 17:17:06 +0200633SSL *ssl_sock_get_ssl_object(struct connection *conn)
634{
635 if (!ssl_sock_is_ssl(conn))
636 return NULL;
637
638 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
639}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100640/*
641 * This function gives the detail of the SSL error. It is used only
642 * if the debug mode and the verbose mode are activated. It dump all
643 * the SSL error until the stack was empty.
644 */
645static forceinline void ssl_sock_dump_errors(struct connection *conn)
646{
647 unsigned long ret;
648
649 if (unlikely(global.mode & MODE_DEBUG)) {
650 while(1) {
651 ret = ERR_get_error();
652 if (ret == 0)
653 return;
Willy Tarreau566cebc2021-03-02 19:32:39 +0100654 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
655 conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100656 ERR_func_error_string(ret), ERR_reason_error_string(ret));
657 }
658 }
659}
660
yanbzhube2774d2015-12-10 15:07:30 -0500661
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200662#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200663int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000664{
665 int err_code = ERR_ABORT;
666 ENGINE *engine;
667 struct ssl_engine_list *el;
668
669 /* grab the structural reference to the engine */
670 engine = ENGINE_by_id(engine_id);
671 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100672 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000673 goto fail_get;
674 }
675
676 if (!ENGINE_init(engine)) {
677 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100678 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000679 goto fail_init;
680 }
681
682 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100683 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000684 goto fail_set_method;
685 }
686
687 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton46697c82021-05-12 17:45:21 +0200688 if (!el)
689 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000690 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200691 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100692 nb_engines++;
693 if (global_ssl.async)
694 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000695 return 0;
696
Remi Tricot-Le Breton46697c82021-05-12 17:45:21 +0200697fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000698fail_set_method:
699 /* release the functional reference from ENGINE_init() */
700 ENGINE_finish(engine);
701
702fail_init:
703 /* release the structural reference from ENGINE_by_id() */
704 ENGINE_free(engine);
705
706fail_get:
707 return err_code;
708}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200709#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000710
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500711#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200712/*
713 * openssl async fd handler
714 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200715void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000716{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200717 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000718
Emeric Brun3854e012017-05-17 20:42:48 +0200719 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000720 * to poll this fd until it is requested
721 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000722 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000723 fd_cant_recv(fd);
724
725 /* crypto engine is available, let's notify the associated
726 * connection that it can pursue its processing.
727 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200728 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000729}
730
Emeric Brun3854e012017-05-17 20:42:48 +0200731/*
732 * openssl async delayed SSL_free handler
733 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200734void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000735{
736 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200737 OSSL_ASYNC_FD all_fd[32];
738 size_t num_all_fds = 0;
739 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000740
Emeric Brun3854e012017-05-17 20:42:48 +0200741 /* We suppose that the async job for a same SSL *
742 * are serialized. So if we are awake it is
743 * because the running job has just finished
744 * and we can remove all async fds safely
745 */
746 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
747 if (num_all_fds > 32) {
748 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
749 return;
750 }
751
752 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
753 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200754 fd_stop_both(all_fd[i]);
Emeric Brun3854e012017-05-17 20:42:48 +0200755
756 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000757 SSL_free(ssl);
Willy Tarreau4781b152021-04-06 13:53:36 +0200758 _HA_ATOMIC_DEC(&sslconns);
759 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000760}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000761/*
Emeric Brun3854e012017-05-17 20:42:48 +0200762 * function used to manage a returned SSL_ERROR_WANT_ASYNC
763 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000764 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200765static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000766{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100767 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200768 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200769 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000770 size_t num_add_fds = 0;
771 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200772 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000773
774 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
775 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200776 if (num_add_fds > 32 || num_del_fds > 32) {
777 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 +0000778 return;
779 }
780
Emeric Brun3854e012017-05-17 20:42:48 +0200781 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000782
Emeric Brun3854e012017-05-17 20:42:48 +0200783 /* We remove unused fds from the fdtab */
784 for (i=0 ; i < num_del_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200785 fd_stop_both(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000786
Emeric Brun3854e012017-05-17 20:42:48 +0200787 /* We add new fds to the fdtab */
788 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200789 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000790 }
791
Emeric Brun3854e012017-05-17 20:42:48 +0200792 num_add_fds = 0;
793 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
794 if (num_add_fds > 32) {
795 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
796 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000797 }
Emeric Brun3854e012017-05-17 20:42:48 +0200798
799 /* We activate the polling for all known async fds */
800 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000801 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200802 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000803 /* To ensure that the fd cache won't be used
804 * We'll prefer to catch a real RD event
805 * because handling an EAGAIN on this fd will
806 * result in a context switch and also
807 * some engines uses a fd in blocking mode.
808 */
809 fd_cant_recv(add_fd[i]);
810 }
Emeric Brun3854e012017-05-17 20:42:48 +0200811
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000812}
813#endif
814
William Lallemand104a7a62019-10-14 14:14:59 +0200815#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200816/*
817 * This function returns the number of seconds elapsed
818 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
819 * date presented un ASN1_GENERALIZEDTIME.
820 *
821 * In parsing error case, it returns -1.
822 */
823static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
824{
825 long epoch;
826 char *p, *end;
827 const unsigned short month_offset[12] = {
828 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
829 };
Remi Tricot-Le Breton1adb4392021-06-09 17:16:18 +0200830 unsigned long year, month;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200831
832 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
833
834 p = (char *)d->data;
835 end = p + d->length;
836
837 if (end - p < 4) return -1;
838 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
839 p += 4;
840 if (end - p < 2) return -1;
841 month = 10 * (p[0] - '0') + p[1] - '0';
842 if (month < 1 || month > 12) return -1;
843 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
844 We consider leap years and the current month (<marsh or not) */
845 epoch = ( ((year - 1970) * 365)
846 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
847 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
848 + month_offset[month-1]
849 ) * 24 * 60 * 60;
850 p += 2;
851 if (end - p < 2) return -1;
852 /* Add the number of seconds of completed days of current month */
853 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
854 p += 2;
855 if (end - p < 2) return -1;
856 /* Add the completed hours of the current day */
857 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
858 p += 2;
859 if (end - p < 2) return -1;
860 /* Add the completed minutes of the current hour */
861 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
862 p += 2;
863 if (p == end) return -1;
864 /* Test if there is available seconds */
865 if (p[0] < '0' || p[0] > '9')
866 goto nosec;
867 if (end - p < 2) return -1;
868 /* Add the seconds of the current minute */
869 epoch += 10 * (p[0] - '0') + p[1] - '0';
870 p += 2;
871 if (p == end) return -1;
872 /* Ignore seconds float part if present */
873 if (p[0] == '.') {
874 do {
875 if (++p == end) return -1;
876 } while (p[0] >= '0' && p[0] <= '9');
877 }
878
879nosec:
880 if (p[0] == 'Z') {
881 if (end - p != 1) return -1;
882 return epoch;
883 }
884 else if (p[0] == '+') {
885 if (end - p != 5) return -1;
886 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700887 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 +0200888 }
889 else if (p[0] == '-') {
890 if (end - p != 5) return -1;
891 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700892 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 +0200893 }
894
895 return -1;
896}
897
William Lallemand104a7a62019-10-14 14:14:59 +0200898/*
899 * struct alignment works here such that the key.key is the same as key_data
900 * Do not change the placement of key_data
901 */
902struct certificate_ocsp {
903 struct ebmb_node key;
904 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
905 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200906 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200907 long expire;
908};
909
910struct ocsp_cbk_arg {
911 int is_single;
912 int single_kt;
913 union {
914 struct certificate_ocsp *s_ocsp;
915 /*
916 * m_ocsp will have multiple entries dependent on key type
917 * Entry 0 - DSA
918 * Entry 1 - ECDSA
919 * Entry 2 - RSA
920 */
921 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
922 };
923};
924
Emeric Brun1d3865b2014-06-20 15:37:32 +0200925static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200926
927/* This function starts to check if the OCSP response (in DER format) contained
928 * in chunk 'ocsp_response' is valid (else exits on error).
929 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
930 * contained in the OCSP Response and exits on error if no match.
931 * If it's a valid OCSP Response:
932 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
933 * pointed by 'ocsp'.
934 * If 'ocsp' is NULL, the function looks up into the OCSP response's
935 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
936 * from the response) and exits on error if not found. Finally, If an OCSP response is
937 * already present in the container, it will be overwritten.
938 *
939 * Note: OCSP response containing more than one OCSP Single response is not
940 * considered valid.
941 *
942 * Returns 0 on success, 1 in error case.
943 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200944static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
945 struct certificate_ocsp *ocsp,
946 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200947{
948 OCSP_RESPONSE *resp;
949 OCSP_BASICRESP *bs = NULL;
950 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200951 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200952 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200953 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200954 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200955 int reason;
956 int ret = 1;
957
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200958 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
959 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200960 if (!resp) {
961 memprintf(err, "Unable to parse OCSP response");
962 goto out;
963 }
964
965 rc = OCSP_response_status(resp);
966 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
967 memprintf(err, "OCSP response status not successful");
968 goto out;
969 }
970
971 bs = OCSP_response_get1_basic(resp);
972 if (!bs) {
973 memprintf(err, "Failed to get basic response from OCSP Response");
974 goto out;
975 }
976
977 count_sr = OCSP_resp_count(bs);
978 if (count_sr > 1) {
979 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
980 goto out;
981 }
982
983 sr = OCSP_resp_get0(bs, 0);
984 if (!sr) {
985 memprintf(err, "Failed to get OCSP single response");
986 goto out;
987 }
988
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200989 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
990
Emeric Brun4147b2e2014-06-16 18:36:30 +0200991 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200992 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200993 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200994 goto out;
995 }
996
Emeric Brun13a6b482014-06-20 15:44:34 +0200997 if (!nextupd) {
998 memprintf(err, "OCSP single response: missing nextupdate");
999 goto out;
1000 }
1001
Emeric Brunc8b27b62014-06-19 14:16:17 +02001002 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001003 if (!rc) {
1004 memprintf(err, "OCSP single response: no longer valid.");
1005 goto out;
1006 }
1007
1008 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001009 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +02001010 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
1011 goto out;
1012 }
1013 }
1014
1015 if (!ocsp) {
1016 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
1017 unsigned char *p;
1018
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001019 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001020 if (!rc) {
1021 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
1022 goto out;
1023 }
1024
1025 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
1026 memprintf(err, "OCSP single response: Certificate ID too long");
1027 goto out;
1028 }
1029
1030 p = key;
1031 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001032 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001033 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
1034 if (!ocsp) {
1035 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
1036 goto out;
1037 }
1038 }
1039
1040 /* According to comments on "chunk_dup", the
1041 previous chunk buffer will be freed */
1042 if (!chunk_dup(&ocsp->response, ocsp_response)) {
1043 memprintf(err, "OCSP response: Memory allocation error");
1044 goto out;
1045 }
1046
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001047 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
Remi Tricot-Le Breton1adb4392021-06-09 17:16:18 +02001048 if (ocsp->expire < 0) {
1049 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1050 goto out;
1051 }
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001052
Emeric Brun4147b2e2014-06-16 18:36:30 +02001053 ret = 0;
1054out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001055 ERR_clear_error();
1056
Emeric Brun4147b2e2014-06-16 18:36:30 +02001057 if (bs)
1058 OCSP_BASICRESP_free(bs);
1059
1060 if (resp)
1061 OCSP_RESPONSE_free(resp);
1062
1063 return ret;
1064}
1065/*
1066 * External function use to update the OCSP response in the OCSP response's
1067 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1068 * to update in DER format.
1069 *
1070 * Returns 0 on success, 1 in error case.
1071 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001072int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001073{
1074 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1075}
1076
William Lallemand4a660132019-10-14 14:51:41 +02001077#endif
1078
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001079#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1080static 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)
1081{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001082 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001083 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001084 struct connection *conn;
1085 int head;
1086 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001087 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001088
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001089 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001090 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001091 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1092
1093 keys = ref->tlskeys;
1094 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001095
1096 if (enc) {
1097 memcpy(key_name, keys[head].name, 16);
1098
1099 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001100 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001101
Emeric Brun9e754772019-01-10 17:51:55 +01001102 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001103
Emeric Brun9e754772019-01-10 17:51:55 +01001104 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1105 goto end;
1106
Willy Tarreau9356dac2019-05-10 09:22:53 +02001107 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001108 ret = 1;
1109 }
1110 else if (ref->key_size_bits == 256 ) {
1111
1112 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1113 goto end;
1114
Willy Tarreau9356dac2019-05-10 09:22:53 +02001115 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001116 ret = 1;
1117 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001118 } else {
1119 for (i = 0; i < TLS_TICKETS_NO; i++) {
1120 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1121 goto found;
1122 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001123 ret = 0;
1124 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001125
Christopher Faulet16f45c82018-02-16 11:23:49 +01001126 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001127 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001128 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 +01001129 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1130 goto end;
1131 /* 2 for key renewal, 1 if current key is still valid */
1132 ret = i ? 2 : 1;
1133 }
1134 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001135 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 +01001136 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1137 goto end;
1138 /* 2 for key renewal, 1 if current key is still valid */
1139 ret = i ? 2 : 1;
1140 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001141 }
Emeric Brun9e754772019-01-10 17:51:55 +01001142
Christopher Faulet16f45c82018-02-16 11:23:49 +01001143 end:
1144 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1145 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001146}
1147
1148struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1149{
1150 struct tls_keys_ref *ref;
1151
1152 list_for_each_entry(ref, &tlskeys_reference, list)
1153 if (ref->filename && strcmp(filename, ref->filename) == 0)
1154 return ref;
1155 return NULL;
1156}
1157
1158struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1159{
1160 struct tls_keys_ref *ref;
1161
1162 list_for_each_entry(ref, &tlskeys_reference, list)
1163 if (ref->unique_id == unique_id)
1164 return ref;
1165 return NULL;
1166}
1167
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001168/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001169 * match existing ones, this function returns -1
1170 * else it returns 0 on success.
1171 */
1172int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001173 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001174{
Emeric Brun9e754772019-01-10 17:51:55 +01001175 if (ref->key_size_bits == 128) {
1176 if (tlskey->data != sizeof(struct tls_sess_key_128))
1177 return -1;
1178 }
1179 else if (ref->key_size_bits == 256) {
1180 if (tlskey->data != sizeof(struct tls_sess_key_256))
1181 return -1;
1182 }
1183 else
1184 return -1;
1185
Christopher Faulet16f45c82018-02-16 11:23:49 +01001186 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001187 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1188 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001189 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1190 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001191
1192 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001193}
1194
Willy Tarreau83061a82018-07-13 11:56:34 +02001195int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001196{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001197 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1198
1199 if(!ref) {
1200 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1201 return 1;
1202 }
Emeric Brun9e754772019-01-10 17:51:55 +01001203 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1204 memprintf(err, "Invalid key size");
1205 return 1;
1206 }
1207
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001208 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001209}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001210
1211/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001212 * automatic ids. It's called just after the basic checks. It returns
1213 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001214 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001215static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001216{
1217 int i = 0;
1218 struct tls_keys_ref *ref, *ref2, *ref3;
1219 struct list tkr = LIST_HEAD_INIT(tkr);
1220
1221 list_for_each_entry(ref, &tlskeys_reference, list) {
1222 if (ref->unique_id == -1) {
1223 /* Look for the first free id. */
1224 while (1) {
1225 list_for_each_entry(ref2, &tlskeys_reference, list) {
1226 if (ref2->unique_id == i) {
1227 i++;
1228 break;
1229 }
1230 }
1231 if (&ref2->list == &tlskeys_reference)
1232 break;
1233 }
1234
1235 /* Uses the unique id and increment it for the next entry. */
1236 ref->unique_id = i;
1237 i++;
1238 }
1239 }
1240
1241 /* This sort the reference list by id. */
1242 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001243 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001244 list_for_each_entry(ref3, &tkr, list) {
1245 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001246 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001247 break;
1248 }
1249 }
1250 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001251 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001252 }
1253
1254 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001255 LIST_INSERT(&tkr, &tlskeys_reference);
1256 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001257 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001258}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001259#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1260
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001261#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001262int ocsp_ex_index = -1;
1263
yanbzhube2774d2015-12-10 15:07:30 -05001264int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1265{
1266 switch (evp_keytype) {
1267 case EVP_PKEY_RSA:
1268 return 2;
1269 case EVP_PKEY_DSA:
1270 return 0;
1271 case EVP_PKEY_EC:
1272 return 1;
1273 }
1274
1275 return -1;
1276}
1277
Emeric Brun4147b2e2014-06-16 18:36:30 +02001278/*
1279 * Callback used to set OCSP status extension content in server hello.
1280 */
1281int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1282{
yanbzhube2774d2015-12-10 15:07:30 -05001283 struct certificate_ocsp *ocsp;
1284 struct ocsp_cbk_arg *ocsp_arg;
1285 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001286 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001287 EVP_PKEY *ssl_pkey;
1288 int key_type;
1289 int index;
1290
William Lallemand76b4a122020-08-04 17:41:39 +02001291 ctx = SSL_get_SSL_CTX(ssl);
1292 if (!ctx)
1293 return SSL_TLSEXT_ERR_NOACK;
1294
1295 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1296 if (!ocsp_arg)
1297 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001298
1299 ssl_pkey = SSL_get_privatekey(ssl);
1300 if (!ssl_pkey)
1301 return SSL_TLSEXT_ERR_NOACK;
1302
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001303 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001304
1305 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1306 ocsp = ocsp_arg->s_ocsp;
1307 else {
1308 /* For multiple certs per context, we have to find the correct OCSP response based on
1309 * the certificate type
1310 */
1311 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1312
1313 if (index < 0)
1314 return SSL_TLSEXT_ERR_NOACK;
1315
1316 ocsp = ocsp_arg->m_ocsp[index];
1317
1318 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001319
1320 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001321 !ocsp->response.area ||
1322 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001323 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001324 return SSL_TLSEXT_ERR_NOACK;
1325
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001326 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001327 if (!ssl_buf)
1328 return SSL_TLSEXT_ERR_NOACK;
1329
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001330 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1331 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001332
1333 return SSL_TLSEXT_ERR_OK;
1334}
1335
William Lallemand4a660132019-10-14 14:51:41 +02001336#endif
1337
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001338#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001339
1340
1341/*
1342 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1343 * used anymore. Also removes it from the tree if free'd.
1344 */
1345static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1346{
1347 if (!ocsp)
1348 return;
1349
1350 ocsp->refcount--;
1351 if (ocsp->refcount <= 0) {
1352 ebmb_delete(&ocsp->key);
1353 chunk_destroy(&ocsp->response);
1354 free(ocsp);
1355 }
1356}
1357
1358
Emeric Brun4147b2e2014-06-16 18:36:30 +02001359/*
1360 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001361 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1362 * status extension, the issuer's certificate is mandatory. It should be
1363 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001364 *
William Lallemand246c0242019-10-11 08:59:13 +02001365 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1366 * OCSP response. If file is empty or content is not a valid OCSP response,
1367 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1368 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001369 *
1370 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001371 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001372 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001373static 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 +02001374{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001375 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001376 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001377 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001378 struct certificate_ocsp *ocsp = NULL, *iocsp;
1379 char *warn = NULL;
1380 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001381 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001382
Emeric Brun4147b2e2014-06-16 18:36:30 +02001383
William Lallemand246c0242019-10-11 08:59:13 +02001384 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001385 if (!x)
1386 goto out;
1387
William Lallemand246c0242019-10-11 08:59:13 +02001388 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001389 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1390 if (chain) {
1391 /* check if one of the certificate of the chain is the issuer */
1392 for (i = 0; i < sk_X509_num(chain); i++) {
1393 X509 *ti = sk_X509_value(chain, i);
1394 if (X509_check_issued(ti, x) == X509_V_OK) {
1395 issuer = ti;
1396 break;
1397 }
1398 }
1399 }
William Lallemand246c0242019-10-11 08:59:13 +02001400 if (!issuer)
1401 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001402
1403 cid = OCSP_cert_to_id(0, x, issuer);
1404 if (!cid)
1405 goto out;
1406
1407 i = i2d_OCSP_CERTID(cid, NULL);
1408 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1409 goto out;
1410
Vincent Bernat02779b62016-04-03 13:48:43 +02001411 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001412 if (!ocsp)
1413 goto out;
1414
1415 p = ocsp->key_data;
1416 i2d_OCSP_CERTID(cid, &p);
1417
1418 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1419 if (iocsp == ocsp)
1420 ocsp = NULL;
1421
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001422#ifndef SSL_CTX_get_tlsext_status_cb
1423# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1424 *cb = (void (*) (void))ctx->tlsext_status_cb;
1425#endif
1426 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1427
1428 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001429 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001430 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001431
William Lallemanda560c062020-07-31 11:43:20 +02001432 cb_arg = calloc(1, sizeof(*cb_arg));
1433 if (!cb_arg)
1434 goto out;
1435
yanbzhube2774d2015-12-10 15:07:30 -05001436 cb_arg->is_single = 1;
1437 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001438 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001439
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001440 pkey = X509_get_pubkey(x);
1441 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1442 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001443
1444 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001445 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 */
1446
yanbzhube2774d2015-12-10 15:07:30 -05001447 } else {
1448 /*
1449 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1450 * Update that cb_arg with the new cert's staple
1451 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001452 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001453 struct certificate_ocsp *tmp_ocsp;
1454 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001455 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001456 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001457
William Lallemand76b4a122020-08-04 17:41:39 +02001458 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001459
1460 /*
1461 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1462 * the order of operations below matter, take care when changing it
1463 */
1464 tmp_ocsp = cb_arg->s_ocsp;
1465 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1466 cb_arg->s_ocsp = NULL;
1467 cb_arg->m_ocsp[index] = tmp_ocsp;
1468 cb_arg->is_single = 0;
1469 cb_arg->single_kt = 0;
1470
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001471 pkey = X509_get_pubkey(x);
1472 key_type = EVP_PKEY_base_id(pkey);
1473 EVP_PKEY_free(pkey);
1474
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001475 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001476 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001477 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001478 iocsp->refcount++;
1479 }
yanbzhube2774d2015-12-10 15:07:30 -05001480 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001481
1482 ret = 0;
1483
1484 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001485 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001486 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001487 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001488 }
1489
1490out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001491 if (cid)
1492 OCSP_CERTID_free(cid);
1493
1494 if (ocsp)
1495 free(ocsp);
1496
1497 if (warn)
1498 free(warn);
1499
Emeric Brun4147b2e2014-06-16 18:36:30 +02001500 return ret;
1501}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001502#endif
1503
1504#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001505static 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 +02001506{
William Lallemand4a660132019-10-14 14:51:41 +02001507 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 +02001508}
1509#endif
1510
William Lallemand4a660132019-10-14 14:51:41 +02001511
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001512#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001513
1514#define CT_EXTENSION_TYPE 18
1515
William Lallemand03c331c2020-05-13 10:10:01 +02001516int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001517
1518int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1519{
Willy Tarreau83061a82018-07-13 11:56:34 +02001520 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001521
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001522 *out = (unsigned char *) sctl->area;
1523 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001524
1525 return 1;
1526}
1527
1528int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1529{
1530 return 1;
1531}
1532
William Lallemanda17f4112019-10-10 15:16:44 +02001533static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001534{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001535 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001536
William Lallemanda17f4112019-10-10 15:16:44 +02001537 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 +01001538 goto out;
1539
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001540 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1541
1542 ret = 0;
1543
1544out:
1545 return ret;
1546}
1547
1548#endif
1549
Emeric Brune1f38db2012-09-03 20:36:47 +02001550void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1551{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001552 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001553 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001554 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001555 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001556
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001557#ifndef SSL_OP_NO_RENEGOTIATION
1558 /* Please note that BoringSSL defines this macro to zero so don't
1559 * change this to #if and do not assign a default value to this macro!
1560 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001561 if (where & SSL_CB_HANDSHAKE_START) {
1562 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001563 if ((conn->flags & (CO_FL_WAIT_L6_CONN | CO_FL_EARLY_SSL_HS | CO_FL_EARLY_DATA)) == 0) {
Emeric Brune1f38db2012-09-03 20:36:47 +02001564 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001565 conn->err_code = CO_ER_SSL_RENEG;
1566 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001567 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001568#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001569
1570 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001571 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001572 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001573 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001574 consider that the buffering was activated,
1575 so we rise the output buffer size from 4k
1576 to 16k */
1577 write_bio = SSL_get_wbio(ssl);
1578 if (write_bio != SSL_get_rbio(ssl)) {
1579 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001580 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001581 }
1582 }
1583 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001584}
1585
Emeric Brune64aef12012-09-21 13:15:06 +02001586/* Callback is called for each certificate of the chain during a verify
1587 ok is set to 1 if preverify detect no error on current certificate.
1588 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001589int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001590{
1591 SSL *ssl;
1592 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001593 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001594 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001595
1596 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001597 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001598
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001599 ctx = conn->xprt_ctx;
1600
1601 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001602
Emeric Brun81c00f02012-09-21 14:31:21 +02001603 if (ok) /* no errors */
1604 return ok;
1605
1606 depth = X509_STORE_CTX_get_error_depth(x_store);
1607 err = X509_STORE_CTX_get_error(x_store);
1608
1609 /* check if CA error needs to be ignored */
1610 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001611 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1612 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1613 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001614 }
1615
Willy Tarreau731248f2020-02-04 14:02:02 +01001616 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001617 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001618 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001619 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001620 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001621
Willy Tarreau20879a02012-12-03 16:32:10 +01001622 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001623 return 0;
1624 }
1625
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001626 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1627 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001628
Emeric Brun81c00f02012-09-21 14:31:21 +02001629 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001630 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001631 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001632 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001633 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001634 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001635
Willy Tarreau20879a02012-12-03 16:32:10 +01001636 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001637 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001638}
1639
Dragan Dosen9ac98092020-05-11 15:51:45 +02001640#ifdef TLS1_RT_HEARTBEAT
1641static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1642 int content_type, const void *buf, size_t len,
1643 SSL *ssl)
1644{
1645 /* test heartbeat received (write_p is set to 0
1646 for a received record) */
1647 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1648 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1649 const unsigned char *p = buf;
1650 unsigned int payload;
1651
1652 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1653
1654 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1655 if (*p != TLS1_HB_REQUEST)
1656 return;
1657
1658 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1659 goto kill_it;
1660
1661 payload = (p[1] * 256) + p[2];
1662 if (3 + payload + 16 <= len)
1663 return; /* OK no problem */
1664 kill_it:
1665 /* We have a clear heartbleed attack (CVE-2014-0160), the
1666 * advertised payload is larger than the advertised packet
1667 * length, so we have garbage in the buffer between the
1668 * payload and the end of the buffer (p+len). We can't know
1669 * if the SSL stack is patched, and we don't know if we can
1670 * safely wipe out the area between p+3+len and payload.
1671 * So instead, we prevent the response from being sent by
1672 * setting the max_send_fragment to 0 and we report an SSL
1673 * error, which will kill this connection. It will be reported
1674 * above as SSL_ERROR_SSL while an other handshake failure with
1675 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1676 */
1677 ssl->max_send_fragment = 0;
1678 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1679 }
1680}
1681#endif
1682
1683static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1684 int content_type, const void *buf, size_t len,
1685 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001686{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001687 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001688 unsigned char *msg;
1689 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001690 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001691
1692 /* This function is called for "from client" and "to server"
1693 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001694 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001695 */
1696
1697 /* "write_p" is set to 0 is the bytes are received messages,
1698 * otherwise it is set to 1.
1699 */
1700 if (write_p != 0)
1701 return;
1702
1703 /* content_type contains the type of message received or sent
1704 * according with the SSL/TLS protocol spec. This message is
1705 * encoded with one byte. The value 256 (two bytes) is used
1706 * for designing the SSL/TLS record layer. According with the
1707 * rfc6101, the expected message (other than 256) are:
1708 * - change_cipher_spec(20)
1709 * - alert(21)
1710 * - handshake(22)
1711 * - application_data(23)
1712 * - (255)
1713 * We are interessed by the handshake and specially the client
1714 * hello.
1715 */
1716 if (content_type != 22)
1717 return;
1718
1719 /* The message length is at least 4 bytes, containing the
1720 * message type and the message length.
1721 */
1722 if (len < 4)
1723 return;
1724
1725 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001726 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001727 * - hello_request(0)
1728 * - client_hello(1)
1729 * - server_hello(2)
1730 * - certificate(11)
1731 * - server_key_exchange (12)
1732 * - certificate_request(13)
1733 * - server_hello_done(14)
1734 * We are interested by the client hello.
1735 */
1736 msg = (unsigned char *)buf;
1737 if (msg[0] != 1)
1738 return;
1739
1740 /* Next three bytes are the length of the message. The total length
1741 * must be this decoded length + 4. If the length given as argument
1742 * is not the same, we abort the protocol dissector.
1743 */
1744 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1745 if (len < rec_len + 4)
1746 return;
1747 msg += 4;
1748 end = msg + rec_len;
1749 if (end < msg)
1750 return;
1751
1752 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1753 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001754 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1755 */
1756 msg += 1 + 1 + 4 + 28;
1757 if (msg > end)
1758 return;
1759
1760 /* Next, is session id:
1761 * if present, we have to jump by length + 1 for the size information
1762 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001763 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001764 if (msg[0] > 0)
1765 msg += msg[0];
1766 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001767 if (msg > end)
1768 return;
1769
1770 /* Next two bytes are the ciphersuite length. */
1771 if (msg + 2 > end)
1772 return;
1773 rec_len = (msg[0] << 8) + msg[1];
1774 msg += 2;
1775 if (msg + rec_len > end || msg + rec_len < msg)
1776 return;
1777
Willy Tarreaub454e902021-03-22 15:09:41 +01001778 capture = pool_alloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001779 if (!capture)
1780 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001781 /* Compute the xxh64 of the ciphersuite. */
1782 capture->xxh64 = XXH64(msg, rec_len, 0);
1783
1784 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001785 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1786 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001787 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001788
1789 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001790}
William Lallemand7d42ef52020-07-06 11:41:30 +02001791
1792
William Lallemandca5cf0a2021-06-09 16:46:12 +02001793#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001794static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1795 int content_type, const void *buf, size_t len,
1796 SSL *ssl)
1797{
1798 struct ssl_keylog *keylog;
1799
1800 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1801 return;
1802
Willy Tarreauf208ac02021-03-22 21:10:12 +01001803 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001804 if (!keylog)
1805 return;
1806
William Lallemand7d42ef52020-07-06 11:41:30 +02001807 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1808 pool_free(pool_head_ssl_keylog, keylog);
1809 return;
1810 }
1811}
1812#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001813
Emeric Brun29f037d2014-04-25 19:05:36 +02001814/* Callback is called for ssl protocol analyse */
1815void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1816{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001817 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1818 struct ssl_sock_msg_callback *cbk;
1819
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001820 /* Try to call all callback functions that were registered by using
1821 * ssl_sock_register_msg_callback().
1822 */
1823 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1824 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1825 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001826}
1827
Bernard Spil13c53f82018-02-15 13:34:58 +01001828#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001829static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1830 const unsigned char *in, unsigned int inlen,
1831 void *arg)
1832{
1833 struct server *srv = arg;
1834
1835 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1836 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1837 return SSL_TLSEXT_ERR_OK;
1838 return SSL_TLSEXT_ERR_NOACK;
1839}
1840#endif
1841
1842#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001843/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001844 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001845 */
1846static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1847 unsigned int *len, void *arg)
1848{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001849 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001850
1851 *data = (const unsigned char *)conf->npn_str;
1852 *len = conf->npn_len;
1853 return SSL_TLSEXT_ERR_OK;
1854}
1855#endif
1856
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001857#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001858/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001859 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001860 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001861static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1862 unsigned char *outlen,
1863 const unsigned char *server,
1864 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001865{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001866 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001867
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001868 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1869 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1870 return SSL_TLSEXT_ERR_NOACK;
1871 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001872 return SSL_TLSEXT_ERR_OK;
1873}
1874#endif
1875
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001876#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001877#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001878
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001879/* Configure a DNS SAN extenion on a certificate. */
1880int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1881 int failure = 0;
1882 X509_EXTENSION *san_ext = NULL;
1883 CONF *conf = NULL;
1884 struct buffer *san_name = get_trash_chunk();
1885
1886 conf = NCONF_new(NULL);
1887 if (!conf) {
1888 failure = 1;
1889 goto cleanup;
1890 }
1891
1892 /* Build an extension based on the DNS entry above */
1893 chunk_appendf(san_name, "DNS:%s", servername);
1894 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1895 if (!san_ext) {
1896 failure = 1;
1897 goto cleanup;
1898 }
1899
1900 /* Add the extension */
1901 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1902 failure = 1;
1903 goto cleanup;
1904 }
1905
1906 /* Success */
1907 failure = 0;
1908
1909cleanup:
1910 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1911 if (NULL != conf) NCONF_free(conf);
1912
1913 return failure;
1914}
1915
Christopher Faulet30548802015-06-11 13:39:32 +02001916/* Create a X509 certificate with the specified servername and serial. This
1917 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001918static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001919ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001920{
Shimi Gersner5846c492020-08-23 13:58:12 +03001921 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1922 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001923 SSL_CTX *ssl_ctx = NULL;
1924 X509 *newcrt = NULL;
1925 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001926 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001927 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001928 X509_NAME *name;
1929 const EVP_MD *digest;
1930 X509V3_CTX ctx;
1931 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001932 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001933
Christopher Faulet48a83322017-07-28 16:56:09 +02001934 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001935#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001936 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1937#else
1938 tmp_ssl = SSL_new(bind_conf->default_ctx);
1939 if (tmp_ssl)
1940 pkey = SSL_get_privatekey(tmp_ssl);
1941#endif
1942 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001943 goto mkcert_error;
1944
1945 /* Create the certificate */
1946 if (!(newcrt = X509_new()))
1947 goto mkcert_error;
1948
1949 /* Set version number for the certificate (X509v3) and the serial
1950 * number */
1951 if (X509_set_version(newcrt, 2L) != 1)
1952 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001953 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001954
1955 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001956 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1957 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001958 goto mkcert_error;
1959
1960 /* set public key in the certificate */
1961 if (X509_set_pubkey(newcrt, pkey) != 1)
1962 goto mkcert_error;
1963
1964 /* Set issuer name from the CA */
1965 if (!(name = X509_get_subject_name(cacert)))
1966 goto mkcert_error;
1967 if (X509_set_issuer_name(newcrt, name) != 1)
1968 goto mkcert_error;
1969
1970 /* Set the subject name using the same, but the CN */
1971 name = X509_NAME_dup(name);
1972 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1973 (const unsigned char *)servername,
1974 -1, -1, 0) != 1) {
1975 X509_NAME_free(name);
1976 goto mkcert_error;
1977 }
1978 if (X509_set_subject_name(newcrt, name) != 1) {
1979 X509_NAME_free(name);
1980 goto mkcert_error;
1981 }
1982 X509_NAME_free(name);
1983
1984 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001985 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001986 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1987 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1988 X509_EXTENSION *ext;
1989
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001990 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001991 goto mkcert_error;
1992 if (!X509_add_ext(newcrt, ext, -1)) {
1993 X509_EXTENSION_free(ext);
1994 goto mkcert_error;
1995 }
1996 X509_EXTENSION_free(ext);
1997 }
1998
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001999 /* Add SAN extension */
2000 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
2001 goto mkcert_error;
2002 }
2003
Christopher Faulet31af49d2015-06-09 17:29:50 +02002004 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002005
2006 key_type = EVP_PKEY_base_id(capkey);
2007
2008 if (key_type == EVP_PKEY_DSA)
2009 digest = EVP_sha1();
2010 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002011 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002012 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002013 digest = EVP_sha256();
2014 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002015#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002016 int nid;
2017
2018 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2019 goto mkcert_error;
2020 if (!(digest = EVP_get_digestbynid(nid)))
2021 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002022#else
2023 goto mkcert_error;
2024#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002025 }
2026
Christopher Faulet31af49d2015-06-09 17:29:50 +02002027 if (!(X509_sign(newcrt, capkey, digest)))
2028 goto mkcert_error;
2029
2030 /* Create and set the new SSL_CTX */
2031 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2032 goto mkcert_error;
2033 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2034 goto mkcert_error;
2035 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2036 goto mkcert_error;
2037 if (!SSL_CTX_check_private_key(ssl_ctx))
2038 goto mkcert_error;
2039
Shimi Gersner5846c492020-08-23 13:58:12 +03002040 /* Build chaining the CA cert and the rest of the chain, keep these order */
2041#if defined(SSL_CTX_add1_chain_cert)
2042 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2043 goto mkcert_error;
2044 }
2045
2046 if (bind_conf->ca_sign_ckch->chain) {
2047 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2048 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2049 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2050 goto mkcert_error;
2051 }
2052 }
2053 }
2054#endif
2055
Christopher Faulet31af49d2015-06-09 17:29:50 +02002056 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002057
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002058#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002059 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002060#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002061#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2062 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002063 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002064 EC_KEY *ecc;
2065 int nid;
2066
2067 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2068 goto end;
2069 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2070 goto end;
2071 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2072 EC_KEY_free(ecc);
2073 }
2074#endif
2075 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002076 return ssl_ctx;
2077
2078 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002079 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002080 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002081 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2082 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002083 return NULL;
2084}
2085
Christopher Faulet7969a332015-10-09 11:15:03 +02002086SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002087ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02002088{
Willy Tarreau07d94e42018-09-20 10:57:52 +02002089 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01002090 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002091
Olivier Houchard66ab4982019-02-26 18:37:15 +01002092 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02002093}
2094
Christopher Faulet30548802015-06-11 13:39:32 +02002095/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002096 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002097SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002098ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002099{
2100 struct lru64 *lru = NULL;
2101
2102 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002103 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002104 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002105 if (lru && lru->domain) {
2106 if (ssl)
2107 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002108 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002109 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002110 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002111 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002112 }
2113 return NULL;
2114}
2115
Emeric Brun821bb9b2017-06-15 16:37:39 +02002116/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2117 * function is not thread-safe, it should only be used to check if a certificate
2118 * exists in the lru cache (with no warranty it will not be removed by another
2119 * thread). It is kept for backward compatibility. */
2120SSL_CTX *
2121ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2122{
2123 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2124}
2125
Christopher Fauletd2cab922015-07-28 16:03:47 +02002126/* Set a certificate int the LRU cache used to store generated
2127 * certificate. Return 0 on success, otherwise -1 */
2128int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002129ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002130{
2131 struct lru64 *lru = NULL;
2132
2133 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002134 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002135 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002136 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002137 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002138 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002139 }
Christopher Faulet30548802015-06-11 13:39:32 +02002140 if (lru->domain && lru->data)
2141 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002142 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002143 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002144 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002145 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002146 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002147}
2148
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002149/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002150unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002151ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002152{
2153 return XXH32(data, len, ssl_ctx_lru_seed);
2154}
2155
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002156/* Generate a cert and immediately assign it to the SSL session so that the cert's
2157 * refcount is maintained regardless of the cert's presence in the LRU cache.
2158 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002159static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002160ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002161{
Shimi Gersner5846c492020-08-23 13:58:12 +03002162 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002163 SSL_CTX *ssl_ctx = NULL;
2164 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002165 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002166
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002167 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002168 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002169 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002170 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002171 if (lru && lru->domain)
2172 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002173 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002174 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002175 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002176 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002177 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002178 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002179 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002180 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002181 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002182 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002183 SSL_set_SSL_CTX(ssl, ssl_ctx);
2184 /* No LRU cache, this CTX will be released as soon as the session dies */
2185 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002186 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002187 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002188 return 0;
2189}
2190static int
2191ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2192{
2193 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002194 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002195
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002196 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002197 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002198 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002199 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002200 }
2201 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002202}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002203#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002204
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002205#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002206
2207static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002208{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002209#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002210 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002211 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2212#endif
2213}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002214static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2215 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002216 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2217}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002218static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002219#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002220 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002221 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2222#endif
2223}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002224static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002225#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002226 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002227 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2228#endif
2229}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002230/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002231static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2232/* Unusable in this context. */
2233static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2234static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2235static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2236static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2237static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002238#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002239
2240static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2241 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002242 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2243}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002244static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2245 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2246 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2247}
2248static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2249 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002250 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2251}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002252static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2253 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2254 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2255}
2256static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2257 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002258 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2259}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002260static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2261 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2262 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2263}
2264static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2265 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002266 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2267}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002268static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2269 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2270 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2271}
2272static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002273#if SSL_OP_NO_TLSv1_3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002274 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002275 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2276#endif
2277}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002278static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
2279#if SSL_OP_NO_TLSv1_3
2280 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2281 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002282#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002283}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002284#endif
2285static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2286static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002287
William Lallemand7fd8b452020-05-07 15:20:43 +02002288struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002289 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2290 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2291 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2292 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2293 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2294 {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 +02002295};
2296
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002297static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2298{
2299 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2300 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2301 SSL_set_SSL_CTX(ssl, ctx);
2302}
2303
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002304#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002305
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002306int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002307{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002308 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002309 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002310
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002311 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2312 return SSL_TLSEXT_ERR_OK;
2313 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002314}
2315
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002316#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002317int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002318{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002319 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002320#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002321int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002322{
2323#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002324 struct connection *conn;
2325 struct bind_conf *s;
2326 const uint8_t *extension_data;
2327 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002328 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002329
2330 char *wildp = NULL;
2331 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002332 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002333 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002334 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002335 int i;
2336
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002337 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002338 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002339
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002340#ifdef USE_QUIC
2341 if (conn->qc) {
2342 /* Look for the QUIC transport parameters. */
2343#ifdef OPENSSL_IS_BORINGSSL
2344 if (!SSL_early_callback_ctx_extension_get(ctx, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2345 &extension_data, &extension_len))
2346#else
2347 if (!SSL_client_hello_get0_ext(ssl, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2348 &extension_data, &extension_len))
2349#endif
2350 goto abort;
2351
2352 if (!quic_transport_params_store(conn->qc, 0, extension_data,
2353 extension_data + extension_len))
2354 goto abort;
2355 }
2356#endif
2357
Olivier Houchard9679ac92017-10-27 14:58:08 +02002358 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002359 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002360#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002361 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2362 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002363#else
2364 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2365#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002366 /*
2367 * The server_name extension was given too much extensibility when it
2368 * was written, so parsing the normal case is a bit complex.
2369 */
2370 size_t len;
2371 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002372 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002373 /* Extract the length of the supplied list of names. */
2374 len = (*extension_data++) << 8;
2375 len |= *extension_data++;
2376 if (len + 2 != extension_len)
2377 goto abort;
2378 /*
2379 * The list in practice only has a single element, so we only consider
2380 * the first one.
2381 */
2382 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2383 goto abort;
2384 extension_len = len - 1;
2385 /* Now we can finally pull out the byte array with the actual hostname. */
2386 if (extension_len <= 2)
2387 goto abort;
2388 len = (*extension_data++) << 8;
2389 len |= *extension_data++;
2390 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2391 || memchr(extension_data, 0, len) != NULL)
2392 goto abort;
2393 servername = extension_data;
2394 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002395 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002396#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2397 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002398 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002399 }
2400#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002401 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002402 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002403 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002404 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002405 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002406 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002407 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002408 goto abort;
2409 }
2410
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002411 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002412#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002413 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002414#else
2415 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2416#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002417 uint8_t sign;
2418 size_t len;
2419 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002420 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002421 len = (*extension_data++) << 8;
2422 len |= *extension_data++;
2423 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002424 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002425 if (len % 2 != 0)
2426 goto abort;
2427 for (; len > 0; len -= 2) {
2428 extension_data++; /* hash */
2429 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002430 switch (sign) {
2431 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002432 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002433 break;
2434 case TLSEXT_signature_ecdsa:
2435 has_ecdsa_sig = 1;
2436 break;
2437 default:
2438 continue;
2439 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002440 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002441 break;
2442 }
2443 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002444 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002445 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002446 }
2447 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002448 const SSL_CIPHER *cipher;
2449 size_t len;
2450 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002451 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002452#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002453 len = ctx->cipher_suites_len;
2454 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002455#else
2456 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2457#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002458 if (len % 2 != 0)
2459 goto abort;
2460 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002461#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002462 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002463 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002464#else
2465 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2466#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002467 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002468 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002469 break;
2470 }
2471 }
2472 }
2473
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002474 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002475 trash.area[i] = tolower(servername[i]);
2476 if (!wildp && (trash.area[i] == '.'))
2477 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002478 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002479 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002480
William Lallemand150bfa82019-09-19 17:12:49 +02002481 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002482
William Lallemand94bd3192020-08-14 14:43:35 +02002483 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2484 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002485 for (i = 0; i < 2; i++) {
2486 if (i == 0) /* lookup in full qualified names */
2487 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002488 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002489 node = ebst_lookup(&s->sni_w_ctx, wildp);
2490 else
2491 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002492
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002493 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002494
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002495 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002496 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002497 struct sni_ctx *sni, *sni_tmp;
2498 int skip = 0;
2499
2500 if (i == 1 && wildp) { /* wildcard */
2501 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2502 sni = container_of(n, struct sni_ctx, name);
2503 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002504 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002505 skip = 1;
2506 break;
2507 }
2508 }
2509 if (skip)
2510 continue;
2511 }
2512
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002513 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002514 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002515 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002516 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002517 break;
2518 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002519 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002520 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002521 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002522 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002523 if (!node_anonymous)
2524 node_anonymous = n;
2525 break;
2526 }
2527 }
2528 }
William Lallemand94bd3192020-08-14 14:43:35 +02002529 }
2530 /* Once the certificates are found, select them depending on what is
2531 * supported in the client and by key_signature priority order: EDSA >
2532 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002533 if (has_ecdsa_sig && node_ecdsa)
2534 node = node_ecdsa;
2535 else if (has_rsa_sig && node_rsa)
2536 node = node_rsa;
2537 else if (node_anonymous)
2538 node = node_anonymous;
2539 else if (node_ecdsa)
2540 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2541 else
2542 node = node_rsa; /* no rsa signature case (far far away) */
2543
William Lallemand94bd3192020-08-14 14:43:35 +02002544 if (node) {
2545 /* switch ctx */
2546 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2547 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2548 if (conf) {
2549 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2550 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2551 if (conf->early_data)
2552 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002553 }
William Lallemand94bd3192020-08-14 14:43:35 +02002554 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2555 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002556 }
William Lallemand150bfa82019-09-19 17:12:49 +02002557
William Lallemand02010472019-10-18 11:02:19 +02002558 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002559#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002560 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002561 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002562 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002563 }
2564#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002565 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002566 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002567 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002568 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002569 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002570 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02002571allow_early:
2572#ifdef OPENSSL_IS_BORINGSSL
2573 if (allow_early)
2574 SSL_set_early_data_enabled(ssl, 1);
2575#else
2576 if (!allow_early)
2577 SSL_set_max_early_data(ssl, 0);
2578#endif
2579 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002580 abort:
2581 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2582 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002583#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002584 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002585#else
2586 *al = SSL_AD_UNRECOGNIZED_NAME;
2587 return 0;
2588#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002589}
2590
2591#else /* OPENSSL_IS_BORINGSSL */
2592
Emeric Brunfc0421f2012-09-07 17:30:07 +02002593/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2594 * warning when no match is found, which implies the default (first) cert
2595 * will keep being used.
2596 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002597static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002598{
2599 const char *servername;
2600 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002601 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002602 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002603 int i;
2604 (void)al; /* shut gcc stupid warning */
2605
2606 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002607 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002608#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002609 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2610 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002611#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002612 if (s->strict_sni)
2613 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002614 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002615 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002616 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002617 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002618 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002619
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002620 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002621 if (!servername[i])
2622 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002623 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002624 if (!wildp && (trash.area[i] == '.'))
2625 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002626 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002627 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002628
William Lallemand150bfa82019-09-19 17:12:49 +02002629 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002630 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002631 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002632 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2633 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002634 if (!container_of(n, struct sni_ctx, name)->neg) {
2635 node = n;
2636 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002637 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002638 }
2639 if (!node && wildp) {
2640 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002641 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2642 /* lookup a not neg filter */
2643 if (!container_of(n, struct sni_ctx, name)->neg) {
2644 node = n;
2645 break;
2646 }
2647 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002648 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002649 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002650#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002651 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2652 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002653 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002654 return SSL_TLSEXT_ERR_OK;
2655 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002656#endif
William Lallemand21724f02019-11-04 17:56:13 +01002657 if (s->strict_sni) {
2658 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002659 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002660 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002661 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002662 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002663 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002664 }
2665
2666 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002667 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002668 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002669 return SSL_TLSEXT_ERR_OK;
2670}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002671#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002672#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2673
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002674#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002675
2676static DH * ssl_get_dh_1024(void)
2677{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002678 static unsigned char dh1024_p[]={
2679 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2680 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2681 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2682 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2683 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2684 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2685 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2686 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2687 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2688 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2689 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2690 };
2691 static unsigned char dh1024_g[]={
2692 0x02,
2693 };
2694
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002695 BIGNUM *p;
2696 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002697 DH *dh = DH_new();
2698 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002699 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2700 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002701
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002702 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002703 DH_free(dh);
2704 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002705 } else {
2706 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002707 }
2708 }
2709 return dh;
2710}
2711
2712static DH *ssl_get_dh_2048(void)
2713{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002714 static unsigned char dh2048_p[]={
2715 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2716 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2717 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2718 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2719 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2720 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2721 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2722 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2723 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2724 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2725 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2726 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2727 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2728 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2729 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2730 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2731 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2732 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2733 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2734 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2735 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2736 0xB7,0x1F,0x77,0xF3,
2737 };
2738 static unsigned char dh2048_g[]={
2739 0x02,
2740 };
2741
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002742 BIGNUM *p;
2743 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002744 DH *dh = DH_new();
2745 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002746 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2747 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002748
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002749 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002750 DH_free(dh);
2751 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002752 } else {
2753 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002754 }
2755 }
2756 return dh;
2757}
2758
2759static DH *ssl_get_dh_4096(void)
2760{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002761 static unsigned char dh4096_p[]={
2762 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2763 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2764 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2765 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2766 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2767 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2768 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2769 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2770 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2771 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2772 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2773 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2774 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2775 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2776 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2777 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2778 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2779 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2780 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2781 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2782 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2783 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2784 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2785 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2786 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2787 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2788 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2789 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2790 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2791 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2792 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2793 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2794 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2795 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2796 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2797 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2798 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2799 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2800 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2801 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2802 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2803 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2804 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002805 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002806 static unsigned char dh4096_g[]={
2807 0x02,
2808 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002809
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002810 BIGNUM *p;
2811 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002812 DH *dh = DH_new();
2813 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002814 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2815 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002816
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002817 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002818 DH_free(dh);
2819 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002820 } else {
2821 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002822 }
2823 }
2824 return dh;
2825}
2826
2827/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002828 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002829static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2830{
2831 DH *dh = NULL;
2832 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002833 int type;
2834
2835 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002836
2837 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2838 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2839 */
2840 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2841 keylen = EVP_PKEY_bits(pkey);
2842 }
2843
Willy Tarreauef934602016-12-22 23:12:01 +01002844 if (keylen > global_ssl.default_dh_param) {
2845 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002846 }
2847
Remi Gacogned3a341a2015-05-29 16:26:17 +02002848 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002849 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002850 }
2851 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002852 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002853 }
2854 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002855 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002856 }
2857
2858 return dh;
2859}
2860
Remi Gacogne47783ef2015-05-29 15:53:22 +02002861static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002862{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002863 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002864 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002865
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002866 if (in == NULL)
2867 goto end;
2868
Remi Gacogne47783ef2015-05-29 15:53:22 +02002869 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002870 goto end;
2871
Remi Gacogne47783ef2015-05-29 15:53:22 +02002872 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2873
2874end:
2875 if (in)
2876 BIO_free(in);
2877
Emeric Brune1b4ed42018-08-16 15:14:12 +02002878 ERR_clear_error();
2879
Remi Gacogne47783ef2015-05-29 15:53:22 +02002880 return dh;
2881}
2882
2883int ssl_sock_load_global_dh_param_from_file(const char *filename)
2884{
2885 global_dh = ssl_sock_get_dh_from_file(filename);
2886
2887 if (global_dh) {
2888 return 0;
2889 }
2890
2891 return -1;
2892}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002893#endif
2894
William Lallemand9117de92019-10-04 00:29:42 +02002895/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002896static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002897 struct bind_conf *s, struct ssl_bind_conf *conf,
2898 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002899{
2900 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002901 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002902
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002903 if (*name == '!') {
2904 neg = 1;
2905 name++;
2906 }
2907 if (*name == '*') {
2908 wild = 1;
2909 name++;
2910 }
2911 /* !* filter is a nop */
2912 if (neg && wild)
2913 return order;
2914 if (*name) {
2915 int j, len;
2916 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002917 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02002918 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002919 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002920 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002921 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002922
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002923 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002924 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002925 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002926 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002927 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002928 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002929 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002930 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002931 sc->order = order++;
2932 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002933 sc->wild = wild;
2934 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002935 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02002936 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002937 }
2938 return order;
2939}
2940
William Lallemand6af03992019-07-23 15:00:54 +02002941/*
William Lallemand1d29c742019-10-04 00:53:29 +02002942 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2943 * This function can't return an error.
2944 *
2945 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2946 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002947void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002948{
2949
2950 struct sni_ctx *sc0, *sc0b, *sc1;
2951 struct ebmb_node *node;
2952
2953 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2954
2955 /* ignore if sc0 was already inserted in a tree */
2956 if (sc0->name.node.leaf_p)
2957 continue;
2958
2959 /* Check for duplicates. */
2960 if (sc0->wild)
2961 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2962 else
2963 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2964
2965 for (; node; node = ebmb_next_dup(node)) {
2966 sc1 = ebmb_entry(node, struct sni_ctx, name);
2967 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2968 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2969 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02002970 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002971 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002972 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02002973 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002974 }
2975 }
2976
2977 /* if duplicate, ignore the insertion */
2978 if (!sc0)
2979 continue;
2980
2981 if (sc0->wild)
2982 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
2983 else
2984 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01002985 }
William Lallemand21724f02019-11-04 17:56:13 +01002986
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01002987 /* replace the default_ctx if required with the instance's ctx. */
2988 if (ckch_inst->is_default) {
2989 SSL_CTX_free(bind_conf->default_ctx);
2990 SSL_CTX_up_ref(ckch_inst->ctx);
2991 bind_conf->default_ctx = ckch_inst->ctx;
William Lallemand1d29c742019-10-04 00:53:29 +02002992 }
2993}
2994
2995/*
William Lallemande3af8fb2019-10-08 11:36:53 +02002996 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02002997 */
William Lallemande3af8fb2019-10-08 11:36:53 +02002998struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02002999
William Lallemand2954c472020-03-06 21:54:13 +01003000/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003001struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003002
Emeric Brun7a883362019-10-17 13:27:40 +02003003/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003004 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003005 * DH parameter is loaded into the SSL_CTX and if there is no
3006 * DH parameter available in ckchs nor in global, the default
3007 * DH parameters are applied on the SSL_CTX.
3008 * Returns a bitfield containing the flags:
3009 * ERR_FATAL in any fatal error case
3010 * ERR_ALERT if a reason of the error is availabine in err
3011 * ERR_WARN if a warning is available into err
3012 * The value 0 means there is no error nor warning and
3013 * the operation succeed.
3014 */
William Lallemandfa892222019-07-23 16:06:08 +02003015#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02003016static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
3017 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003018{
Emeric Brun7a883362019-10-17 13:27:40 +02003019 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02003020 DH *dh = NULL;
3021
William Lallemanda8c73742019-07-31 18:31:34 +02003022 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02003023 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02003024 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
3025 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3026 err && *err ? *err : "", path);
3027#if defined(SSL_CTX_set_dh_auto)
3028 SSL_CTX_set_dh_auto(ctx, 1);
3029 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3030 err && *err ? *err : "");
3031#else
3032 memprintf(err, "%s, DH ciphers won't be available.\n",
3033 err && *err ? *err : "");
3034#endif
3035 ret |= ERR_WARN;
3036 goto end;
3037 }
William Lallemandfa892222019-07-23 16:06:08 +02003038
3039 if (ssl_dh_ptr_index >= 0) {
3040 /* store a pointer to the DH params to avoid complaining about
3041 ssl-default-dh-param not being set for this SSL_CTX */
3042 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3043 }
3044 }
3045 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003046 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
3047 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3048 err && *err ? *err : "", path);
3049#if defined(SSL_CTX_set_dh_auto)
3050 SSL_CTX_set_dh_auto(ctx, 1);
3051 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3052 err && *err ? *err : "");
3053#else
3054 memprintf(err, "%s, DH ciphers won't be available.\n",
3055 err && *err ? *err : "");
3056#endif
3057 ret |= ERR_WARN;
3058 goto end;
3059 }
William Lallemandfa892222019-07-23 16:06:08 +02003060 }
3061 else {
3062 /* Clear openssl global errors stack */
3063 ERR_clear_error();
3064
Willy Tarreau6d27a922020-11-05 19:38:05 +01003065 if (global_ssl.default_dh_param && global_ssl.default_dh_param <= 1024) {
William Lallemandfa892222019-07-23 16:06:08 +02003066 /* we are limited to DH parameter of 1024 bits anyway */
3067 if (local_dh_1024 == NULL)
3068 local_dh_1024 = ssl_get_dh_1024();
3069
Emeric Brun7a883362019-10-17 13:27:40 +02003070 if (local_dh_1024 == NULL) {
3071 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3072 err && *err ? *err : "", path);
3073 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02003074 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02003075 }
William Lallemandfa892222019-07-23 16:06:08 +02003076
Emeric Bruna9363eb2019-10-17 14:53:03 +02003077 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
3078 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3079 err && *err ? *err : "", path);
3080#if defined(SSL_CTX_set_dh_auto)
3081 SSL_CTX_set_dh_auto(ctx, 1);
3082 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3083 err && *err ? *err : "");
3084#else
3085 memprintf(err, "%s, DH ciphers won't be available.\n",
3086 err && *err ? *err : "");
3087#endif
3088 ret |= ERR_WARN;
3089 goto end;
3090 }
William Lallemandfa892222019-07-23 16:06:08 +02003091 }
3092 else {
3093 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
3094 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003095 }
3096
William Lallemandf9568fc2019-10-16 18:27:58 +02003097end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003098 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003099 return ret;
3100}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003101#endif
William Lallemandfa892222019-07-23 16:06:08 +02003102
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003103
3104/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003105 * Returns a bitfield containing the flags:
3106 * ERR_FATAL in any fatal error case
3107 * ERR_ALERT if the reason of the error is available in err
3108 * ERR_WARN if a warning is available into err
3109 * The value 0 means there is no error nor warning and
3110 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003111 */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003112static int ssl_sock_load_cert_chain(const char *path, const struct cert_key_and_chain *ckch,
3113 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003114{
Emeric Bruna96b5822019-10-17 13:25:14 +02003115 int errcode = 0;
3116
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003117 if (find_chain == NULL) {
3118 errcode |= ERR_FATAL;
3119 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003120 }
3121
3122 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3123 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3124 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003125 errcode |= ERR_ALERT | ERR_FATAL;
3126 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003127 }
3128
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003129 if (ckch->chain) {
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003130 *find_chain = ckch->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003131 } else {
3132 /* Find Certificate Chain in global */
3133 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003134 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003135 if (issuer)
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003136 *find_chain = issuer->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003137 }
William Lallemand85888572020-02-27 14:48:35 +01003138
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003139 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003140 /* always put a null chain stack in the SSL_CTX so it does not
3141 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003142 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003143 }
3144
William Lallemandf187ce62020-06-02 18:27:20 +02003145 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003146#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003147 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand935d8292020-08-12 20:02:10 +02003148 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3149 err && *err ? *err : "", path);
3150 errcode |= ERR_ALERT | ERR_FATAL;
3151 goto end;
3152 }
William Lallemandf187ce62020-06-02 18:27:20 +02003153#else
3154 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003155 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02003156 STACK_OF(X509) *chain;
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003157 chain = X509_chain_up_ref(*find_chain);
William Lallemandf187ce62020-06-02 18:27:20 +02003158 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003159 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003160 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3161 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003162 X509_free(ca);
3163 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003164 errcode |= ERR_ALERT | ERR_FATAL;
3165 goto end;
3166 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003167 }
William Lallemandf187ce62020-06-02 18:27:20 +02003168#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003169
William Lallemand9a1d8392020-08-10 17:28:23 +02003170#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003171 /* remove the Root CA from the SSL_CTX if the option is activated */
3172 if (global_ssl.skip_self_issued_ca) {
3173 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3174 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3175 err && *err ? *err : "", path);
3176 errcode |= ERR_ALERT | ERR_FATAL;
3177 goto end;
3178 }
3179 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003180#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003181
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003182end:
3183 return errcode;
3184}
3185
3186
3187/* Loads the info in ckch into ctx
3188 * Returns a bitfield containing the flags:
3189 * ERR_FATAL in any fatal error case
3190 * ERR_ALERT if the reason of the error is available in err
3191 * ERR_WARN if a warning is available into err
3192 * The value 0 means there is no error nor warning and
3193 * the operation succeed.
3194 */
3195static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3196{
3197 int errcode = 0;
3198 STACK_OF(X509) *find_chain = NULL;
3199
3200 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3201 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3202 err && *err ? *err : "", path);
3203 errcode |= ERR_ALERT | ERR_FATAL;
3204 return errcode;
3205 }
3206
3207 /* Load certificate chain */
3208 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3209 if (errcode & ERR_CODE)
3210 goto end;
3211
William Lallemandfa892222019-07-23 16:06:08 +02003212#ifndef OPENSSL_NO_DH
3213 /* store a NULL pointer to indicate we have not yet loaded
3214 a custom DH param file */
3215 if (ssl_dh_ptr_index >= 0) {
3216 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3217 }
3218
Emeric Brun7a883362019-10-17 13:27:40 +02003219 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3220 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003221 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3222 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003223 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003224 }
3225#endif
3226
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003227#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003228 if (sctl_ex_index >= 0 && ckch->sctl) {
3229 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3230 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003231 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003232 errcode |= ERR_ALERT | ERR_FATAL;
3233 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003234 }
3235 }
3236#endif
3237
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003238#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003239 /* Load OCSP Info into context */
3240 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003241 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003242 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",
3243 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003244 errcode |= ERR_ALERT | ERR_FATAL;
3245 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003246 }
3247 }
William Lallemand246c0242019-10-11 08:59:13 +02003248#endif
3249
Emeric Bruna96b5822019-10-17 13:25:14 +02003250 end:
3251 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003252}
3253
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003254
3255/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3256 * Returns a bitfield containing the flags:
3257 * ERR_FATAL in any fatal error case
3258 * ERR_ALERT if the reason of the error is available in err
3259 * ERR_WARN if a warning is available into err
3260 * The value 0 means there is no error nor warning and
3261 * the operation succeed.
3262 */
3263static int ssl_sock_put_srv_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch,
3264 SSL_CTX *ctx, char **err)
3265{
3266 int errcode = 0;
3267 STACK_OF(X509) *find_chain = NULL;
3268
3269 /* Load the private key */
3270 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3271 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3272 err && *err ? *err : "", path);
3273 errcode |= ERR_ALERT | ERR_FATAL;
3274 }
3275
3276 /* Load certificate chain */
3277 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3278 if (errcode & ERR_CODE)
3279 goto end;
3280
3281 if (SSL_CTX_check_private_key(ctx) <= 0) {
3282 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3283 err && *err ? *err : "", path);
3284 errcode |= ERR_ALERT | ERR_FATAL;
3285 }
3286
3287end:
3288 return errcode;
3289}
3290
3291
William Lallemand614ca0d2019-10-07 13:52:11 +02003292/*
3293 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003294 *
3295 * Returns a bitfield containing the flags:
3296 * ERR_FATAL in any fatal error case
3297 * ERR_ALERT if the reason of the error is available in err
3298 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003299 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003300int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003301 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003302{
William Lallemandc9402072019-05-15 15:33:54 +02003303 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003304 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003305 int order = 0;
3306 X509_NAME *xname;
3307 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003308 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003309 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003310#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3311 STACK_OF(GENERAL_NAME) *names;
3312#endif
William Lallemand36b84632019-07-18 19:28:17 +02003313 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003314 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003315 int errcode = 0;
3316
3317 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003318
William Lallemande3af8fb2019-10-08 11:36:53 +02003319 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003320 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003321
William Lallemande3af8fb2019-10-08 11:36:53 +02003322 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003323
William Lallemandc9402072019-05-15 15:33:54 +02003324 ctx = SSL_CTX_new(SSLv23_server_method());
3325 if (!ctx) {
3326 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3327 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003328 errcode |= ERR_ALERT | ERR_FATAL;
3329 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003330 }
3331
Emeric Bruna96b5822019-10-17 13:25:14 +02003332 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3333 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003334 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003335
3336 ckch_inst = ckch_inst_new();
3337 if (!ckch_inst) {
3338 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3339 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003340 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003341 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003342 }
3343
William Lallemand36b84632019-07-18 19:28:17 +02003344 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003345 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003346 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003347 switch(EVP_PKEY_base_id(pkey)) {
3348 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003349 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003350 break;
3351 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003352 kinfo.sig = TLSEXT_signature_ecdsa;
3353 break;
3354 case EVP_PKEY_DSA:
3355 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003356 break;
3357 }
3358 EVP_PKEY_free(pkey);
3359 }
3360
Emeric Brun50bcecc2013-04-22 13:05:23 +02003361 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003362 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003363 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 +02003364 if (order < 0) {
3365 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003366 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003367 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003368 }
3369 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003370 }
3371 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003372#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003373 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003374 if (names) {
3375 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3376 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3377 if (name->type == GEN_DNS) {
3378 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003379 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003380 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003381 if (order < 0) {
3382 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003383 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003384 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003385 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003386 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003387 }
3388 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003389 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003390 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003391#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003392 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003393 i = -1;
3394 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3395 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003396 ASN1_STRING *value;
3397
3398 value = X509_NAME_ENTRY_get_data(entry);
3399 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003400 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003401 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003402 if (order < 0) {
3403 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003404 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003405 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003406 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003407 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003408 }
3409 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003410 /* we must not free the SSL_CTX anymore below, since it's already in
3411 * the tree, so it will be discovered and cleaned in time.
3412 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003413
Emeric Brunfc0421f2012-09-07 17:30:07 +02003414#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003415 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003416 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3417 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003418 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003419 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003420 }
3421#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003422 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003423 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003424 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003425 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003426 SSL_CTX_up_ref(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003427 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003428
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003429 /* Always keep a reference to the newly constructed SSL_CTX in the
3430 * instance. This way if the instance has no SNIs, the SSL_CTX will
3431 * still be linked. */
3432 SSL_CTX_up_ref(ctx);
3433 ckch_inst->ctx = ctx;
3434
William Lallemand9117de92019-10-04 00:29:42 +02003435 /* everything succeed, the ckch instance can be used */
3436 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003437 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003438 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003439
William Lallemand02e19a52020-04-08 16:11:26 +02003440 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3441
Emeric Brun054563d2019-10-17 13:16:58 +02003442 *ckchi = ckch_inst;
3443 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003444
3445error:
3446 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003447 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003448 if (ckch_inst->is_default)
3449 SSL_CTX_free(ctx);
3450
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003451 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003452 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003453 }
William Lallemandd9199372019-10-04 15:37:05 +02003454 SSL_CTX_free(ctx);
3455
Emeric Brun054563d2019-10-17 13:16:58 +02003456 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003457}
3458
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003459
3460/*
3461 * This function allocate a ckch_inst that will be used on the backend side
3462 * (server line)
3463 *
3464 * Returns a bitfield containing the flags:
3465 * ERR_FATAL in any fatal error case
3466 * ERR_ALERT if the reason of the error is available in err
3467 * ERR_WARN if a warning is available into err
3468 */
3469int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003470 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003471{
3472 SSL_CTX *ctx;
3473 struct cert_key_and_chain *ckch;
3474 struct ckch_inst *ckch_inst = NULL;
3475 int errcode = 0;
3476
3477 *ckchi = NULL;
3478
3479 if (!ckchs || !ckchs->ckch)
3480 return ERR_FATAL;
3481
3482 ckch = ckchs->ckch;
3483
3484 ctx = SSL_CTX_new(SSLv23_client_method());
3485 if (!ctx) {
3486 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3487 err && *err ? *err : "", path);
3488 errcode |= ERR_ALERT | ERR_FATAL;
3489 goto error;
3490 }
3491
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003492 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, ckch, ctx, err);
3493 if (errcode & ERR_CODE)
3494 goto error;
3495
3496 ckch_inst = ckch_inst_new();
3497 if (!ckch_inst) {
3498 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3499 err && *err ? *err : "", path);
3500 errcode |= ERR_ALERT | ERR_FATAL;
3501 goto error;
3502 }
3503
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003504 /* everything succeed, the ckch instance can be used */
3505 ckch_inst->bind_conf = NULL;
3506 ckch_inst->ssl_conf = NULL;
3507 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003508 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003509 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003510
3511 *ckchi = ckch_inst;
3512 return errcode;
3513
3514error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003515 SSL_CTX_free(ctx);
3516
3517 return errcode;
3518}
3519
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003520/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003521static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3522 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003523 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003524{
Emeric Brun054563d2019-10-17 13:16:58 +02003525 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003526
3527 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003528 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 +02003529
Emeric Brun054563d2019-10-17 13:16:58 +02003530 if (errcode & ERR_CODE)
3531 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003532
William Lallemand24bde432020-03-09 16:48:43 +01003533 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003534
3535 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003536 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003537 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003538}
3539
William Lallemanddb26e2b2021-01-26 12:01:46 +01003540/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3541 * fill the SSL_CTX of the server.
3542 *
3543 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003544static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003545 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003546{
3547 int errcode = 0;
3548
3549 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003550 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003551
3552 if (errcode & ERR_CODE)
3553 return errcode;
3554
William Lallemanddb26e2b2021-01-26 12:01:46 +01003555 (*ckch_inst)->server = server;
3556 /* Keep the reference to the SSL_CTX in the server. */
3557 SSL_CTX_up_ref((*ckch_inst)->ctx);
3558 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003559 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003560 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003561 return errcode;
3562}
3563
William Lallemand6be66ec2020-03-06 22:26:32 +01003564
William Lallemand4c68bba2020-03-30 18:45:10 +02003565
3566
3567/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3568 * done once. Zero is returned if the operation fails. No error is returned
3569 * if the random is said as not implemented, because we expect that openssl
3570 * will use another method once needed.
3571 */
3572static int ssl_initialize_random()
3573{
3574 unsigned char random;
3575 static int random_initialized = 0;
3576
3577 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3578 random_initialized = 1;
3579
3580 return random_initialized;
3581}
3582
William Lallemand2954c472020-03-06 21:54:13 +01003583/* Load a crt-list file, this is done in 2 parts:
3584 * - store the content of the file in a crtlist structure with crtlist_entry structures
3585 * - generate the instances by iterating on entries in the crtlist struct
3586 *
3587 * Nothing is locked there, this function is used in the configuration parser.
3588 *
3589 * Returns a set of ERR_* flags possibly with an error in <err>.
3590 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003591int 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 +01003592{
3593 struct crtlist *crtlist = NULL;
3594 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003595 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003596 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003597 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003598 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003599
William Lallemand79d31ec2020-03-25 15:10:49 +01003600 bind_conf_node = malloc(sizeof(*bind_conf_node));
3601 if (!bind_conf_node) {
3602 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3603 cfgerr |= ERR_FATAL | ERR_ALERT;
3604 goto error;
3605 }
3606 bind_conf_node->next = NULL;
3607 bind_conf_node->bind_conf = bind_conf;
3608
William Lallemand41ca9302020-04-08 13:15:18 +02003609 /* strip trailing slashes, including first one */
3610 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3611 *end = 0;
3612
William Lallemand2954c472020-03-06 21:54:13 +01003613 /* look for an existing crtlist or create one */
3614 eb = ebst_lookup(&crtlists_tree, file);
3615 if (eb) {
3616 crtlist = ebmb_entry(eb, struct crtlist, node);
3617 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003618 /* load a crt-list OR a directory */
3619 if (dir)
3620 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3621 else
3622 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3623
William Lallemand2954c472020-03-06 21:54:13 +01003624 if (!(cfgerr & ERR_CODE))
3625 ebst_insert(&crtlists_tree, &crtlist->node);
3626 }
3627
3628 if (cfgerr & ERR_CODE) {
3629 cfgerr |= ERR_FATAL | ERR_ALERT;
3630 goto error;
3631 }
3632
3633 /* generates ckch instance from the crtlist_entry */
3634 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3635 struct ckch_store *store;
3636 struct ckch_inst *ckch_inst = NULL;
3637
3638 store = entry->node.key;
3639 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3640 if (cfgerr & ERR_CODE) {
3641 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3642 goto error;
3643 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003644 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003645 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003646 }
William Lallemand2954c472020-03-06 21:54:13 +01003647
William Lallemand79d31ec2020-03-25 15:10:49 +01003648 /* add the bind_conf to the list */
3649 bind_conf_node->next = crtlist->bind_conf;
3650 crtlist->bind_conf = bind_conf_node;
3651
William Lallemand2954c472020-03-06 21:54:13 +01003652 return cfgerr;
3653error:
3654 {
William Lallemand49398312020-03-30 17:01:33 +02003655 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003656 struct ckch_inst *inst, *s_inst;
3657
William Lallemand49398312020-03-30 17:01:33 +02003658 lastentry = entry; /* which entry we tried to generate last */
3659 if (lastentry) {
3660 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3661 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3662 break;
3663
3664 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003665
William Lallemand49398312020-03-30 17:01:33 +02003666 /* this was not generated for this bind_conf, skip */
3667 if (inst->bind_conf != bind_conf)
3668 continue;
3669
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003670 /* free the sni_ctx and instance */
3671 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003672 }
William Lallemand2954c472020-03-06 21:54:13 +01003673 }
William Lallemand2954c472020-03-06 21:54:13 +01003674 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003675 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003676 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003677 return cfgerr;
3678}
3679
William Lallemand06b22a82020-03-16 14:45:55 +01003680/* Returns a set of ERR_* flags possibly with an error in <err>. */
3681int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3682{
3683 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003684 int cfgerr = 0;
3685 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003686 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003687 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003688
3689 if ((ckchs = ckchs_lookup(path))) {
3690 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003691 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3692 found++;
3693 } else if (stat(path, &buf) == 0) {
3694 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003695 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003696 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003697 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003698 cfgerr |= ERR_ALERT | ERR_FATAL;
3699 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003700 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003701 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003702 }
3703 } else {
3704 /* stat failed, could be a bundle */
3705 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003706 char fp[MAXPATHLEN+1] = {0};
3707 int n = 0;
3708
3709 /* Load all possible certs and keys in separate ckch_store */
3710 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3711 struct stat buf;
3712 int ret;
3713
3714 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3715 if (ret > sizeof(fp))
3716 continue;
3717
3718 if ((ckchs = ckchs_lookup(fp))) {
3719 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003720 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003721 } else {
3722 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003723 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003724 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003725 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003726 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003727 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3728 }
3729 }
3730 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003731#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3732 if (found) {
3733 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3734 err && *err ? *err : "", path);
3735 cfgerr |= ERR_ALERT | ERR_FATAL;
3736 }
3737#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003738 }
3739 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003740 if (!found) {
3741 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3742 err && *err ? *err : "", path, strerror(errno));
3743 cfgerr |= ERR_ALERT | ERR_FATAL;
3744 }
William Lallemand06b22a82020-03-16 14:45:55 +01003745
3746 return cfgerr;
3747}
3748
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003749
3750/* Create a full ssl context and ckch instance that will be used for a specific
3751 * backend server (server configuration line).
3752 * Returns a set of ERR_* flags possibly with an error in <err>.
3753 */
3754int ssl_sock_load_srv_cert(char *path, struct server *server, char **err)
3755{
3756 struct stat buf;
3757 int cfgerr = 0;
3758 struct ckch_store *ckchs;
3759 int found = 0; /* did we found a file to load ? */
3760
3761 if ((ckchs = ckchs_lookup(path))) {
3762 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01003763 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003764 found++;
3765 } else if (stat(path, &buf) == 0) {
3766 /* We do not manage directories on backend side. */
3767 if (S_ISDIR(buf.st_mode) == 0) {
3768 ++found;
3769 ckchs = ckchs_load_cert_file(path, err);
3770 if (!ckchs)
3771 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003772 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003773 }
3774 }
3775 if (!found) {
3776 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3777 err && *err ? *err : "", path, strerror(errno));
3778 cfgerr |= ERR_ALERT | ERR_FATAL;
3779 }
3780
3781 return cfgerr;
3782}
3783
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003784/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003785static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003786ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003787{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003788 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003789 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003790 SSL_OP_ALL | /* all known workarounds for bugs */
3791 SSL_OP_NO_SSLv2 |
3792 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003793 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003794 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003795 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003796 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003797 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003798 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003799 SSL_MODE_ENABLE_PARTIAL_WRITE |
3800 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003801 SSL_MODE_RELEASE_BUFFERS |
3802 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003803 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003804 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003805 int flags = MC_SSL_O_ALL;
3806 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003807 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003808
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003809 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003810 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003811
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003812 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003813 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3814 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3815 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003816 else
3817 flags = conf_ssl_methods->flags;
3818
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003819 min = conf_ssl_methods->min;
3820 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003821
3822 /* default minimum is TLSV12, */
3823 if (!min) {
3824 if (!max || (max >= default_min_ver)) {
3825 min = default_min_ver;
3826 } else {
3827 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). "
3828 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3829 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3830 min = max;
3831 }
3832 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003833 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003834 if (min)
3835 flags |= (methodVersions[min].flag - 1);
3836 if (max)
3837 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003838 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003839 min = max = CONF_TLSV_NONE;
3840 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003841 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003842 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003843 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003844 if (min) {
3845 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003846 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3847 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3848 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3849 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003850 hole = 0;
3851 }
3852 max = i;
3853 }
3854 else {
3855 min = max = i;
3856 }
3857 }
3858 else {
3859 if (min)
3860 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003861 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003862 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003863 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3864 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003865 cfgerr += 1;
3866 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003867 /* save real min/max in bind_conf */
3868 conf_ssl_methods->min = min;
3869 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003870
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003871#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003872 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003873 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003874 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003875 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003876 else
William Lallemandd0712f32020-06-11 17:34:00 +02003877 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
3878 /* clear every version flags in case SSL_CTX_new()
3879 * returns an SSL_CTX with disabled versions */
3880 SSL_CTX_clear_options(ctx, methodVersions[i].option);
3881
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003882 if (flags & methodVersions[i].flag)
3883 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02003884
3885 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003886#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003887 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003888 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3889 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003890#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003891
3892 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3893 options |= SSL_OP_NO_TICKET;
3894 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3895 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003896
3897#ifdef SSL_OP_NO_RENEGOTIATION
3898 options |= SSL_OP_NO_RENEGOTIATION;
3899#endif
3900
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003901 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003902
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05003903#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003904 if (global_ssl.async)
3905 mode |= SSL_MODE_ASYNC;
3906#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003907 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003908 if (global_ssl.life_time)
3909 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003910
3911#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3912#ifdef OPENSSL_IS_BORINGSSL
3913 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3914 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003915#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003916 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003917 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003918 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3919 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003920#else
3921 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003922#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003923 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003924#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003925 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003926}
3927
William Lallemand4f45bb92017-10-30 20:08:51 +01003928
3929static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3930{
3931 if (first == block) {
3932 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3933 if (first->len > 0)
3934 sh_ssl_sess_tree_delete(sh_ssl_sess);
3935 }
3936}
3937
3938/* return first block from sh_ssl_sess */
3939static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3940{
3941 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3942
3943}
3944
3945/* store a session into the cache
3946 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3947 * data: asn1 encoded session
3948 * data_len: asn1 encoded session length
3949 * Returns 1 id session was stored (else 0)
3950 */
3951static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3952{
3953 struct shared_block *first;
3954 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3955
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003956 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003957 if (!first) {
3958 /* Could not retrieve enough free blocks to store that session */
3959 return 0;
3960 }
3961
3962 /* STORE the key in the first elem */
3963 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3964 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3965 first->len = sizeof(struct sh_ssl_sess_hdr);
3966
3967 /* it returns the already existing node
3968 or current node if none, never returns null */
3969 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3970 if (oldsh_ssl_sess != sh_ssl_sess) {
3971 /* NOTE: Row couldn't be in use because we lock read & write function */
3972 /* release the reserved row */
3973 shctx_row_dec_hot(ssl_shctx, first);
3974 /* replace the previous session already in the tree */
3975 sh_ssl_sess = oldsh_ssl_sess;
3976 /* ignore the previous session data, only use the header */
3977 first = sh_ssl_sess_first_block(sh_ssl_sess);
3978 shctx_row_inc_hot(ssl_shctx, first);
3979 first->len = sizeof(struct sh_ssl_sess_hdr);
3980 }
3981
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003982 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01003983 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003984 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01003985 }
3986
3987 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003988
3989 return 1;
3990}
William Lallemanded0b5ad2017-10-30 19:36:36 +01003991
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003992/* SSL callback used when a new session is created while connecting to a server */
3993static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
3994{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02003995 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003996 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003997
Willy Tarreau07d94e42018-09-20 10:57:52 +02003998 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003999
William Lallemand3ce6eed2021-02-08 10:43:44 +01004000 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4001 * one cache per thread, it only prevents to flush it from the CLI in
4002 * another thread */
4003
Olivier Houcharde6060c52017-11-16 17:42:52 +01004004 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4005 int len;
4006 unsigned char *ptr;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004007
Olivier Houcharde6060c52017-11-16 17:42:52 +01004008 len = i2d_SSL_SESSION(sess, NULL);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004009 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004010 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4011 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4012 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004013 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4014 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004015 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4016 }
4017 if (s->ssl_ctx.reused_sess[tid].ptr) {
4018 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4019 &ptr);
4020 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004021 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004022 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004023 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004024 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004025 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004026 }
4027
4028 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004029}
4030
Olivier Houcharde6060c52017-11-16 17:42:52 +01004031
William Lallemanded0b5ad2017-10-30 19:36:36 +01004032/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004033int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004034{
4035 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4036 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4037 unsigned char *p;
4038 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004039 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004040 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004041
4042 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004043 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004044 * note: SSL_SESSION_set1_id is using
4045 * a memcpy so we need to use a different pointer
4046 * than sid_data or sid_ctx_data to avoid valgrind
4047 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004048 */
4049
4050 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004051
4052 /* copy value in an other buffer */
4053 memcpy(encid, sid_data, sid_length);
4054
4055 /* pad with 0 */
4056 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4057 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4058
4059 /* force length to zero to avoid ASN1 encoding */
4060 SSL_SESSION_set1_id(sess, encid, 0);
4061
4062 /* force length to zero to avoid ASN1 encoding */
4063 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004064
4065 /* check if buffer is large enough for the ASN1 encoded session */
4066 data_len = i2d_SSL_SESSION(sess, NULL);
4067 if (data_len > SHSESS_MAX_DATA_LEN)
4068 goto err;
4069
4070 p = encsess;
4071
4072 /* process ASN1 session encoding before the lock */
4073 i2d_SSL_SESSION(sess, &p);
4074
William Lallemanded0b5ad2017-10-30 19:36:36 +01004075
William Lallemanda3c77cf2017-10-30 23:44:40 +01004076 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004077 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004078 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004079 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004080err:
4081 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004082 SSL_SESSION_set1_id(sess, encid, sid_length);
4083 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004084
4085 return 0; /* do not increment session reference count */
4086}
4087
4088/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004089SSL_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 +01004090{
William Lallemand4f45bb92017-10-30 20:08:51 +01004091 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004092 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4093 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004094 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004095 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004096
Willy Tarreau37d69392021-06-15 16:39:22 +02004097 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004098
4099 /* allow the session to be freed automatically by openssl */
4100 *do_copy = 0;
4101
4102 /* tree key is zeros padded sessionid */
4103 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4104 memcpy(tmpkey, key, key_len);
4105 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4106 key = tmpkey;
4107 }
4108
4109 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004110 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004111
4112 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004113 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4114 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004115 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004116 shctx_unlock(ssl_shctx);
Willy Tarreau37d69392021-06-15 16:39:22 +02004117 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004118 return NULL;
4119 }
4120
William Lallemand4f45bb92017-10-30 20:08:51 +01004121 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4122 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004123
William Lallemand4f45bb92017-10-30 20:08:51 +01004124 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 +01004125
William Lallemanda3c77cf2017-10-30 23:44:40 +01004126 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004127
4128 /* decode ASN1 session */
4129 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004130 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004131 /* Reset session id and session id contenxt */
4132 if (sess) {
4133 SSL_SESSION_set1_id(sess, key, key_len);
4134 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4135 }
4136
4137 return sess;
4138}
4139
William Lallemand4f45bb92017-10-30 20:08:51 +01004140
William Lallemanded0b5ad2017-10-30 19:36:36 +01004141/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004142void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004143{
William Lallemand4f45bb92017-10-30 20:08:51 +01004144 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004145 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4146 unsigned int sid_length;
4147 const unsigned char *sid_data;
4148 (void)ctx;
4149
4150 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4151 /* tree key is zeros padded sessionid */
4152 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4153 memcpy(tmpkey, sid_data, sid_length);
4154 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4155 sid_data = tmpkey;
4156 }
4157
William Lallemanda3c77cf2017-10-30 23:44:40 +01004158 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004159
4160 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004161 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4162 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004163 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004164 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004165 }
4166
4167 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004168 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004169}
4170
4171/* Set session cache mode to server and disable openssl internal cache.
4172 * Set shared cache callbacks on an ssl context.
4173 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004174void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004175{
4176 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4177
4178 if (!ssl_shctx) {
4179 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4180 return;
4181 }
4182
4183 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4184 SSL_SESS_CACHE_NO_INTERNAL |
4185 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4186
4187 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004188 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4189 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4190 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004191}
William Lallemand7d42ef52020-07-06 11:41:30 +02004192
4193/*
4194 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4195 *
4196 * The format is:
4197 * * <Label> <space> <ClientRandom> <space> <Secret>
4198 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4199 */
4200
William Lallemandca5cf0a2021-06-09 16:46:12 +02004201#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004202void SSL_CTX_keylog(const SSL *ssl, const char *line)
4203{
4204 struct ssl_keylog *keylog;
4205 char *lastarg = NULL;
4206 char *dst = NULL;
4207
4208 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4209 if (!keylog)
4210 return;
4211
4212 lastarg = strrchr(line, ' ');
4213 if (lastarg == NULL || ++lastarg == NULL)
4214 return;
4215
4216 dst = pool_alloc(pool_head_ssl_keylog_str);
4217 if (!dst)
4218 return;
4219
4220 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4221 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4222
4223 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4224 if (keylog->client_random)
4225 goto error;
4226 keylog->client_random = dst;
4227
4228 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4229 if (keylog->client_early_traffic_secret)
4230 goto error;
4231 keylog->client_early_traffic_secret = dst;
4232
4233 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4234 if(keylog->client_handshake_traffic_secret)
4235 goto error;
4236 keylog->client_handshake_traffic_secret = dst;
4237
4238 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4239 if (keylog->server_handshake_traffic_secret)
4240 goto error;
4241 keylog->server_handshake_traffic_secret = dst;
4242
4243 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4244 if (keylog->client_traffic_secret_0)
4245 goto error;
4246 keylog->client_traffic_secret_0 = dst;
4247
4248 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4249 if (keylog->server_traffic_secret_0)
4250 goto error;
4251 keylog->server_traffic_secret_0 = dst;
4252
4253 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4254 if (keylog->early_exporter_secret)
4255 goto error;
4256 keylog->early_exporter_secret = dst;
4257
4258 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4259 if (keylog->exporter_secret)
4260 goto error;
4261 keylog->exporter_secret = dst;
4262 } else {
4263 goto error;
4264 }
4265
4266 return;
4267
4268error:
4269 pool_free(pool_head_ssl_keylog_str, dst);
4270
4271 return;
4272}
4273#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004274
William Lallemand8b453912019-11-21 15:48:10 +01004275/*
4276 * This function applies the SSL configuration on a SSL_CTX
4277 * It returns an error code and fills the <err> buffer
4278 */
4279int 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 +01004280{
4281 struct proxy *curproxy = bind_conf->frontend;
4282 int cfgerr = 0;
4283 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004284 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004285 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004286#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004287 const char *conf_ciphersuites;
4288#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004289 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004290
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004291 if (ssl_conf) {
4292 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4293 int i, min, max;
4294 int flags = MC_SSL_O_ALL;
4295
4296 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004297 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4298 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004299 if (min)
4300 flags |= (methodVersions[min].flag - 1);
4301 if (max)
4302 flags |= ~((methodVersions[max].flag << 1) - 1);
4303 min = max = CONF_TLSV_NONE;
4304 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4305 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4306 if (min)
4307 max = i;
4308 else
4309 min = max = i;
4310 }
4311 /* save real min/max */
4312 conf_ssl_methods->min = min;
4313 conf_ssl_methods->max = max;
4314 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004315 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4316 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004317 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004318 }
4319 }
4320
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004321 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004322 case SSL_SOCK_VERIFY_NONE:
4323 verify = SSL_VERIFY_NONE;
4324 break;
4325 case SSL_SOCK_VERIFY_OPTIONAL:
4326 verify = SSL_VERIFY_PEER;
4327 break;
4328 case SSL_SOCK_VERIFY_REQUIRED:
4329 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4330 break;
4331 }
4332 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4333 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004334 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 +01004335 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 +01004336 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 +01004337 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004338 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004339 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004340 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004341 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004342 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004343 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004344 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4345 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4346 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4347 cfgerr |= ERR_ALERT | ERR_FATAL;
4348 }
4349 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004350 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004351 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 +02004352 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004353 }
Emeric Brun850efd52014-01-29 12:24:34 +01004354 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004355 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4356 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004357 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004358 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004359#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004360 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004361 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4362
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004363 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004364 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4365 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004366 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004367 }
Emeric Brun561e5742012-10-02 15:20:55 +02004368 else {
4369 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4370 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004371 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004372#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004373 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004374 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004375#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004376 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004377 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004378 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4379 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004380 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004381 }
4382 }
4383#endif
4384
William Lallemand4f45bb92017-10-30 20:08:51 +01004385 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004386 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4387 if (conf_ciphers &&
4388 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004389 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4390 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004391 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004392 }
4393
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004394#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004395 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4396 if (conf_ciphersuites &&
4397 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004398 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4399 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004400 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004401 }
4402#endif
4403
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004404#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004405 /* If tune.ssl.default-dh-param has not been set,
4406 neither has ssl-default-dh-file and no static DH
4407 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004408 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004409 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004410 (ssl_dh_ptr_index == -1 ||
4411 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004412 /* default to dh-param 2048 */
4413 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004414 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004415
Willy Tarreauef934602016-12-22 23:12:01 +01004416 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004417 if (local_dh_1024 == NULL) {
4418 local_dh_1024 = ssl_get_dh_1024();
4419 }
Willy Tarreauef934602016-12-22 23:12:01 +01004420 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004421 if (local_dh_2048 == NULL) {
4422 local_dh_2048 = ssl_get_dh_2048();
4423 }
Willy Tarreauef934602016-12-22 23:12:01 +01004424 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004425 if (local_dh_4096 == NULL) {
4426 local_dh_4096 = ssl_get_dh_4096();
4427 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004428 }
4429 }
4430 }
4431#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004432
Emeric Brunfc0421f2012-09-07 17:30:07 +02004433 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004434#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004435 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004436#endif
William Lallemandca5cf0a2021-06-09 16:46:12 +02004437#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004438 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
4439#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004440
Bernard Spil13c53f82018-02-15 13:34:58 +01004441#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004442 ssl_conf_cur = NULL;
4443 if (ssl_conf && ssl_conf->npn_str)
4444 ssl_conf_cur = ssl_conf;
4445 else if (bind_conf->ssl_conf.npn_str)
4446 ssl_conf_cur = &bind_conf->ssl_conf;
4447 if (ssl_conf_cur)
4448 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004449#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004450#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004451 ssl_conf_cur = NULL;
4452 if (ssl_conf && ssl_conf->alpn_str)
4453 ssl_conf_cur = ssl_conf;
4454 else if (bind_conf->ssl_conf.alpn_str)
4455 ssl_conf_cur = &bind_conf->ssl_conf;
4456 if (ssl_conf_cur)
4457 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004458#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004459#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004460 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4461 if (conf_curves) {
4462 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004463 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4464 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004465 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004466 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004467 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004468 }
4469#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004470#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004471 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004472 int i;
4473 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004474#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004475 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004476 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4477 NULL);
4478
4479 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004480 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004481 return cfgerr;
4482 }
4483#else
4484 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4485 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4486 ECDHE_DEFAULT_CURVE);
4487#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004488
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004489 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004490 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004491 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4492 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004493 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004494 }
4495 else {
4496 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4497 EC_KEY_free(ecdh);
4498 }
4499 }
4500#endif
4501
Emeric Brunfc0421f2012-09-07 17:30:07 +02004502 return cfgerr;
4503}
4504
Evan Broderbe554312013-06-27 00:05:25 -07004505static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4506{
4507 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4508 size_t prefixlen, suffixlen;
4509
4510 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004511 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004512 return 1;
4513
Evan Broderbe554312013-06-27 00:05:25 -07004514 /* The rest of this logic is based on RFC 6125, section 6.4.3
4515 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4516
Emeric Bruna848dae2013-10-08 11:27:28 +02004517 pattern_wildcard = NULL;
4518 pattern_left_label_end = pattern;
4519 while (*pattern_left_label_end != '.') {
4520 switch (*pattern_left_label_end) {
4521 case 0:
4522 /* End of label not found */
4523 return 0;
4524 case '*':
4525 /* If there is more than one wildcards */
4526 if (pattern_wildcard)
4527 return 0;
4528 pattern_wildcard = pattern_left_label_end;
4529 break;
4530 }
4531 pattern_left_label_end++;
4532 }
4533
4534 /* If it's not trivial and there is no wildcard, it can't
4535 * match */
4536 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004537 return 0;
4538
4539 /* Make sure all labels match except the leftmost */
4540 hostname_left_label_end = strchr(hostname, '.');
4541 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004542 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004543 return 0;
4544
4545 /* Make sure the leftmost label of the hostname is long enough
4546 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004547 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004548 return 0;
4549
4550 /* Finally compare the string on either side of the
4551 * wildcard */
4552 prefixlen = pattern_wildcard - pattern;
4553 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004554 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4555 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004556 return 0;
4557
4558 return 1;
4559}
4560
4561static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4562{
4563 SSL *ssl;
4564 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004565 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004566 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004567 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004568
4569 int depth;
4570 X509 *cert;
4571 STACK_OF(GENERAL_NAME) *alt_names;
4572 int i;
4573 X509_NAME *cert_subject;
4574 char *str;
4575
4576 if (ok == 0)
4577 return ok;
4578
4579 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004580 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004581 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004582
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004583 /* We're checking if the provided hostnames match the desired one. The
4584 * desired hostname comes from the SNI we presented if any, or if not
4585 * provided then it may have been explicitly stated using a "verifyhost"
4586 * directive. If neither is set, we don't care about the name so the
4587 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004588 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004589 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004590 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004591 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004592 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004593 if (!servername)
4594 return ok;
4595 }
Evan Broderbe554312013-06-27 00:05:25 -07004596
4597 /* We only need to verify the CN on the actual server cert,
4598 * not the indirect CAs */
4599 depth = X509_STORE_CTX_get_error_depth(ctx);
4600 if (depth != 0)
4601 return ok;
4602
4603 /* At this point, the cert is *not* OK unless we can find a
4604 * hostname match */
4605 ok = 0;
4606
4607 cert = X509_STORE_CTX_get_current_cert(ctx);
4608 /* It seems like this might happen if verify peer isn't set */
4609 if (!cert)
4610 return ok;
4611
4612 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4613 if (alt_names) {
4614 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4615 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4616 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004617#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004618 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4619#else
Evan Broderbe554312013-06-27 00:05:25 -07004620 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004621#endif
Evan Broderbe554312013-06-27 00:05:25 -07004622 ok = ssl_sock_srv_hostcheck(str, servername);
4623 OPENSSL_free(str);
4624 }
4625 }
4626 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004627 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004628 }
4629
4630 cert_subject = X509_get_subject_name(cert);
4631 i = -1;
4632 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4633 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004634 ASN1_STRING *value;
4635 value = X509_NAME_ENTRY_get_data(entry);
4636 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004637 ok = ssl_sock_srv_hostcheck(str, servername);
4638 OPENSSL_free(str);
4639 }
4640 }
4641
Willy Tarreau71d058c2017-07-26 20:09:56 +02004642 /* report the mismatch and indicate if SNI was used or not */
4643 if (!ok && !conn->err_code)
4644 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004645 return ok;
4646}
4647
Emeric Brun94324a42012-10-11 14:00:19 +02004648/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004649int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004650{
Willy Tarreau03209342016-12-22 17:08:28 +01004651 struct proxy *curproxy = srv->proxy;
Emeric Brun94324a42012-10-11 14:00:19 +02004652 int cfgerr = 0;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004653 SSL_CTX *ctx = srv->ssl_ctx.ctx;
Emeric Brun94324a42012-10-11 14:00:19 +02004654
Thierry Fournier383085f2013-01-24 14:15:43 +01004655 /* Make sure openssl opens /dev/urandom before the chroot */
4656 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004657 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004658 cfgerr++;
4659 }
4660
Willy Tarreaufce03112015-01-15 21:32:40 +01004661 /* Automatic memory computations need to know we use SSL there */
4662 global.ssl_used_backend = 1;
4663
4664 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004665 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004666 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004667 ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4668 curproxy->id, srv->id,
4669 srv->conf.file, srv->conf.line);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004670 cfgerr++;
4671 return cfgerr;
4672 }
4673 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004674 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004675 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004676
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004677 /* The context will be uninitialized if there wasn't any "cert" option
4678 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004679 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004680 ctx = SSL_CTX_new(SSLv23_client_method());
4681 if (!ctx) {
4682 ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4683 proxy_type_str(curproxy), curproxy->id,
4684 srv->id);
4685 cfgerr++;
4686 return cfgerr;
4687 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004688
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004689 srv->ssl_ctx.ctx = ctx;
4690 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004691
4692 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, srv->ssl_ctx.ctx);
4693
4694 return cfgerr;
4695}
4696
4697
4698/* Initialize an SSL context that will be used on the backend side.
4699 * Returns an error count.
4700 */
4701int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
4702{
4703 struct proxy *curproxy = srv->proxy;
4704 int cfgerr = 0;
4705 long options =
4706 SSL_OP_ALL | /* all known workarounds for bugs */
4707 SSL_OP_NO_SSLv2 |
4708 SSL_OP_NO_COMPRESSION;
4709 long mode =
4710 SSL_MODE_ENABLE_PARTIAL_WRITE |
4711 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4712 SSL_MODE_RELEASE_BUFFERS |
4713 SSL_MODE_SMALL_BUFFERS;
4714 int verify = SSL_VERIFY_NONE;
4715 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4716 int i, min, max, hole;
4717 int flags = MC_SSL_O_ALL;
4718
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004719 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004720 ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4721 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4722 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004723 else
4724 flags = conf_ssl_methods->flags;
4725
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004726 /* Real min and max should be determinate with configuration and openssl's capabilities */
4727 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004728 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004729 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004730 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004731
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004732 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004733 min = max = CONF_TLSV_NONE;
4734 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004735 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004736 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004737 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004738 if (min) {
4739 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004740 ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4741 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4742 proxy_type_str(curproxy), curproxy->id, srv->id,
4743 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004744 hole = 0;
4745 }
4746 max = i;
4747 }
4748 else {
4749 min = max = i;
4750 }
4751 }
4752 else {
4753 if (min)
4754 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004755 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004756 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004757 ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4758 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004759 cfgerr += 1;
4760 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004761
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004762#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004763 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004764 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004765 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004766 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004767 else
4768 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4769 if (flags & methodVersions[i].flag)
4770 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004771#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004772 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004773 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4774 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004775#endif
4776
4777 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4778 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004779 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004780
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004781#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004782 if (global_ssl.async)
4783 mode |= SSL_MODE_ASYNC;
4784#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004785 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004786
Emeric Brun850efd52014-01-29 12:24:34 +01004787 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4788 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004789 switch (srv->ssl_ctx.verify) {
4790 case SSL_SOCK_VERIFY_NONE:
4791 verify = SSL_VERIFY_NONE;
4792 break;
4793 case SSL_SOCK_VERIFY_REQUIRED:
4794 verify = SSL_VERIFY_PEER;
4795 break;
4796 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004797 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004798 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004799 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004800 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004801 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004802 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004803 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to set CA file '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004804 curproxy->id, srv->id,
4805 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004806 cfgerr++;
4807 }
4808 }
Emeric Brun850efd52014-01-29 12:24:34 +01004809 else {
4810 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Christopher Faulet767a84b2017-11-24 16:50:31 +01004811 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled by default but no CA file specified. If you're running on a LAN where you're certain to trust the server's certificate, please set an explicit 'verify none' statement on the 'server' line, or use 'ssl-server-verify none' in the global section to disable server-side verifications by default.\n",
4812 curproxy->id, srv->id,
4813 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004814 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01004815 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4816 curproxy->id, srv->id,
4817 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004818 cfgerr++;
4819 }
Emeric Brunef42d922012-10-11 16:11:36 +02004820#ifdef X509_V_FLAG_CRL_CHECK
4821 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004822 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02004823
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004824 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004825 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4826 curproxy->id, srv->id,
4827 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004828 cfgerr++;
4829 }
4830 else {
4831 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4832 }
4833 }
4834#endif
4835 }
4836
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004837 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
4838 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004839 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004840 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004841 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4842 curproxy->id, srv->id,
4843 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004844 cfgerr++;
4845 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004846
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004847#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004848 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004849 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004850 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4851 curproxy->id, srv->id,
4852 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4853 cfgerr++;
4854 }
4855#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004856#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4857 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004858 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01004859#endif
4860#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4861 if (srv->ssl_ctx.alpn_str)
4862 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4863#endif
4864
Emeric Brun94324a42012-10-11 14:00:19 +02004865
4866 return cfgerr;
4867}
4868
Frédéric Lécailleec216522020-11-23 14:33:30 +01004869/*
4870 * Create an initial CTX used to start the SSL connections.
4871 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
4872 * Returns 0 if succeeded, or something >0 if not.
4873 */
4874#ifdef USE_QUIC
4875static int ssl_initial_ctx(struct bind_conf *bind_conf)
4876{
4877 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
4878 return ssl_quic_initial_ctx(bind_conf);
4879 else
4880 return ssl_sock_initial_ctx(bind_conf);
4881}
4882#else
4883static int ssl_initial_ctx(struct bind_conf *bind_conf)
4884{
4885 return ssl_sock_initial_ctx(bind_conf);
4886}
4887#endif
4888
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004889/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004890 * be NULL, in which case nothing is done. Returns the number of errors
4891 * encountered.
4892 */
Willy Tarreau03209342016-12-22 17:08:28 +01004893int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004894{
4895 struct ebmb_node *node;
4896 struct sni_ctx *sni;
4897 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004898 int errcode = 0;
4899 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004900
Willy Tarreaufce03112015-01-15 21:32:40 +01004901 /* Automatic memory computations need to know we use SSL there */
4902 global.ssl_used_frontend = 1;
4903
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004904 /* Make sure openssl opens /dev/urandom before the chroot */
4905 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004906 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004907 err++;
4908 }
4909 /* Create initial_ctx used to start the ssl connection before do switchctx */
4910 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01004911 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004912 /* It should not be necessary to call this function, but it's
4913 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01004914 to initial_ctx in ssl_initial_ctx. */
William Lallemand8b453912019-11-21 15:48:10 +01004915 errcode |= ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004916 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004917 if (bind_conf->default_ctx)
William Lallemand8b453912019-11-21 15:48:10 +01004918 errcode |= ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, &errmsg);
Emeric Brun0bed9942014-10-30 19:25:24 +01004919
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004920 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004921 while (node) {
4922 sni = ebmb_entry(node, struct sni_ctx, name);
Emeric Brun0bed9942014-10-30 19:25:24 +01004923 if (!sni->order && sni->ctx != bind_conf->default_ctx)
4924 /* only initialize the CTX on its first occurrence and
4925 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004926 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004927 node = ebmb_next(node);
4928 }
4929
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004930 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004931 while (node) {
4932 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004933 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004934 /* only initialize the CTX on its first occurrence and
4935 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004936 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
4937 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004938 node = ebmb_next(node);
4939 }
William Lallemand8b453912019-11-21 15:48:10 +01004940
4941 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004942 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004943 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004944 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004945 err++;
4946 }
4947
4948 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004949 return err;
4950}
4951
Willy Tarreau55d37912016-12-21 23:38:39 +01004952/* Prepares all the contexts for a bind_conf and allocates the shared SSL
4953 * context if needed. Returns < 0 on error, 0 on success. The warnings and
4954 * alerts are directly emitted since the rest of the stack does it below.
4955 */
4956int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
4957{
4958 struct proxy *px = bind_conf->frontend;
4959 int alloc_ctx;
4960 int err;
4961
4962 if (!bind_conf->is_ssl) {
4963 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004964 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
4965 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01004966 }
4967 return 0;
4968 }
4969 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004970 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004971 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
4972 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004973 }
4974 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004975 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
4976 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004977 return -1;
4978 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004979 }
William Lallemandc61c0b32017-12-04 18:46:39 +01004980 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004981 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02004982 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01004983 sizeof(*sh_ssl_sess_tree),
4984 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02004985 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004986 if (alloc_ctx == SHCTX_E_INIT_LOCK)
4987 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");
4988 else
4989 ha_alert("Unable to allocate SSL session cache.\n");
4990 return -1;
4991 }
4992 /* free block callback */
4993 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
4994 /* init the root tree within the extra space */
4995 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
4996 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01004997 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004998 err = 0;
4999 /* initialize all certificate contexts */
5000 err += ssl_sock_prepare_all_ctx(bind_conf);
5001
5002 /* initialize CA variables if the certificates generation is enabled */
5003 err += ssl_sock_load_ca(bind_conf);
5004
5005 return -err;
5006}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005007
5008/* release ssl context allocated for servers. */
5009void ssl_sock_free_srv_ctx(struct server *srv)
5010{
Olivier Houchardc7566002018-11-20 23:33:50 +01005011#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5012 if (srv->ssl_ctx.alpn_str)
Willy Tarreaue709e822021-02-26 21:06:32 +01005013 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005014#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005015#ifdef OPENSSL_NPN_NEGOTIATED
Olivier Houchardc7566002018-11-20 23:33:50 +01005016 if (srv->ssl_ctx.npn_str)
Willy Tarreaue709e822021-02-26 21:06:32 +01005017 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005018#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005019 if (srv->ssl_ctx.reused_sess) {
5020 int i;
5021
5022 for (i = 0; i < global.nbthread; i++)
Willy Tarreaue709e822021-02-26 21:06:32 +01005023 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
5024 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005025 }
5026
Willy Tarreaue709e822021-02-26 21:06:32 +01005027 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005028 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005029 srv->ssl_ctx.ctx = NULL;
5030 }
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005031}
5032
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005033/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005034 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5035 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005036void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005037{
5038 struct ebmb_node *node, *back;
5039 struct sni_ctx *sni;
5040
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005041 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005042 while (node) {
5043 sni = ebmb_entry(node, struct sni_ctx, name);
5044 back = ebmb_next(node);
5045 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005046 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005047 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005048 free(sni);
5049 node = back;
5050 }
5051
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005052 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005053 while (node) {
5054 sni = ebmb_entry(node, struct sni_ctx, name);
5055 back = ebmb_next(node);
5056 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005057 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005058 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005059 free(sni);
5060 node = back;
5061 }
William Lallemandb2408692020-06-24 09:54:29 +02005062
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005063 SSL_CTX_free(bind_conf->initial_ctx);
5064 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005065 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005066 bind_conf->default_ctx = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005067 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005068}
William Lallemandb2408692020-06-24 09:54:29 +02005069
5070
5071void ssl_sock_deinit()
5072{
5073 crtlist_deinit(); /* must be free'd before the ckchs */
5074 ckch_deinit();
5075}
5076REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005077
Willy Tarreau795cdab2016-12-22 17:30:54 +01005078/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5079void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5080{
5081 ssl_sock_free_ca(bind_conf);
5082 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005083 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005084 free(bind_conf->ca_sign_file);
5085 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005086 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005087 free(bind_conf->keys_ref->filename);
5088 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005089 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005090 free(bind_conf->keys_ref);
5091 }
5092 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005093 bind_conf->ca_sign_pass = NULL;
5094 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005095}
5096
Christopher Faulet31af49d2015-06-09 17:29:50 +02005097/* Load CA cert file and private key used to generate certificates */
5098int
Willy Tarreau03209342016-12-22 17:08:28 +01005099ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005100{
Willy Tarreau03209342016-12-22 17:08:28 +01005101 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03005102 struct cert_key_and_chain *ckch = NULL;
5103 int ret = 0;
5104 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005105
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02005106 if (!bind_conf->generate_certs)
Shimi Gersner5846c492020-08-23 13:58:12 +03005107 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005108
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005109#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005110 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005111 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005112 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005113 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005114 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005115#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005116
Christopher Faulet31af49d2015-06-09 17:29:50 +02005117 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005118 ha_alert("Proxy '%s': cannot enable certificate generation, "
5119 "no CA certificate File configured at [%s:%d].\n",
5120 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005121 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005122 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005123
Shimi Gersner5846c492020-08-23 13:58:12 +03005124 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02005125 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03005126 if (!ckch) {
5127 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5128 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5129 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005130 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005131
5132 /* Try to parse file */
5133 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
5134 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5135 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005136 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005137 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005138 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005139
5140 /* Fail if missing cert or pkey */
5141 if ((!ckch->cert) || (!ckch->key)) {
5142 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5143 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5144 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005145 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005146
Shimi Gersner5846c492020-08-23 13:58:12 +03005147 /* Final assignment to bind */
5148 bind_conf->ca_sign_ckch = ckch;
5149 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005150
Shimi Gersner5846c492020-08-23 13:58:12 +03005151 failed:
5152 if (ckch) {
5153 ssl_sock_free_cert_key_and_chain_contents(ckch);
5154 free(ckch);
5155 }
5156
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005157 bind_conf->generate_certs = 0;
Shimi Gersner5846c492020-08-23 13:58:12 +03005158 ret++;
5159 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005160}
5161
5162/* Release CA cert and private key used to generate certificated */
5163void
5164ssl_sock_free_ca(struct bind_conf *bind_conf)
5165{
Shimi Gersner5846c492020-08-23 13:58:12 +03005166 if (bind_conf->ca_sign_ckch) {
5167 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005168 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005169 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005170}
5171
Emeric Brun46591952012-05-18 15:47:34 +02005172/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005173 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5174 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5175 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5176 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005177 * 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 +01005178 * as parameters to this function.
5179 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5180 * CO_ER_SSL_NO_MEM.
5181 */
5182int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5183 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5184{
5185 int retry = 1;
5186
5187 retry:
5188 /* Alloc a new SSL session. */
5189 *ssl = SSL_new(ssl_ctx);
5190 if (!*ssl) {
5191 if (!retry--)
5192 goto err;
5193
5194 pool_gc(NULL);
5195 goto retry;
5196 }
5197
5198 *bio = BIO_new(bio_meth);
5199 if (!*bio) {
5200 SSL_free(*ssl);
5201 *ssl = NULL;
5202 if (!retry--)
5203 goto err;
5204
5205 pool_gc(NULL);
5206 goto retry;
5207 }
5208
5209 BIO_set_data(*bio, ctx);
5210 SSL_set_bio(*ssl, *bio, *bio);
5211
5212 /* set connection pointer. */
5213 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5214 SSL_free(*ssl);
5215 *ssl = NULL;
5216 if (!retry--)
5217 goto err;
5218
5219 pool_gc(NULL);
5220 goto retry;
5221 }
5222
5223 return 0;
5224
5225 err:
5226 conn->err_code = CO_ER_SSL_NO_MEM;
5227 return -1;
5228}
5229
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005230/* This function is called when all the XPRT have been initialized. We can
5231 * now attempt to start the SSL handshake.
5232 */
5233static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5234{
5235 struct ssl_sock_ctx *ctx = xprt_ctx;
5236
5237 if (ctx->xprt->start) {
5238 int ret;
5239
5240 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5241 if (ret < 0)
5242 return ret;
5243 }
5244 tasklet_wakeup(ctx->wait_event.tasklet);
5245
5246 return 0;
5247}
5248
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005249/*
Emeric Brun46591952012-05-18 15:47:34 +02005250 * This function is called if SSL * context is not yet allocated. The function
5251 * is designed to be called before any other data-layer operation and sets the
5252 * handshake flag on the connection. It is safe to call it multiple times.
5253 * It returns 0 on success and -1 in error case.
5254 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005255static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005256{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005257 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005258 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005259 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005260 return 0;
5261
Olivier Houchard66ab4982019-02-26 18:37:15 +01005262 ctx = pool_alloc(ssl_sock_ctx_pool);
5263 if (!ctx) {
5264 conn->err_code = CO_ER_SSL_NO_MEM;
5265 return -1;
5266 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005267 ctx->wait_event.tasklet = tasklet_new();
5268 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005269 conn->err_code = CO_ER_SSL_NO_MEM;
5270 pool_free(ssl_sock_ctx_pool, ctx);
5271 return -1;
5272 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005273 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5274 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005275 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005276 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005277 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005278 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005279 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005280 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005281 ctx->xprt_st = 0;
5282 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005283
5284 /* Only work with sockets for now, this should be adapted when we'll
5285 * add QUIC support.
5286 */
5287 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005288 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005289 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5290 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005291 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005292
Willy Tarreau20879a02012-12-03 16:32:10 +01005293 if (global.maxsslconn && sslconns >= global.maxsslconn) {
5294 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005295 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005296 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005297
Emeric Brun46591952012-05-18 15:47:34 +02005298 /* If it is in client mode initiate SSL session
5299 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005300 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005301 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5302 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005303 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005304
Olivier Houchard66ab4982019-02-26 18:37:15 +01005305 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005306 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005307 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5308 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5309 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 +01005310 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005311 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005312 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005313 } else if (sess) {
5314 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005315 }
5316 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005317 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005318
Emeric Brun46591952012-05-18 15:47:34 +02005319 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005320 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005321
Willy Tarreau4781b152021-04-06 13:53:36 +02005322 _HA_ATOMIC_INC(&sslconns);
5323 _HA_ATOMIC_INC(&totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005324 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005325 return 0;
5326 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005327 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005328 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005329
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005330 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5331 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005332 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005333
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005334#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005335 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005336 b_alloc(&ctx->early_buf);
5337 SSL_set_max_early_data(ctx->ssl,
5338 /* Only allow early data if we managed to allocate
5339 * a buffer.
5340 */
5341 (!b_is_null(&ctx->early_buf)) ?
5342 global.tune.bufsize - global.tune.maxrewrite : 0);
5343 }
5344#endif
5345
Olivier Houchard66ab4982019-02-26 18:37:15 +01005346 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005347
Emeric Brun46591952012-05-18 15:47:34 +02005348 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005349 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005350#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005351 if (bc->ssl_conf.early_data)
5352 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005353#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005354
Willy Tarreau4781b152021-04-06 13:53:36 +02005355 _HA_ATOMIC_INC(&sslconns);
5356 _HA_ATOMIC_INC(&totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005357 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005358 return 0;
5359 }
5360 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005361 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005362err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005363 if (ctx && ctx->wait_event.tasklet)
5364 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005365 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005366 return -1;
5367}
5368
5369
5370/* This is the callback which is used when an SSL handshake is pending. It
5371 * updates the FD status if it wants some polling before being called again.
5372 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5373 * otherwise it returns non-zero and removes itself from the connection's
5374 * flags (the bit is provided in <flag> by the caller).
5375 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005376static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005377{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005378 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005379 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005380 struct ssl_counters *counters = NULL;
5381 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005382 struct listener *li;
5383 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005384 socklen_t lskerr;
5385 int skerr;
5386
Emeric Brun46591952012-05-18 15:47:34 +02005387
Willy Tarreau3c728722014-01-23 13:50:42 +01005388 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005389 return 0;
5390
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005391 /* get counters */
5392 switch (obj_type(conn->target)) {
5393 case OBJ_TYPE_LISTENER:
5394 li = objt_listener(conn->target);
5395 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5396 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5397 &ssl_stats_module);
5398 break;
5399
5400 case OBJ_TYPE_SERVER:
5401 srv = objt_server(conn->target);
5402 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5403 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5404 &ssl_stats_module);
5405 break;
5406
5407 default:
5408 break;
5409 }
5410
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005411 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005412 goto out_error;
5413
Willy Tarreau06300382021-02-02 15:42:25 +01005414 /* don't start calculating a handshake on a dead connection */
5415 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5416 goto out_error;
5417
5418 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5419 * status from the lower layers, so let's check the FD directly. Ideally
5420 * the xprt layers should provide some status indicating their knowledge
5421 * of shutdowns or error.
5422 */
5423 skerr = 0;
5424 lskerr = sizeof(skerr);
5425 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5426 skerr != 0)
5427 goto out_error;
5428
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005429#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005430 /*
5431 * Check if we have early data. If we do, we have to read them
5432 * before SSL_do_handshake() is called, And there's no way to
5433 * detect early data, except to try to read them
5434 */
5435 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005436 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005437
Olivier Houchard54907bb2019-12-19 15:02:39 +01005438 while (1) {
5439 ret = SSL_read_early_data(ctx->ssl,
5440 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5441 &read_data);
5442 if (ret == SSL_READ_EARLY_DATA_ERROR)
5443 goto check_error;
5444 if (read_data > 0) {
5445 conn->flags |= CO_FL_EARLY_DATA;
5446 b_add(&ctx->early_buf, read_data);
5447 }
5448 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5449 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5450 if (!b_data(&ctx->early_buf))
5451 b_free(&ctx->early_buf);
5452 break;
5453 }
5454 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005455 }
5456#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005457 /* If we use SSL_do_handshake to process a reneg initiated by
5458 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5459 * Usually SSL_write and SSL_read are used and process implicitly
5460 * the reneg handshake.
5461 * Here we use SSL_peek as a workaround for reneg.
5462 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005463 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005464 char c;
5465
Olivier Houchard66ab4982019-02-26 18:37:15 +01005466 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005467 if (ret <= 0) {
5468 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005469 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005470
Emeric Brun674b7432012-11-08 19:21:55 +01005471 if (ret == SSL_ERROR_WANT_WRITE) {
5472 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005473 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005474 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005475 return 0;
5476 }
5477 else if (ret == SSL_ERROR_WANT_READ) {
5478 /* handshake may have been completed but we have
5479 * no more data to read.
5480 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005481 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005482 ret = 1;
5483 goto reneg_ok;
5484 }
5485 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005486 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005487 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005488 return 0;
5489 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005490#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005491 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005492 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005493 return 0;
5494 }
5495#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005496 else if (ret == SSL_ERROR_SYSCALL) {
5497 /* if errno is null, then connection was successfully established */
5498 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5499 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005500 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005501#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5502 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005503 conn->err_code = CO_ER_SSL_HANDSHAKE;
5504#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005505 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005506#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005507 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005508 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005509 empty_handshake = state == TLS_ST_BEFORE;
5510#else
Lukas Tribus49799162019-07-08 14:29:15 +02005511 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5512 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005513#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005514 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005515 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005516 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005517 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5518 else
5519 conn->err_code = CO_ER_SSL_EMPTY;
5520 }
5521 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005522 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005523 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5524 else
5525 conn->err_code = CO_ER_SSL_ABORT;
5526 }
5527 }
5528 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005529 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005530 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005531 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005532 conn->err_code = CO_ER_SSL_HANDSHAKE;
5533 }
Lukas Tribus49799162019-07-08 14:29:15 +02005534#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005535 }
Emeric Brun674b7432012-11-08 19:21:55 +01005536 goto out_error;
5537 }
5538 else {
5539 /* Fail on all other handshake errors */
5540 /* Note: OpenSSL may leave unread bytes in the socket's
5541 * buffer, causing an RST to be emitted upon close() on
5542 * TCP sockets. We first try to drain possibly pending
5543 * data to avoid this as much as possible.
5544 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005545 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005546 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005547 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005548 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005549 goto out_error;
5550 }
5551 }
5552 /* read some data: consider handshake completed */
5553 goto reneg_ok;
5554 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005555 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005556check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005557 if (ret != 1) {
5558 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005559 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005560
5561 if (ret == SSL_ERROR_WANT_WRITE) {
5562 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005563 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005564 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005565 return 0;
5566 }
5567 else if (ret == SSL_ERROR_WANT_READ) {
5568 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005569 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005570 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5571 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005572 return 0;
5573 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005574#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005575 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005576 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005577 return 0;
5578 }
5579#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005580 else if (ret == SSL_ERROR_SYSCALL) {
5581 /* if errno is null, then connection was successfully established */
5582 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5583 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005584 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005585#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5586 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005587 conn->err_code = CO_ER_SSL_HANDSHAKE;
5588#else
5589 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005590#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005591 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005592 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005593 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005594#else
Lukas Tribus49799162019-07-08 14:29:15 +02005595 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5596 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005597#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005598 if (empty_handshake) {
5599 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005600 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005601 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5602 else
5603 conn->err_code = CO_ER_SSL_EMPTY;
5604 }
5605 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005606 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005607 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5608 else
5609 conn->err_code = CO_ER_SSL_ABORT;
5610 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005611 }
5612 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005613 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005614 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5615 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005616 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005617 }
Lukas Tribus49799162019-07-08 14:29:15 +02005618#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005619 }
Willy Tarreau89230192012-09-28 20:22:13 +02005620 goto out_error;
5621 }
Emeric Brun46591952012-05-18 15:47:34 +02005622 else {
5623 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005624 /* Note: OpenSSL may leave unread bytes in the socket's
5625 * buffer, causing an RST to be emitted upon close() on
5626 * TCP sockets. We first try to drain possibly pending
5627 * data to avoid this as much as possible.
5628 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005629 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005630 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005631 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005632 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005633 goto out_error;
5634 }
5635 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005636#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005637 else {
5638 /*
5639 * If the server refused the early data, we have to send a
5640 * 425 to the client, as we no longer have the data to sent
5641 * them again.
5642 */
5643 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005644 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005645 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5646 goto out_error;
5647 }
5648 }
5649 }
5650#endif
5651
Emeric Brun46591952012-05-18 15:47:34 +02005652
Emeric Brun674b7432012-11-08 19:21:55 +01005653reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005654
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005655#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005656 /* ASYNC engine API doesn't support moving read/write
5657 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005658 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005659 */
5660 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005661 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005662#endif
Emeric Brun46591952012-05-18 15:47:34 +02005663 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005664 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005665 if (objt_server(conn->target)) {
5666 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5667 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5668 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005669 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005670 else {
5671 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5672 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5673 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5674 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005675
Willy Tarreau42995282020-11-06 13:19:18 +01005676 if (counters) {
5677 ++counters->sess;
5678 ++counters_px->sess;
5679 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005680 }
Willy Tarreau42995282020-11-06 13:19:18 +01005681 else if (counters) {
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005682 ++counters->reused_sess;
5683 ++counters_px->reused_sess;
Emeric Brun46591952012-05-18 15:47:34 +02005684 }
5685
5686 /* The connection is now established at both layers, it's time to leave */
5687 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5688 return 1;
5689
5690 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005691 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005692 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005693 ERR_clear_error();
5694
Emeric Brun9fa89732012-10-04 17:09:56 +02005695 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01005696 if (objt_server(conn->target)) {
5697 struct server *s = __objt_server(conn->target);
5698 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
5699 * one cache per thread, it only prevents to flush it from the CLI in
5700 * another thread */
5701
5702 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005703 if (s->ssl_ctx.reused_sess[tid].ptr)
5704 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005705 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02005706 }
5707
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005708 if (counters) {
5709 ++counters->failed_handshake;
5710 ++counters_px->failed_handshake;
5711 }
5712
Emeric Brun46591952012-05-18 15:47:34 +02005713 /* Fail on all other handshake errors */
5714 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005715 if (!conn->err_code)
5716 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005717 return 0;
5718}
5719
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005720/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5721 * event subscriber <es> is not allowed to change from a previous call as long
5722 * as at least one event is still subscribed. The <event_type> must only be a
5723 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5724 * unless the transport layer was already released.
5725 */
5726static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005727{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005728 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005729
Olivier Houchard0ff28652019-06-24 18:57:39 +02005730 if (!ctx)
5731 return -1;
5732
Willy Tarreau113d52b2020-01-10 09:20:26 +01005733 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005734 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005735
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005736 ctx->subs = es;
5737 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005738
5739 /* we may have to subscribe to lower layers for new events */
5740 event_type &= ~ctx->wait_event.events;
5741 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5742 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005743 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005744}
5745
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005746/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5747 * The <es> pointer is not allowed to differ from the one passed to the
5748 * subscribe() call. It always returns zero.
5749 */
5750static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005751{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005752 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005753
Willy Tarreau113d52b2020-01-10 09:20:26 +01005754 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005755 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005756
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005757 es->events &= ~event_type;
5758 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005759 ctx->subs = NULL;
5760
5761 /* If we subscribed, and we're not doing the handshake,
5762 * then we subscribed because the upper layer asked for it,
5763 * as the upper layer is no longer interested, we can
5764 * unsubscribe too.
5765 */
5766 event_type &= ctx->wait_event.events;
5767 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5768 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005769
5770 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005771}
5772
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005773/* The connection has been taken over, so destroy the old tasklet and create
5774 * a new one. The original thread ID must be passed into orig_tid
5775 * It should be called with the takeover lock for the old thread held.
5776 * Returns 0 on success, and -1 on failure
5777 */
5778static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
5779{
5780 struct ssl_sock_ctx *ctx = xprt_ctx;
5781 struct tasklet *tl = tasklet_new();
5782
5783 if (!tl)
5784 return -1;
5785
5786 ctx->wait_event.tasklet->context = NULL;
5787 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
5788 ctx->wait_event.tasklet = tl;
5789 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5790 ctx->wait_event.tasklet->context = ctx;
5791 return 0;
5792}
5793
Willy Tarreau41491682021-03-02 17:29:56 +01005794/* notify the next xprt that the connection is about to become idle and that it
5795 * may be stolen at any time after the function returns and that any tasklet in
5796 * the chain must be careful before dereferencing its context.
5797 */
5798static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
5799{
5800 struct ssl_sock_ctx *ctx = xprt_ctx;
5801
5802 if (!ctx || !ctx->wait_event.tasklet)
5803 return;
5804
5805 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5806 if (ctx->xprt)
5807 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
5808}
5809
5810/* notify the next xprt that the connection is not idle anymore and that it may
5811 * not be stolen before the next xprt_set_idle().
5812 */
5813static void ssl_set_used(struct connection *conn, void *xprt_ctx)
5814{
5815 struct ssl_sock_ctx *ctx = xprt_ctx;
5816
5817 if (!ctx || !ctx->wait_event.tasklet)
5818 return;
5819
5820 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5821 if (ctx->xprt)
5822 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
5823}
5824
Olivier Houchard2e055482019-05-27 19:50:12 +02005825/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5826 * Returns 0 on success, and non-zero on failure.
5827 */
5828static 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)
5829{
5830 struct ssl_sock_ctx *ctx = xprt_ctx;
5831
5832 if (oldxprt_ops != NULL)
5833 *oldxprt_ops = ctx->xprt;
5834 if (oldxprt_ctx != NULL)
5835 *oldxprt_ctx = ctx->xprt_ctx;
5836 ctx->xprt = toadd_ops;
5837 ctx->xprt_ctx = toadd_ctx;
5838 return 0;
5839}
5840
Olivier Houchard5149b592019-05-23 17:47:36 +02005841/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5842 * return 0, otherwise just call the remove_xprt method from the underlying
5843 * XPRT.
5844 */
5845static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5846{
5847 struct ssl_sock_ctx *ctx = xprt_ctx;
5848
5849 if (ctx->xprt_ctx == toremove_ctx) {
5850 ctx->xprt_ctx = newctx;
5851 ctx->xprt = newops;
5852 return 0;
5853 }
5854 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5855}
5856
Willy Tarreau144f84a2021-03-02 16:09:26 +01005857struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02005858{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005859 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005860 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005861 struct connection *conn;
5862 int conn_in_list;
5863 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005864
Willy Tarreau41491682021-03-02 17:29:56 +01005865 if (state & TASK_F_USR1) {
5866 /* the tasklet was idling on an idle connection, it might have
5867 * been stolen, let's be careful!
5868 */
5869 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5870 if (tl->context == NULL) {
5871 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5872 tasklet_free(tl);
5873 return NULL;
5874 }
5875 conn = ctx->conn;
5876 conn_in_list = conn->flags & CO_FL_LIST_MASK;
5877 if (conn_in_list)
5878 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005879 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01005880 } else {
5881 conn = ctx->conn;
5882 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005883 }
Willy Tarreau41491682021-03-02 17:29:56 +01005884
Olivier Houchardea8dd942019-05-20 14:02:16 +02005885 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01005886 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005887 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005888 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5889 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01005890 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005891 }
5892 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005893 /* If we had an error, or the handshake is done and I/O is available,
5894 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005895 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005896 * we can't be sure conn_fd_handler() will be called again.
5897 */
5898 if ((ctx->conn->flags & CO_FL_ERROR) ||
5899 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005900 int woke = 0;
5901
5902 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005903 if (ctx->subs) {
5904 tasklet_wakeup(ctx->subs->tasklet);
5905 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005906 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005907 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005908 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005909
Olivier Houchardea8dd942019-05-20 14:02:16 +02005910 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005911 * upper layers know. If we have no mux, create it,
5912 * and once we have a mux, call its wake method if we didn't
5913 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005914 */
5915 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005916 if (!ctx->conn->mux)
5917 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005918 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005919 ret = ctx->conn->mux->wake(ctx->conn);
5920 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005921 }
5922 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05005923#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01005924 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005925 else if (b_data(&ctx->early_buf) && ctx->subs &&
5926 ctx->subs->events & SUB_RETRY_RECV) {
5927 tasklet_wakeup(ctx->subs->tasklet);
5928 ctx->subs->events &= ~SUB_RETRY_RECV;
5929 if (!ctx->subs->events)
5930 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005931 }
5932#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005933leave:
5934 if (!ret && conn_in_list) {
5935 struct server *srv = objt_server(conn->target);
5936
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005937 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005938 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau430bf4a2021-03-04 09:45:32 +01005939 ebmb_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005940 else
Willy Tarreau430bf4a2021-03-04 09:45:32 +01005941 ebmb_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005942 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005943 }
Willy Tarreau74163142021-03-13 11:30:19 +01005944 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005945}
5946
Emeric Brun46591952012-05-18 15:47:34 +02005947/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01005948 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02005949 * buffer wraps, in which case a second call may be performed. The connection's
5950 * flags are updated with whatever special event is detected (error, read0,
5951 * empty). The caller is responsible for taking care of those events and
5952 * avoiding the call if inappropriate. The function does not call the
5953 * connection's polling update function, so the caller is responsible for this.
5954 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005955static 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 +02005956{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005957 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02005958 ssize_t ret;
5959 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02005960
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005961 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005962 goto out_error;
5963
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05005964#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01005965 if (b_data(&ctx->early_buf)) {
5966 try = b_contig_space(buf);
5967 if (try > b_data(&ctx->early_buf))
5968 try = b_data(&ctx->early_buf);
5969 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
5970 b_add(buf, try);
5971 b_del(&ctx->early_buf, try);
5972 if (b_data(&ctx->early_buf) == 0)
5973 b_free(&ctx->early_buf);
5974 return try;
5975 }
5976#endif
5977
Willy Tarreau911db9b2020-01-23 16:27:54 +01005978 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005979 /* a handshake was requested */
5980 return 0;
5981
Emeric Brun46591952012-05-18 15:47:34 +02005982 /* read the largest possible block. For this, we perform only one call
5983 * to recv() unless the buffer wraps and we exactly fill the first hunk,
5984 * in which case we accept to do it once again. A new attempt is made on
5985 * EINTR too.
5986 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01005987 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005988
Willy Tarreau591d4452018-06-15 17:21:00 +02005989 try = b_contig_space(buf);
5990 if (!try)
5991 break;
5992
Willy Tarreauabf08d92014-01-14 11:31:27 +01005993 if (try > count)
5994 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02005995
Olivier Houchard66ab4982019-02-26 18:37:15 +01005996 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005997
Emeric Brune1f38db2012-09-03 20:36:47 +02005998 if (conn->flags & CO_FL_ERROR) {
5999 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006000 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006001 }
Emeric Brun46591952012-05-18 15:47:34 +02006002 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006003 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006004 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006005 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006006 }
Emeric Brun46591952012-05-18 15:47:34 +02006007 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006008 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006009 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006010 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006011 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006012 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006013#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006014 /* Async mode can be re-enabled, because we're leaving data state.*/
6015 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006016 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006017#endif
Emeric Brun46591952012-05-18 15:47:34 +02006018 break;
6019 }
6020 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006021 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006022 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6023 SUB_RETRY_RECV,
6024 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006025 /* handshake is running, and it may need to re-enable read */
6026 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006027#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006028 /* Async mode can be re-enabled, because we're leaving data state.*/
6029 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006030 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006031#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006032 break;
6033 }
Emeric Brun46591952012-05-18 15:47:34 +02006034 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006035 } else if (ret == SSL_ERROR_ZERO_RETURN)
6036 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006037 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6038 * stack before shutting down the connection for
6039 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006040 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
6041 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006042 /* otherwise it's a real error */
6043 goto out_error;
6044 }
6045 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006046 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006047 return done;
6048
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006049 clear_ssl_error:
6050 /* Clear openssl global errors stack */
6051 ssl_sock_dump_errors(conn);
6052 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006053 read0:
6054 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006055 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006056
Emeric Brun46591952012-05-18 15:47:34 +02006057 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006058 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006059 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006060 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006061 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006062 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006063}
6064
6065
Willy Tarreau787db9a2018-06-14 18:31:46 +02006066/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6067 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6068 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006069 * Only one call to send() is performed, unless the buffer wraps, in which case
6070 * a second call may be performed. The connection's flags are updated with
6071 * whatever special event is detected (error, empty). The caller is responsible
6072 * for taking care of those events and avoiding the call if inappropriate. The
6073 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006074 * is responsible for this. The buffer's output is not adjusted, it's up to the
6075 * caller to take care of this. It's up to the caller to update the buffer's
6076 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006077 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006078static 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 +02006079{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006080 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006081 ssize_t ret;
6082 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006083
6084 done = 0;
6085
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006086 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006087 goto out_error;
6088
Willy Tarreau911db9b2020-01-23 16:27:54 +01006089 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006090 /* a handshake was requested */
6091 return 0;
6092
6093 /* send the largest possible block. For this we perform only one call
6094 * to send() unless the buffer wraps and we exactly fill the first hunk,
6095 * in which case we accept to do it once again.
6096 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006097 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006098#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006099 size_t written_data;
6100#endif
6101
Willy Tarreau787db9a2018-06-14 18:31:46 +02006102 try = b_contig_data(buf, done);
6103 if (try > count)
6104 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006105
Willy Tarreau7bed9452014-02-02 02:00:24 +01006106 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006107 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006108 global_ssl.max_record && try > global_ssl.max_record) {
6109 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006110 }
6111 else {
6112 /* we need to keep the information about the fact that
6113 * we're not limiting the upcoming send(), because if it
6114 * fails, we'll have to retry with at least as many data.
6115 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006116 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006117 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006118
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006119#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006120 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006121 unsigned int max_early;
6122
Olivier Houchard522eea72017-11-03 16:27:47 +01006123 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006124 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006125 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006126 if (SSL_get0_session(ctx->ssl))
6127 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006128 else
6129 max_early = 0;
6130 }
6131
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006132 if (try + ctx->sent_early_data > max_early) {
6133 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006134 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006135 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006136 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006137 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006138 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006139 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006140 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006141 if (ret == 1) {
6142 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006143 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006144 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006145 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006146 /* Initiate the handshake, now */
6147 tasklet_wakeup(ctx->wait_event.tasklet);
6148 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006149
Olivier Houchardc2aae742017-09-22 18:26:28 +02006150 }
6151
6152 } else
6153#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006154 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006155
Emeric Brune1f38db2012-09-03 20:36:47 +02006156 if (conn->flags & CO_FL_ERROR) {
6157 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006158 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006159 }
Emeric Brun46591952012-05-18 15:47:34 +02006160 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006161 /* A send succeeded, so we can consider ourself connected */
6162 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006163 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006164 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006165 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006166 }
6167 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006168 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006169
Emeric Brun46591952012-05-18 15:47:34 +02006170 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006171 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006172 /* handshake is running, and it may need to re-enable write */
6173 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006174 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006175#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006176 /* Async mode can be re-enabled, because we're leaving data state.*/
6177 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006178 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006179#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006180 break;
6181 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006182
Emeric Brun46591952012-05-18 15:47:34 +02006183 break;
6184 }
6185 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006186 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006187 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006188 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6189 SUB_RETRY_RECV,
6190 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006191#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006192 /* Async mode can be re-enabled, because we're leaving data state.*/
6193 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006194 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006195#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006196 break;
6197 }
Emeric Brun46591952012-05-18 15:47:34 +02006198 goto out_error;
6199 }
6200 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006201 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006202 return done;
6203
6204 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006205 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006206 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006207 ERR_clear_error();
6208
Emeric Brun46591952012-05-18 15:47:34 +02006209 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006210 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006211}
6212
Willy Tarreau832e2422021-05-13 10:11:03 +02006213void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006214
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006215 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006216
Olivier Houchardea8dd942019-05-20 14:02:16 +02006217
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006218 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006219 if (ctx->wait_event.events != 0)
6220 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6221 ctx->wait_event.events,
6222 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006223 if (ctx->subs) {
6224 ctx->subs->events = 0;
6225 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006226 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006227
Olivier Houchard692c1d02019-05-23 18:41:47 +02006228 if (ctx->xprt->close)
6229 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006230#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006231 if (global_ssl.async) {
6232 OSSL_ASYNC_FD all_fd[32], afd;
6233 size_t num_all_fds = 0;
6234 int i;
6235
Olivier Houchard66ab4982019-02-26 18:37:15 +01006236 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006237 if (num_all_fds > 32) {
6238 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6239 return;
6240 }
6241
Olivier Houchard66ab4982019-02-26 18:37:15 +01006242 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006243
6244 /* If an async job is pending, we must try to
6245 to catch the end using polling before calling
6246 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006247 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006248 for (i=0 ; i < num_all_fds ; i++) {
6249 /* switch on an handler designed to
6250 * handle the SSL_free
6251 */
6252 afd = all_fd[i];
6253 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006254 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006255 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006256 /* To ensure that the fd cache won't be used
6257 * and we'll catch a real RD event.
6258 */
6259 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006260 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006261 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006262 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006263 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006264 return;
6265 }
Emeric Brun3854e012017-05-17 20:42:48 +02006266 /* Else we can remove the fds from the fdtab
6267 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006268 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006269 * because the fd is owned by the engine.
6270 * the engine is responsible to close
6271 */
6272 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +02006273 fd_stop_both(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006274 }
6275#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006276 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006277 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006278 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006279 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006280 _HA_ATOMIC_DEC(&sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006281 }
Emeric Brun46591952012-05-18 15:47:34 +02006282}
6283
6284/* This function tries to perform a clean shutdown on an SSL connection, and in
6285 * any case, flags the connection as reusable if no handshake was in progress.
6286 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006287static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006288{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006289 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006290
Willy Tarreau911db9b2020-01-23 16:27:54 +01006291 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006292 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006293 if (!clean)
6294 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006295 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006296 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006297 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006298 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006299 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006300 ERR_clear_error();
6301 }
Emeric Brun46591952012-05-18 15:47:34 +02006302}
6303
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006304
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006305/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006306int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6307{
6308 struct ssl_sock_ctx *ctx;
6309 X509 *crt;
6310
6311 if (!ssl_sock_is_ssl(conn))
6312 return 0;
6313
6314 ctx = conn->xprt_ctx;
6315
6316 crt = SSL_get_certificate(ctx->ssl);
6317 if (!crt)
6318 return 0;
6319
6320 return cert_get_pkey_algo(crt, out);
6321}
6322
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006323/* used for ppv2 cert signature (can be used for logging) */
6324const char *ssl_sock_get_cert_sig(struct connection *conn)
6325{
Christopher Faulet82004142019-09-10 10:12:03 +02006326 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006327
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006328 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6329 X509 *crt;
6330
6331 if (!ssl_sock_is_ssl(conn))
6332 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006333 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006334 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006335 if (!crt)
6336 return NULL;
6337 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6338 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6339}
6340
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006341/* used for ppv2 authority */
6342const char *ssl_sock_get_sni(struct connection *conn)
6343{
6344#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006345 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006346
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006347 if (!ssl_sock_is_ssl(conn))
6348 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006349 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006350 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006351#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006352 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006353#endif
6354}
6355
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006356/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006357const char *ssl_sock_get_cipher_name(struct connection *conn)
6358{
Christopher Faulet82004142019-09-10 10:12:03 +02006359 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006360
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006361 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006362 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006363 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006364 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006365}
6366
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006367/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006368const char *ssl_sock_get_proto_version(struct connection *conn)
6369{
Christopher Faulet82004142019-09-10 10:12:03 +02006370 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006371
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006372 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006373 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006374 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006375 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006376}
6377
Olivier Houchardab28a322018-12-21 19:45:40 +01006378void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6379{
6380#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02006381 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006382
Olivier Houcharde488ea82019-06-28 14:10:33 +02006383 if (!ssl_sock_is_ssl(conn))
6384 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006385 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006386 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006387#endif
6388}
6389
Willy Tarreau119a4082016-12-22 21:58:38 +01006390/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6391 * to disable SNI.
6392 */
Willy Tarreau63076412015-07-10 11:33:32 +02006393void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6394{
6395#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006396 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006397
Willy Tarreau119a4082016-12-22 21:58:38 +01006398 char *prev_name;
6399
Willy Tarreau63076412015-07-10 11:33:32 +02006400 if (!ssl_sock_is_ssl(conn))
6401 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006402 ctx = conn->xprt_ctx;
Willy Tarreau63076412015-07-10 11:33:32 +02006403
Willy Tarreau119a4082016-12-22 21:58:38 +01006404 /* if the SNI changes, we must destroy the reusable context so that a
6405 * new connection will present a new SNI. As an optimization we could
6406 * later imagine having a small cache of ssl_ctx to hold a few SNI per
6407 * server.
6408 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006409 prev_name = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau119a4082016-12-22 21:58:38 +01006410 if ((!prev_name && hostname) ||
6411 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006412 SSL_set_session(ctx->ssl, NULL);
Willy Tarreau119a4082016-12-22 21:58:38 +01006413
Olivier Houchard66ab4982019-02-26 18:37:15 +01006414 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006415#endif
6416}
6417
Emeric Brun0abf8362014-06-24 18:26:41 +02006418/* Extract peer certificate's common name into the chunk dest
6419 * Returns
6420 * the len of the extracted common name
6421 * or 0 if no CN found in DN
6422 * or -1 on error case (i.e. no peer certificate)
6423 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006424int ssl_sock_get_remote_common_name(struct connection *conn,
6425 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006426{
Christopher Faulet82004142019-09-10 10:12:03 +02006427 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04006428 X509 *crt = NULL;
6429 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006430 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006431 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006432 .area = (char *)&find_cn,
6433 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006434 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006435 int result = -1;
David Safb76832014-05-08 23:42:08 -04006436
6437 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02006438 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02006439 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006440
6441 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006442 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006443 if (!crt)
6444 goto out;
6445
6446 name = X509_get_subject_name(crt);
6447 if (!name)
6448 goto out;
David Safb76832014-05-08 23:42:08 -04006449
Emeric Brun0abf8362014-06-24 18:26:41 +02006450 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6451out:
David Safb76832014-05-08 23:42:08 -04006452 if (crt)
6453 X509_free(crt);
6454
6455 return result;
6456}
6457
Dave McCowan328fb582014-07-30 10:39:13 -04006458/* returns 1 if client passed a certificate for this session, 0 if not */
6459int ssl_sock_get_cert_used_sess(struct connection *conn)
6460{
Christopher Faulet82004142019-09-10 10:12:03 +02006461 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006462 X509 *crt = NULL;
6463
6464 if (!ssl_sock_is_ssl(conn))
6465 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006466 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006467
6468 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006469 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006470 if (!crt)
6471 return 0;
6472
6473 X509_free(crt);
6474 return 1;
6475}
6476
6477/* returns 1 if client passed a certificate for this connection, 0 if not */
6478int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006479{
Christopher Faulet82004142019-09-10 10:12:03 +02006480 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006481
David Safb76832014-05-08 23:42:08 -04006482 if (!ssl_sock_is_ssl(conn))
6483 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006484 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006485 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006486}
6487
6488/* returns result from SSL verify */
6489unsigned int ssl_sock_get_verify_result(struct connection *conn)
6490{
Christopher Faulet82004142019-09-10 10:12:03 +02006491 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006492
David Safb76832014-05-08 23:42:08 -04006493 if (!ssl_sock_is_ssl(conn))
6494 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006495 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006496 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006497}
6498
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006499/* Returns the application layer protocol name in <str> and <len> when known.
6500 * Zero is returned if the protocol name was not found, otherwise non-zero is
6501 * returned. The string is allocated in the SSL context and doesn't have to be
6502 * freed by the caller. NPN is also checked if available since older versions
6503 * of openssl (1.0.1) which are more common in field only support this one.
6504 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006505static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006506{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006507#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6508 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006509 struct ssl_sock_ctx *ctx = xprt_ctx;
6510 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006511 return 0;
6512
6513 *str = NULL;
6514
6515#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006516 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006517 if (*str)
6518 return 1;
6519#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006520#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006521 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006522 if (*str)
6523 return 1;
6524#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006525#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006526 return 0;
6527}
6528
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006529/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006530int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006531{
6532 X509 *ca;
6533 X509_NAME *name = NULL;
6534 ASN1_OCTET_STRING *skid = NULL;
6535 STACK_OF(X509) *chain = NULL;
6536 struct issuer_chain *issuer;
6537 struct eb64_node *node;
6538 char *path;
6539 u64 key;
6540 int ret = 0;
6541
6542 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6543 if (chain == NULL) {
6544 chain = sk_X509_new_null();
6545 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6546 name = X509_get_subject_name(ca);
6547 }
6548 if (!sk_X509_push(chain, ca)) {
6549 X509_free(ca);
6550 goto end;
6551 }
6552 }
6553 if (!chain) {
6554 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6555 goto end;
6556 }
6557 if (!skid) {
6558 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6559 goto end;
6560 }
6561 if (!name) {
6562 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6563 goto end;
6564 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006565 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006566 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006567 issuer = container_of(node, typeof(*issuer), node);
6568 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6569 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6570 goto end;
6571 }
6572 }
6573 issuer = calloc(1, sizeof *issuer);
6574 path = strdup(fp);
6575 if (!issuer || !path) {
6576 free(issuer);
6577 free(path);
6578 goto end;
6579 }
6580 issuer->node.key = key;
6581 issuer->path = path;
6582 issuer->chain = chain;
6583 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006584 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006585 ret = 1;
6586 end:
6587 if (skid)
6588 ASN1_OCTET_STRING_free(skid);
6589 if (chain)
6590 sk_X509_pop_free(chain, X509_free);
6591 return ret;
6592}
6593
William Lallemandda8584c2020-05-14 10:14:37 +02006594 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006595{
6596 AUTHORITY_KEYID *akid;
6597 struct issuer_chain *issuer = NULL;
6598
6599 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006600 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006601 struct eb64_node *node;
6602 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006603 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006604 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6605 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6606 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6607 issuer = ti;
6608 break;
6609 }
6610 }
6611 AUTHORITY_KEYID_free(akid);
6612 }
6613 return issuer;
6614}
6615
William Lallemanddad31052020-05-14 17:47:32 +02006616void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006617{
6618 struct eb64_node *node, *back;
6619 struct issuer_chain *issuer;
6620
William Lallemande0f3fd52020-02-25 14:53:06 +01006621 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006622 while (node) {
6623 issuer = container_of(node, typeof(*issuer), node);
6624 back = eb64_next(node);
6625 eb64_delete(node);
6626 free(issuer->path);
6627 sk_X509_pop_free(issuer->chain, X509_free);
6628 free(issuer);
6629 node = back;
6630 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006631}
6632
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006633#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006634static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006635 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006636
Emeric Brun3854e012017-05-17 20:42:48 +02006637 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006638 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006639 err_code = ERR_ABORT;
6640 }
6641 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006642}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006643#endif
6644
Willy Tarreaude5675a2021-01-20 14:41:29 +01006645/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006646 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006647 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006648static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006649{
6650 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006651 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006652
6653 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006654 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006655
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006656 if (sctx->conn != conn) {
6657 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6658 ret = 1;
6659 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01006660 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6661
6662 if (sctx->xprt) {
6663 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6664 if (sctx->xprt_ctx)
6665 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6666 }
6667
6668 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006669
6670 /* as soon as a shutdown is reported the lower layer unregisters its
6671 * subscriber, so the situations below are transient and rare enough to
6672 * be reported as suspicious. In any case they shouldn't last.
6673 */
6674 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
6675 ret = 1;
6676 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
6677 ret = 1;
6678
Willy Tarreaude5675a2021-01-20 14:41:29 +01006679 chunk_appendf(&trash, " .subs=%p", sctx->subs);
6680 if (sctx->subs) {
6681 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006682 if (sctx->subs->tasklet->calls >= 1000000)
6683 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006684 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
6685 sctx->subs->tasklet->calls,
6686 sctx->subs->tasklet->context);
6687 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
6688 chunk_appendf(&trash, ")");
6689 }
6690 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
6691 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006692 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006693}
6694
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006695#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02006696/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006697 * each reference. The variable <ref> must point to the current node's list
6698 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02006699 */
William Lallemand32af2032016-10-29 18:09:35 +02006700static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006701struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02006702{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006703 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006704 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02006705
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006706 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006707 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006708 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02006709
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006710 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02006711}
6712
6713static inline
6714struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6715{
6716 int id;
6717 char *error;
6718
6719 /* If the reference starts by a '#', this is numeric id. */
6720 if (reference[0] == '#') {
6721 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6722 id = strtol(reference + 1, &error, 10);
6723 if (*error != '\0')
6724 return NULL;
6725
6726 /* Perform the unique id lookup. */
6727 return tlskeys_ref_lookupid(id);
6728 }
6729
6730 /* Perform the string lookup. */
6731 return tlskeys_ref_lookup(reference);
6732}
6733#endif
6734
6735
6736#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6737
6738static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6739
6740static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6741 return cli_io_handler_tlskeys_files(appctx);
6742}
6743
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006744/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6745 * (next index to be dumped), and cli.p0 (next key reference).
6746 */
William Lallemand32af2032016-10-29 18:09:35 +02006747static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6748
6749 struct stream_interface *si = appctx->owner;
6750
6751 switch (appctx->st2) {
6752 case STAT_ST_INIT:
6753 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006754 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006755 * later and restart at the state "STAT_ST_INIT".
6756 */
6757 chunk_reset(&trash);
6758
6759 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6760 chunk_appendf(&trash, "# id secret\n");
6761 else
6762 chunk_appendf(&trash, "# id (file)\n");
6763
Willy Tarreau06d80a92017-10-19 14:32:15 +02006764 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006765 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006766 return 0;
6767 }
6768
William Lallemand32af2032016-10-29 18:09:35 +02006769 /* Now, we start the browsing of the references lists.
6770 * Note that the following call to LIST_ELEM return bad pointer. The only
6771 * available field of this pointer is <list>. It is used with the function
6772 * tlskeys_list_get_next() for retruning the first available entry
6773 */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006774 if (appctx->ctx.cli.p0 == NULL)
6775 appctx->ctx.cli.p0 = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006776
6777 appctx->st2 = STAT_ST_LIST;
6778 /* fall through */
6779
6780 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006781 while (appctx->ctx.cli.p0) {
6782 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006783
6784 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006785 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006786 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006787
6788 if (appctx->ctx.cli.i1 == 0)
6789 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6790
William Lallemand32af2032016-10-29 18:09:35 +02006791 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006792 int head;
6793
6794 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6795 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006796 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006797 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006798
6799 chunk_reset(t2);
6800 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006801 if (ref->key_size_bits == 128) {
6802 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6803 sizeof(struct tls_sess_key_128),
6804 t2->area, t2->size);
6805 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6806 t2->area);
6807 }
6808 else if (ref->key_size_bits == 256) {
6809 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6810 sizeof(struct tls_sess_key_256),
6811 t2->area, t2->size);
6812 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6813 t2->area);
6814 }
6815 else {
6816 /* This case should never happen */
6817 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6818 }
William Lallemand32af2032016-10-29 18:09:35 +02006819
Willy Tarreau06d80a92017-10-19 14:32:15 +02006820 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006821 /* let's try again later from this stream. We add ourselves into
6822 * this stream's users so that it can remove us upon termination.
6823 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006824 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006825 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006826 return 0;
6827 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006828 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006829 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006830 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006831 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006832 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006833 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006834 /* let's try again later from this stream. We add ourselves into
6835 * this stream's users so that it can remove us upon termination.
6836 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006837 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006838 return 0;
6839 }
6840
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006841 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006842 break;
6843
6844 /* get next list entry and check the end of the list */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006845 appctx->ctx.cli.p0 = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006846 }
6847
6848 appctx->st2 = STAT_ST_FIN;
6849 /* fall through */
6850
6851 default:
6852 appctx->st2 = STAT_ST_FIN;
6853 return 1;
6854 }
6855 return 0;
6856}
6857
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006858/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006859static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006860{
William Lallemand32af2032016-10-29 18:09:35 +02006861 /* no parameter, shows only file list */
6862 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006863 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006864 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006865 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006866 }
6867
6868 if (args[2][0] == '*') {
6869 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006870 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006871 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006872 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006873 if (!appctx->ctx.cli.p0)
6874 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006875 }
William Lallemand32af2032016-10-29 18:09:35 +02006876 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006877 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006878}
6879
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006880static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006881{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006882 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006883 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006884
William Lallemand32af2032016-10-29 18:09:35 +02006885 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006886 if (!*args[3] || !*args[4])
6887 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 +02006888
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006889 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006890 if (!ref)
6891 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006892
Willy Tarreau1c913e42018-08-22 05:26:57 +02006893 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006894 if (ret < 0)
6895 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006896
Willy Tarreau1c913e42018-08-22 05:26:57 +02006897 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006898 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6899 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006900
Willy Tarreau9d008692019-08-09 11:21:01 +02006901 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006902}
William Lallemandd4f946c2019-12-05 10:26:40 +01006903#endif
William Lallemand419e6342020-04-08 12:05:39 +02006904
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006905static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006906{
6907#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6908 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006909 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006910
6911 if (!payload)
6912 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006913
6914 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006915 if (!*payload)
6916 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006917
6918 /* remove \r and \n from the payload */
6919 for (i = 0, j = 0; payload[i]; i++) {
6920 if (payload[i] == '\r' || payload[i] == '\n')
6921 continue;
6922 payload[j++] = payload[i];
6923 }
6924 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006925
Willy Tarreau1c913e42018-08-22 05:26:57 +02006926 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006927 if (ret < 0)
6928 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006929
Willy Tarreau1c913e42018-08-22 05:26:57 +02006930 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02006931 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02006932 if (err)
6933 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
6934 else
6935 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006936 }
Willy Tarreau9d008692019-08-09 11:21:01 +02006937
6938 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006939#else
Willy Tarreau9d008692019-08-09 11:21:01 +02006940 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 +02006941#endif
6942
Elliot Otchet71f82972020-01-15 08:12:14 -05006943}
6944
William Lallemand32af2032016-10-29 18:09:35 +02006945/* register cli keywords */
6946static struct cli_kw_list cli_kws = {{ },{
6947#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Willy Tarreaub205bfd2021-05-07 11:38:37 +02006948 { { "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 },
6949 { { "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 +02006950#endif
Willy Tarreaub205bfd2021-05-07 11:38:37 +02006951 { { "set", "ssl", "ocsp-response", NULL }, "set ssl ocsp-response <resp|payload> : update a certificate's OCSP Response from a base64-encode DER", cli_parse_set_ocspresponse, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02006952 { { NULL }, NULL, NULL, NULL }
6953}};
6954
Willy Tarreau0108d902018-11-25 19:14:37 +01006955INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02006956
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02006957/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02006958struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02006959 .snd_buf = ssl_sock_from_buf,
6960 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01006961 .subscribe = ssl_subscribe,
6962 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02006963 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02006964 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02006965 .rcv_pipe = NULL,
6966 .snd_pipe = NULL,
6967 .shutr = NULL,
6968 .shutw = ssl_sock_shutw,
6969 .close = ssl_sock_close,
6970 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01006971 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01006972 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01006973 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01006974 .prepare_srv = ssl_sock_prepare_srv_ctx,
6975 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006976 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006977 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01006978 .set_idle = ssl_set_idle,
6979 .set_used = ssl_set_used,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01006980 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01006981 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02006982};
6983
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006984enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
6985 struct session *sess, struct stream *s, int flags)
6986{
6987 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006988 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006989
6990 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006991 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006992
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006993 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006994 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006995 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006996 s->req.flags |= CF_READ_NULL;
6997 return ACT_RET_YIELD;
6998 }
6999 }
7000 return (ACT_RET_CONT);
7001}
7002
7003static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7004{
7005 rule->action_ptr = ssl_action_wait_for_hs;
7006
7007 return ACT_RET_PRS_OK;
7008}
7009
7010static struct action_kw_list http_req_actions = {ILH, {
7011 { "wait-for-handshake", ssl_parse_wait_for_hs },
7012 { /* END */ }
7013}};
7014
Willy Tarreau0108d902018-11-25 19:14:37 +01007015INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7016
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007017#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007018
7019static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7020{
7021 if (ptr) {
7022 chunk_destroy(ptr);
7023 free(ptr);
7024 }
7025}
7026
7027#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007028
7029#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7030static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7031{
7032 struct ocsp_cbk_arg *ocsp_arg;
7033
7034 if (ptr) {
7035 ocsp_arg = ptr;
7036
7037 if (ocsp_arg->is_single) {
7038 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
7039 ocsp_arg->s_ocsp = NULL;
7040 } else {
7041 int i;
7042
7043 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
7044 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
7045 ocsp_arg->m_ocsp[i] = NULL;
7046 }
7047 }
7048 free(ocsp_arg);
7049 }
7050}
7051#endif
7052
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007053static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7054{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007055 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007056}
William Lallemand7d42ef52020-07-06 11:41:30 +02007057
William Lallemandca5cf0a2021-06-09 16:46:12 +02007058#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007059static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7060{
7061 struct ssl_keylog *keylog;
7062
7063 if (!ptr)
7064 return;
7065
7066 keylog = ptr;
7067
7068 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7069 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7070 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7071 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7072 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7073 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7074 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7075 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7076
7077 pool_free(pool_head_ssl_keylog, ptr);
7078}
7079#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007080
Emeric Brun46591952012-05-18 15:47:34 +02007081__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02007082static void __ssl_sock_init(void)
7083{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007084#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007085 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007086 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007087#endif
Emeric Brun46591952012-05-18 15:47:34 +02007088
Willy Tarreauef934602016-12-22 23:12:01 +01007089 if (global_ssl.listen_default_ciphers)
7090 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7091 if (global_ssl.connect_default_ciphers)
7092 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007093#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007094 if (global_ssl.listen_default_ciphersuites)
7095 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7096 if (global_ssl.connect_default_ciphersuites)
7097 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7098#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007099
Willy Tarreau13e14102016-12-22 20:25:26 +01007100 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007101#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007102 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007103#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007104#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007105 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007106 n = sk_SSL_COMP_num(cm);
7107 while (n--) {
7108 (void) sk_SSL_COMP_pop(cm);
7109 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007110#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007111
Willy Tarreau5db847a2019-05-09 14:13:35 +02007112#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007113 ssl_locking_init();
7114#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007115#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007116 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7117#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007118
7119#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7120 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7121#endif
7122
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007123 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007124 ssl_capture_ptr_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_capture_free_func);
William Lallemandca5cf0a2021-06-09 16:46:12 +02007125#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007126 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7127#endif
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007128#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007129 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007130 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007131#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007132#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7133 hap_register_post_check(tlskeys_finalize_config);
7134#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007135
7136 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7137 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7138
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007139 hap_register_post_deinit(ssl_free_global_issuers);
7140
Willy Tarreau80713382018-11-26 10:19:54 +01007141#ifndef OPENSSL_NO_DH
7142 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7143 hap_register_post_deinit(ssl_free_dh);
7144#endif
7145#ifndef OPENSSL_NO_ENGINE
7146 hap_register_post_deinit(ssl_free_engines);
7147#endif
7148 /* Load SSL string for the verbose & debug mode. */
7149 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02007150 ha_meth = BIO_meth_new(0x666, "ha methods");
7151 BIO_meth_set_write(ha_meth, ha_ssl_write);
7152 BIO_meth_set_read(ha_meth, ha_ssl_read);
7153 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7154 BIO_meth_set_create(ha_meth, ha_ssl_new);
7155 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7156 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7157 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007158
7159 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007160
Dragan Dosen9ac98092020-05-11 15:51:45 +02007161 /* Try to register dedicated SSL/TLS protocol message callbacks for
7162 * heartbleed attack (CVE-2014-0160) and clienthello.
7163 */
7164 hap_register_post_check(ssl_sock_register_msg_callbacks);
7165
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007166 /* Try to free all callbacks that were registered by using
7167 * ssl_sock_register_msg_callback().
7168 */
7169 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007170}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007171
Willy Tarreau80713382018-11-26 10:19:54 +01007172/* Compute and register the version string */
7173static void ssl_register_build_options()
7174{
7175 char *ptr = NULL;
7176 int i;
7177
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007178 memprintf(&ptr, "Built with OpenSSL version : "
7179#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007180 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007181#else /* OPENSSL_IS_BORINGSSL */
7182 OPENSSL_VERSION_TEXT
7183 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007184 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007185 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007186#endif
7187 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007188#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007189 "no (library version too old)"
7190#elif defined(OPENSSL_NO_TLSEXT)
7191 "no (disabled via OPENSSL_NO_TLSEXT)"
7192#else
7193 "yes"
7194#endif
7195 "", ptr);
7196
7197 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7198#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7199 "yes"
7200#else
7201#ifdef OPENSSL_NO_TLSEXT
7202 "no (because of OPENSSL_NO_TLSEXT)"
7203#else
7204 "no (version might be too old, 0.9.8f min needed)"
7205#endif
7206#endif
7207 "", ptr);
7208
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007209 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7210 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7211 if (methodVersions[i].option)
7212 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007213
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007214 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007215}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007216
Willy Tarreau80713382018-11-26 10:19:54 +01007217INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007218
Emeric Brun46591952012-05-18 15:47:34 +02007219
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007220#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007221void ssl_free_engines(void) {
7222 struct ssl_engine_list *wl, *wlb;
7223 /* free up engine list */
7224 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7225 ENGINE_finish(wl->e);
7226 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007227 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007228 free(wl);
7229 }
7230}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007231#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007232
Remi Gacogned3a23c32015-05-28 16:39:47 +02007233#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007234void ssl_free_dh(void) {
7235 if (local_dh_1024) {
7236 DH_free(local_dh_1024);
7237 local_dh_1024 = NULL;
7238 }
7239 if (local_dh_2048) {
7240 DH_free(local_dh_2048);
7241 local_dh_2048 = NULL;
7242 }
7243 if (local_dh_4096) {
7244 DH_free(local_dh_4096);
7245 local_dh_4096 = NULL;
7246 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007247 if (global_dh) {
7248 DH_free(global_dh);
7249 global_dh = NULL;
7250 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007251}
7252#endif
7253
7254__attribute__((destructor))
7255static void __ssl_sock_deinit(void)
7256{
7257#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007258 if (ssl_ctx_lru_tree) {
7259 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007260 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007261 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007262#endif
7263
Willy Tarreau5db847a2019-05-09 14:13:35 +02007264#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007265 ERR_remove_state(0);
7266 ERR_free_strings();
7267
7268 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007269#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007270
Willy Tarreau5db847a2019-05-09 14:13:35 +02007271#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007272 CRYPTO_cleanup_all_ex_data();
7273#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007274 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007275}
7276
William Dauchyf6370442020-11-14 19:25:33 +01007277/* Activate ssl on server <s>.
7278 * do nothing if there is no change to apply
7279 *
7280 * Must be called with the server lock held.
7281 */
7282void ssl_sock_set_srv(struct server *s, signed char use_ssl)
7283{
7284 if (s->use_ssl == use_ssl)
7285 return;
7286
7287 s->use_ssl = use_ssl;
7288 if (s->use_ssl == 1)
7289 s->xprt = &ssl_sock;
7290 else
7291 s->xprt = s->check.xprt = s->agent.xprt = xprt_get(XPRT_RAW);
7292}
7293
Emeric Brun46591952012-05-18 15:47:34 +02007294/*
7295 * Local variables:
7296 * c-indent-level: 8
7297 * c-basic-offset: 8
7298 * End:
7299 */