blob: bc827833da3d23b73cd584ed2a79e74865835882 [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 Lallemand722180a2021-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
319/* mimic what X509_STORE_load_locations do with store_ctx */
320static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
321{
Remi Tricot-Le Bretond75b99e2021-05-17 11:45:55 +0200322 X509_STORE *store = NULL;
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +0100323 struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
324 if (ca_e)
325 store = ca_e->ca_store;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200326 if (store_ctx && store) {
327 int i;
328 X509_OBJECT *obj;
329 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
330 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
331 obj = sk_X509_OBJECT_value(objs, i);
332 switch (X509_OBJECT_get_type(obj)) {
333 case X509_LU_X509:
334 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
335 break;
336 case X509_LU_CRL:
337 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
338 break;
339 default:
340 break;
341 }
342 }
343 return 1;
344 }
345 return 0;
346}
347
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500348/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200349static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
350{
351 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
352 return ssl_set_cert_crl_file(store_ctx, path);
353}
354
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200355/*
356 Extract CA_list from CA_file already in tree.
357 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
358 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
359*/
360static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
361{
362 struct ebmb_node *eb;
363 struct cafile_entry *ca_e;
364
365 eb = ebst_lookup(&cafile_tree, path);
366 if (!eb)
367 return NULL;
368 ca_e = ebmb_entry(eb, struct cafile_entry, node);
369
370 if (ca_e->ca_list == NULL) {
371 int i;
372 unsigned long key;
373 struct eb_root ca_name_tree = EB_ROOT;
374 struct eb64_node *node, *back;
375 struct {
376 struct eb64_node node;
377 X509_NAME *xname;
378 } *ca_name;
379 STACK_OF(X509_OBJECT) *objs;
380 STACK_OF(X509_NAME) *skn;
381 X509 *x;
382 X509_NAME *xn;
383
384 skn = sk_X509_NAME_new_null();
385 /* take x509 from cafile_tree */
386 objs = X509_STORE_get0_objects(ca_e->ca_store);
387 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
388 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
389 if (!x)
390 continue;
391 xn = X509_get_subject_name(x);
392 if (!xn)
393 continue;
394 /* Check for duplicates. */
395 key = X509_NAME_hash(xn);
396 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
397 node && ca_name == NULL;
398 node = eb64_next(node)) {
399 ca_name = container_of(node, typeof(*ca_name), node);
400 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
401 ca_name = NULL;
402 }
403 /* find a duplicate */
404 if (ca_name)
405 continue;
406 ca_name = calloc(1, sizeof *ca_name);
407 xn = X509_NAME_dup(xn);
408 if (!ca_name ||
409 !xn ||
410 !sk_X509_NAME_push(skn, xn)) {
411 free(ca_name);
412 X509_NAME_free(xn);
413 sk_X509_NAME_pop_free(skn, X509_NAME_free);
414 sk_X509_NAME_free(skn);
415 skn = NULL;
416 break;
417 }
418 ca_name->node.key = key;
419 ca_name->xname = xn;
420 eb64_insert(&ca_name_tree, &ca_name->node);
421 }
422 ca_e->ca_list = skn;
423 /* remove temporary ca_name tree */
424 node = eb64_first(&ca_name_tree);
425 while (node) {
426 ca_name = container_of(node, typeof(*ca_name), node);
427 back = eb64_next(node);
428 eb64_delete(node);
429 free(ca_name);
430 node = back;
431 }
432 }
433 return ca_e->ca_list;
434}
435
Willy Tarreauff882702021-04-10 17:23:00 +0200436struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200437int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100438int ssl_app_data_index = -1;
Willy Tarreauef934602016-12-22 23:12:01 +0100439
William Lallemand722180a2021-06-09 16:46:12 +0200440#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200441int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200442struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
443struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200444#endif
445
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +0200446int ssl_client_crt_ref_index = -1;
447
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200448#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
449struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
450#endif
451
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200452#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200453unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000454struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
455struct ssl_engine_list {
456 struct list list;
457 ENGINE *e;
458};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200459#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000460
Remi Gacogne8de54152014-07-15 11:36:40 +0200461#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200462static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200463static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200464static DH *local_dh_1024 = NULL;
465static DH *local_dh_2048 = NULL;
466static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100467static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200468#endif /* OPENSSL_NO_DH */
469
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100470#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200471/* X509V3 Extensions that will be added on generated certificates */
472#define X509V3_EXT_SIZE 5
473static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
474 "basicConstraints",
475 "nsComment",
476 "subjectKeyIdentifier",
477 "authorityKeyIdentifier",
478 "keyUsage",
479};
480static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
481 "CA:FALSE",
482 "\"OpenSSL Generated Certificate\"",
483 "hash",
484 "keyid,issuer:always",
485 "nonRepudiation,digitalSignature,keyEncipherment"
486};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200487/* LRU cache to store generated certificate */
488static struct lru64_head *ssl_ctx_lru_tree = NULL;
489static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200490static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100491__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200492
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200493#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
494
yanbzhube2774d2015-12-10 15:07:30 -0500495/* The order here matters for picking a default context,
496 * keep the most common keytype at the bottom of the list
497 */
498const char *SSL_SOCK_KEYTYPE_NAMES[] = {
499 "dsa",
500 "ecdsa",
501 "rsa"
502};
yanbzhube2774d2015-12-10 15:07:30 -0500503
William Lallemandc3cd35f2017-11-28 11:04:43 +0100504static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100505static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
506
Dragan Dosen9ac98092020-05-11 15:51:45 +0200507/* Dedicated callback functions for heartbeat and clienthello.
508 */
509#ifdef TLS1_RT_HEARTBEAT
510static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
511 int content_type, const void *buf, size_t len,
512 SSL *ssl);
513#endif
514static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
515 int content_type, const void *buf, size_t len,
516 SSL *ssl);
517
William Lallemand722180a2021-06-09 16:46:12 +0200518#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200519static void ssl_init_keylog(struct connection *conn, int write_p, int version,
520 int content_type, const void *buf, size_t len,
521 SSL *ssl);
522#endif
523
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200524/* List head of all registered SSL/TLS protocol message callbacks. */
525struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
526
527/* Registers the function <func> in order to be called on SSL/TLS protocol
528 * message processing. It will return 0 if the function <func> is not set
529 * or if it fails to allocate memory.
530 */
531int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
532{
533 struct ssl_sock_msg_callback *cbk;
534
535 if (!func)
536 return 0;
537
538 cbk = calloc(1, sizeof(*cbk));
539 if (!cbk) {
540 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
541 return 0;
542 }
543
544 cbk->func = func;
545
Willy Tarreau2b718102021-04-21 07:32:39 +0200546 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200547
548 return 1;
549}
550
Dragan Dosen9ac98092020-05-11 15:51:45 +0200551/* Used to register dedicated SSL/TLS protocol message callbacks.
552 */
553static int ssl_sock_register_msg_callbacks(void)
554{
555#ifdef TLS1_RT_HEARTBEAT
556 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
557 return ERR_ABORT;
558#endif
559 if (global_ssl.capture_cipherlist > 0) {
560 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
561 return ERR_ABORT;
562 }
William Lallemand722180a2021-06-09 16:46:12 +0200563#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200564 if (global_ssl.keylog > 0) {
565 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
566 return ERR_ABORT;
567 }
568#endif
569
Christopher Fauletfc633b62020-11-06 15:24:23 +0100570 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200571}
572
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200573/* Used to free all SSL/TLS protocol message callbacks that were
574 * registered by using ssl_sock_register_msg_callback().
575 */
576static void ssl_sock_unregister_msg_callbacks(void)
577{
578 struct ssl_sock_msg_callback *cbk, *cbkback;
579
580 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200581 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200582 free(cbk);
583 }
584}
585
Dragan Doseneb607fe2020-05-11 17:17:06 +0200586SSL *ssl_sock_get_ssl_object(struct connection *conn)
587{
588 if (!ssl_sock_is_ssl(conn))
589 return NULL;
590
591 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
592}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100593/*
594 * This function gives the detail of the SSL error. It is used only
595 * if the debug mode and the verbose mode are activated. It dump all
596 * the SSL error until the stack was empty.
597 */
598static forceinline void ssl_sock_dump_errors(struct connection *conn)
599{
600 unsigned long ret;
601
602 if (unlikely(global.mode & MODE_DEBUG)) {
603 while(1) {
604 ret = ERR_get_error();
605 if (ret == 0)
606 return;
Willy Tarreau566cebc2021-03-02 19:32:39 +0100607 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
608 conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100609 ERR_func_error_string(ret), ERR_reason_error_string(ret));
610 }
611 }
612}
613
yanbzhube2774d2015-12-10 15:07:30 -0500614
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200615#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200616int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000617{
618 int err_code = ERR_ABORT;
619 ENGINE *engine;
620 struct ssl_engine_list *el;
621
622 /* grab the structural reference to the engine */
623 engine = ENGINE_by_id(engine_id);
624 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100625 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000626 goto fail_get;
627 }
628
629 if (!ENGINE_init(engine)) {
630 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100631 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000632 goto fail_init;
633 }
634
635 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100636 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000637 goto fail_set_method;
638 }
639
640 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200641 if (!el)
642 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000643 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200644 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100645 nb_engines++;
646 if (global_ssl.async)
647 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000648 return 0;
649
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200650fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000651fail_set_method:
652 /* release the functional reference from ENGINE_init() */
653 ENGINE_finish(engine);
654
655fail_init:
656 /* release the structural reference from ENGINE_by_id() */
657 ENGINE_free(engine);
658
659fail_get:
660 return err_code;
661}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200662#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000663
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500664#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200665/*
666 * openssl async fd handler
667 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200668void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000669{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200670 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000671
Emeric Brun3854e012017-05-17 20:42:48 +0200672 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000673 * to poll this fd until it is requested
674 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000675 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000676 fd_cant_recv(fd);
677
678 /* crypto engine is available, let's notify the associated
679 * connection that it can pursue its processing.
680 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200681 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000682}
683
Emeric Brun3854e012017-05-17 20:42:48 +0200684/*
685 * openssl async delayed SSL_free handler
686 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200687void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000688{
689 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200690 OSSL_ASYNC_FD all_fd[32];
691 size_t num_all_fds = 0;
692 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000693
Emeric Brun3854e012017-05-17 20:42:48 +0200694 /* We suppose that the async job for a same SSL *
695 * are serialized. So if we are awake it is
696 * because the running job has just finished
697 * and we can remove all async fds safely
698 */
699 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
700 if (num_all_fds > 32) {
701 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
702 return;
703 }
704
705 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
706 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200707 fd_stop_both(all_fd[i]);
Emeric Brun3854e012017-05-17 20:42:48 +0200708
709 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000710 SSL_free(ssl);
Willy Tarreau4781b152021-04-06 13:53:36 +0200711 _HA_ATOMIC_DEC(&sslconns);
712 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000713}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000714/*
Emeric Brun3854e012017-05-17 20:42:48 +0200715 * function used to manage a returned SSL_ERROR_WANT_ASYNC
716 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000717 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200718static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000719{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100720 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200721 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200722 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000723 size_t num_add_fds = 0;
724 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200725 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000726
727 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
728 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200729 if (num_add_fds > 32 || num_del_fds > 32) {
730 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 +0000731 return;
732 }
733
Emeric Brun3854e012017-05-17 20:42:48 +0200734 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000735
Emeric Brun3854e012017-05-17 20:42:48 +0200736 /* We remove unused fds from the fdtab */
737 for (i=0 ; i < num_del_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200738 fd_stop_both(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000739
Emeric Brun3854e012017-05-17 20:42:48 +0200740 /* We add new fds to the fdtab */
741 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200742 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000743 }
744
Emeric Brun3854e012017-05-17 20:42:48 +0200745 num_add_fds = 0;
746 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
747 if (num_add_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;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000750 }
Emeric Brun3854e012017-05-17 20:42:48 +0200751
752 /* We activate the polling for all known async fds */
753 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000754 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200755 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000756 /* To ensure that the fd cache won't be used
757 * We'll prefer to catch a real RD event
758 * because handling an EAGAIN on this fd will
759 * result in a context switch and also
760 * some engines uses a fd in blocking mode.
761 */
762 fd_cant_recv(add_fd[i]);
763 }
Emeric Brun3854e012017-05-17 20:42:48 +0200764
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000765}
766#endif
767
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200768#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP && !defined HAVE_ASN1_TIME_TO_TM)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200769/*
770 * This function returns the number of seconds elapsed
771 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
772 * date presented un ASN1_GENERALIZEDTIME.
773 *
774 * In parsing error case, it returns -1.
775 */
776static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
777{
778 long epoch;
779 char *p, *end;
780 const unsigned short month_offset[12] = {
781 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
782 };
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +0200783 unsigned long year, month;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200784
785 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
786
787 p = (char *)d->data;
788 end = p + d->length;
789
790 if (end - p < 4) return -1;
791 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
792 p += 4;
793 if (end - p < 2) return -1;
794 month = 10 * (p[0] - '0') + p[1] - '0';
795 if (month < 1 || month > 12) return -1;
796 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
797 We consider leap years and the current month (<marsh or not) */
798 epoch = ( ((year - 1970) * 365)
799 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
800 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
801 + month_offset[month-1]
802 ) * 24 * 60 * 60;
803 p += 2;
804 if (end - p < 2) return -1;
805 /* Add the number of seconds of completed days of current month */
806 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
807 p += 2;
808 if (end - p < 2) return -1;
809 /* Add the completed hours of the current day */
810 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
811 p += 2;
812 if (end - p < 2) return -1;
813 /* Add the completed minutes of the current hour */
814 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
815 p += 2;
816 if (p == end) return -1;
817 /* Test if there is available seconds */
818 if (p[0] < '0' || p[0] > '9')
819 goto nosec;
820 if (end - p < 2) return -1;
821 /* Add the seconds of the current minute */
822 epoch += 10 * (p[0] - '0') + p[1] - '0';
823 p += 2;
824 if (p == end) return -1;
825 /* Ignore seconds float part if present */
826 if (p[0] == '.') {
827 do {
828 if (++p == end) return -1;
829 } while (p[0] >= '0' && p[0] <= '9');
830 }
831
832nosec:
833 if (p[0] == 'Z') {
834 if (end - p != 1) return -1;
835 return epoch;
836 }
837 else if (p[0] == '+') {
838 if (end - p != 5) return -1;
839 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700840 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 +0200841 }
842 else if (p[0] == '-') {
843 if (end - p != 5) return -1;
844 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700845 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 +0200846 }
847
848 return -1;
849}
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200850#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200851
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200852#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
William Lallemand104a7a62019-10-14 14:14:59 +0200853/*
854 * struct alignment works here such that the key.key is the same as key_data
855 * Do not change the placement of key_data
856 */
857struct certificate_ocsp {
858 struct ebmb_node key;
859 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
Remi Tricot-Le Breton5aa1dce2021-06-10 13:51:12 +0200860 unsigned int key_length;
William Lallemand104a7a62019-10-14 14:14:59 +0200861 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200862 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200863 long expire;
864};
865
866struct ocsp_cbk_arg {
867 int is_single;
868 int single_kt;
869 union {
870 struct certificate_ocsp *s_ocsp;
871 /*
872 * m_ocsp will have multiple entries dependent on key type
873 * Entry 0 - DSA
874 * Entry 1 - ECDSA
875 * Entry 2 - RSA
876 */
877 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
878 };
879};
880
Emeric Brun1d3865b2014-06-20 15:37:32 +0200881static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200882
883/* This function starts to check if the OCSP response (in DER format) contained
884 * in chunk 'ocsp_response' is valid (else exits on error).
885 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
886 * contained in the OCSP Response and exits on error if no match.
887 * If it's a valid OCSP Response:
888 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
889 * pointed by 'ocsp'.
890 * If 'ocsp' is NULL, the function looks up into the OCSP response's
891 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
892 * from the response) and exits on error if not found. Finally, If an OCSP response is
893 * already present in the container, it will be overwritten.
894 *
895 * Note: OCSP response containing more than one OCSP Single response is not
896 * considered valid.
897 *
898 * Returns 0 on success, 1 in error case.
899 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200900static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
901 struct certificate_ocsp *ocsp,
902 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200903{
904 OCSP_RESPONSE *resp;
905 OCSP_BASICRESP *bs = NULL;
906 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200907 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200908 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200909 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200910 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200911 int reason;
912 int ret = 1;
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200913#ifdef HAVE_ASN1_TIME_TO_TM
914 struct tm nextupd_tm = {0};
915#endif
Emeric Brun4147b2e2014-06-16 18:36:30 +0200916
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200917 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
918 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200919 if (!resp) {
920 memprintf(err, "Unable to parse OCSP response");
921 goto out;
922 }
923
924 rc = OCSP_response_status(resp);
925 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
926 memprintf(err, "OCSP response status not successful");
927 goto out;
928 }
929
930 bs = OCSP_response_get1_basic(resp);
931 if (!bs) {
932 memprintf(err, "Failed to get basic response from OCSP Response");
933 goto out;
934 }
935
936 count_sr = OCSP_resp_count(bs);
937 if (count_sr > 1) {
938 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
939 goto out;
940 }
941
942 sr = OCSP_resp_get0(bs, 0);
943 if (!sr) {
944 memprintf(err, "Failed to get OCSP single response");
945 goto out;
946 }
947
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200948 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
949
Emeric Brun4147b2e2014-06-16 18:36:30 +0200950 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200951 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200952 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200953 goto out;
954 }
955
Emeric Brun13a6b482014-06-20 15:44:34 +0200956 if (!nextupd) {
957 memprintf(err, "OCSP single response: missing nextupdate");
958 goto out;
959 }
960
Emeric Brunc8b27b62014-06-19 14:16:17 +0200961 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200962 if (!rc) {
963 memprintf(err, "OCSP single response: no longer valid.");
964 goto out;
965 }
966
967 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200968 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +0200969 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
970 goto out;
971 }
972 }
973
974 if (!ocsp) {
975 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
976 unsigned char *p;
977
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200978 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200979 if (!rc) {
980 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
981 goto out;
982 }
983
984 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
985 memprintf(err, "OCSP single response: Certificate ID too long");
986 goto out;
987 }
988
989 p = key;
990 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200991 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200992 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
993 if (!ocsp) {
994 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
995 goto out;
996 }
997 }
998
999 /* According to comments on "chunk_dup", the
1000 previous chunk buffer will be freed */
1001 if (!chunk_dup(&ocsp->response, ocsp_response)) {
1002 memprintf(err, "OCSP response: Memory allocation error");
1003 goto out;
1004 }
1005
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001006#ifdef HAVE_ASN1_TIME_TO_TM
1007 if (ASN1_TIME_to_tm(nextupd, &nextupd_tm) == 0) {
1008 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1009 goto out;
1010 }
1011 ocsp->expire = my_timegm(&nextupd_tm) - OCSP_MAX_RESPONSE_TIME_SKEW;
1012#else
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001013 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +02001014 if (ocsp->expire < 0) {
1015 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1016 goto out;
1017 }
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001018#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001019
Emeric Brun4147b2e2014-06-16 18:36:30 +02001020 ret = 0;
1021out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001022 ERR_clear_error();
1023
Emeric Brun4147b2e2014-06-16 18:36:30 +02001024 if (bs)
1025 OCSP_BASICRESP_free(bs);
1026
1027 if (resp)
1028 OCSP_RESPONSE_free(resp);
1029
1030 return ret;
1031}
1032/*
1033 * External function use to update the OCSP response in the OCSP response's
1034 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1035 * to update in DER format.
1036 *
1037 * Returns 0 on success, 1 in error case.
1038 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001039int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001040{
1041 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1042}
1043
William Lallemand4a660132019-10-14 14:51:41 +02001044#endif
1045
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001046#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1047static 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)
1048{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001049 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001050 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001051 struct connection *conn;
1052 int head;
1053 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001054 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001055
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001056 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001057 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001058 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1059
1060 keys = ref->tlskeys;
1061 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001062
1063 if (enc) {
1064 memcpy(key_name, keys[head].name, 16);
1065
1066 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001067 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001068
Emeric Brun9e754772019-01-10 17:51:55 +01001069 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001070
Emeric Brun9e754772019-01-10 17:51:55 +01001071 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1072 goto end;
1073
Willy Tarreau9356dac2019-05-10 09:22:53 +02001074 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001075 ret = 1;
1076 }
1077 else if (ref->key_size_bits == 256 ) {
1078
1079 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1080 goto end;
1081
Willy Tarreau9356dac2019-05-10 09:22:53 +02001082 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001083 ret = 1;
1084 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001085 } else {
1086 for (i = 0; i < TLS_TICKETS_NO; i++) {
1087 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1088 goto found;
1089 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001090 ret = 0;
1091 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001092
Christopher Faulet16f45c82018-02-16 11:23:49 +01001093 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001094 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001095 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 +01001096 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1097 goto end;
1098 /* 2 for key renewal, 1 if current key is still valid */
1099 ret = i ? 2 : 1;
1100 }
1101 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001102 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 +01001103 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1104 goto end;
1105 /* 2 for key renewal, 1 if current key is still valid */
1106 ret = i ? 2 : 1;
1107 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001108 }
Emeric Brun9e754772019-01-10 17:51:55 +01001109
Christopher Faulet16f45c82018-02-16 11:23:49 +01001110 end:
1111 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1112 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001113}
1114
1115struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1116{
1117 struct tls_keys_ref *ref;
1118
1119 list_for_each_entry(ref, &tlskeys_reference, list)
1120 if (ref->filename && strcmp(filename, ref->filename) == 0)
1121 return ref;
1122 return NULL;
1123}
1124
1125struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1126{
1127 struct tls_keys_ref *ref;
1128
1129 list_for_each_entry(ref, &tlskeys_reference, list)
1130 if (ref->unique_id == unique_id)
1131 return ref;
1132 return NULL;
1133}
1134
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001135/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001136 * match existing ones, this function returns -1
1137 * else it returns 0 on success.
1138 */
1139int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001140 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001141{
Emeric Brun9e754772019-01-10 17:51:55 +01001142 if (ref->key_size_bits == 128) {
1143 if (tlskey->data != sizeof(struct tls_sess_key_128))
1144 return -1;
1145 }
1146 else if (ref->key_size_bits == 256) {
1147 if (tlskey->data != sizeof(struct tls_sess_key_256))
1148 return -1;
1149 }
1150 else
1151 return -1;
1152
Christopher Faulet16f45c82018-02-16 11:23:49 +01001153 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001154 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1155 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001156 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1157 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001158
1159 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001160}
1161
Willy Tarreau83061a82018-07-13 11:56:34 +02001162int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001163{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001164 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1165
1166 if(!ref) {
1167 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1168 return 1;
1169 }
Emeric Brun9e754772019-01-10 17:51:55 +01001170 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1171 memprintf(err, "Invalid key size");
1172 return 1;
1173 }
1174
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001175 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001176}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001177
1178/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001179 * automatic ids. It's called just after the basic checks. It returns
1180 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001181 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001182static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001183{
1184 int i = 0;
1185 struct tls_keys_ref *ref, *ref2, *ref3;
1186 struct list tkr = LIST_HEAD_INIT(tkr);
1187
1188 list_for_each_entry(ref, &tlskeys_reference, list) {
1189 if (ref->unique_id == -1) {
1190 /* Look for the first free id. */
1191 while (1) {
1192 list_for_each_entry(ref2, &tlskeys_reference, list) {
1193 if (ref2->unique_id == i) {
1194 i++;
1195 break;
1196 }
1197 }
1198 if (&ref2->list == &tlskeys_reference)
1199 break;
1200 }
1201
1202 /* Uses the unique id and increment it for the next entry. */
1203 ref->unique_id = i;
1204 i++;
1205 }
1206 }
1207
1208 /* This sort the reference list by id. */
1209 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001210 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001211 list_for_each_entry(ref3, &tkr, list) {
1212 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001213 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001214 break;
1215 }
1216 }
1217 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001218 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001219 }
1220
1221 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001222 LIST_INSERT(&tkr, &tlskeys_reference);
1223 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001224 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001225}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001226#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1227
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001228#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001229int ocsp_ex_index = -1;
1230
yanbzhube2774d2015-12-10 15:07:30 -05001231int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1232{
1233 switch (evp_keytype) {
1234 case EVP_PKEY_RSA:
1235 return 2;
1236 case EVP_PKEY_DSA:
1237 return 0;
1238 case EVP_PKEY_EC:
1239 return 1;
1240 }
1241
1242 return -1;
1243}
1244
Emeric Brun4147b2e2014-06-16 18:36:30 +02001245/*
1246 * Callback used to set OCSP status extension content in server hello.
1247 */
1248int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1249{
yanbzhube2774d2015-12-10 15:07:30 -05001250 struct certificate_ocsp *ocsp;
1251 struct ocsp_cbk_arg *ocsp_arg;
1252 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001253 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001254 EVP_PKEY *ssl_pkey;
1255 int key_type;
1256 int index;
1257
William Lallemand76b4a122020-08-04 17:41:39 +02001258 ctx = SSL_get_SSL_CTX(ssl);
1259 if (!ctx)
1260 return SSL_TLSEXT_ERR_NOACK;
1261
1262 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1263 if (!ocsp_arg)
1264 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001265
1266 ssl_pkey = SSL_get_privatekey(ssl);
1267 if (!ssl_pkey)
1268 return SSL_TLSEXT_ERR_NOACK;
1269
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001270 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001271
1272 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1273 ocsp = ocsp_arg->s_ocsp;
1274 else {
1275 /* For multiple certs per context, we have to find the correct OCSP response based on
1276 * the certificate type
1277 */
1278 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1279
1280 if (index < 0)
1281 return SSL_TLSEXT_ERR_NOACK;
1282
1283 ocsp = ocsp_arg->m_ocsp[index];
1284
1285 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001286
1287 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001288 !ocsp->response.area ||
1289 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001290 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001291 return SSL_TLSEXT_ERR_NOACK;
1292
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001293 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001294 if (!ssl_buf)
1295 return SSL_TLSEXT_ERR_NOACK;
1296
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001297 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1298 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001299
1300 return SSL_TLSEXT_ERR_OK;
1301}
1302
William Lallemand4a660132019-10-14 14:51:41 +02001303#endif
1304
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001305#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001306
1307
1308/*
1309 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1310 * used anymore. Also removes it from the tree if free'd.
1311 */
1312static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1313{
1314 if (!ocsp)
1315 return;
1316
1317 ocsp->refcount--;
1318 if (ocsp->refcount <= 0) {
1319 ebmb_delete(&ocsp->key);
1320 chunk_destroy(&ocsp->response);
1321 free(ocsp);
1322 }
1323}
1324
1325
Emeric Brun4147b2e2014-06-16 18:36:30 +02001326/*
1327 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001328 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1329 * status extension, the issuer's certificate is mandatory. It should be
1330 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001331 *
William Lallemand246c0242019-10-11 08:59:13 +02001332 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1333 * OCSP response. If file is empty or content is not a valid OCSP response,
1334 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1335 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001336 *
1337 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001338 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001339 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001340static 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 +02001341{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001342 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001343 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001344 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001345 struct certificate_ocsp *ocsp = NULL, *iocsp;
1346 char *warn = NULL;
1347 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001348 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001349
Emeric Brun4147b2e2014-06-16 18:36:30 +02001350
William Lallemand246c0242019-10-11 08:59:13 +02001351 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001352 if (!x)
1353 goto out;
1354
William Lallemand246c0242019-10-11 08:59:13 +02001355 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001356 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1357 if (chain) {
1358 /* check if one of the certificate of the chain is the issuer */
1359 for (i = 0; i < sk_X509_num(chain); i++) {
1360 X509 *ti = sk_X509_value(chain, i);
1361 if (X509_check_issued(ti, x) == X509_V_OK) {
1362 issuer = ti;
1363 break;
1364 }
1365 }
1366 }
William Lallemand246c0242019-10-11 08:59:13 +02001367 if (!issuer)
1368 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001369
1370 cid = OCSP_cert_to_id(0, x, issuer);
1371 if (!cid)
1372 goto out;
1373
1374 i = i2d_OCSP_CERTID(cid, NULL);
1375 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1376 goto out;
1377
Vincent Bernat02779b62016-04-03 13:48:43 +02001378 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001379 if (!ocsp)
1380 goto out;
1381
1382 p = ocsp->key_data;
Remi Tricot-Le Breton5aa1dce2021-06-10 13:51:12 +02001383 ocsp->key_length = i2d_OCSP_CERTID(cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001384
1385 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1386 if (iocsp == ocsp)
1387 ocsp = NULL;
1388
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001389#ifndef SSL_CTX_get_tlsext_status_cb
1390# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1391 *cb = (void (*) (void))ctx->tlsext_status_cb;
1392#endif
1393 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1394
1395 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001396 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001397 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001398
William Lallemanda560c062020-07-31 11:43:20 +02001399 cb_arg = calloc(1, sizeof(*cb_arg));
1400 if (!cb_arg)
1401 goto out;
1402
yanbzhube2774d2015-12-10 15:07:30 -05001403 cb_arg->is_single = 1;
1404 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001405 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001406
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001407 pkey = X509_get_pubkey(x);
1408 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1409 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001410
1411 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001412 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 */
1413
yanbzhube2774d2015-12-10 15:07:30 -05001414 } else {
1415 /*
1416 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1417 * Update that cb_arg with the new cert's staple
1418 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001419 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001420 struct certificate_ocsp *tmp_ocsp;
1421 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001422 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001423 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001424
William Lallemand76b4a122020-08-04 17:41:39 +02001425 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001426
1427 /*
1428 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1429 * the order of operations below matter, take care when changing it
1430 */
1431 tmp_ocsp = cb_arg->s_ocsp;
1432 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1433 cb_arg->s_ocsp = NULL;
1434 cb_arg->m_ocsp[index] = tmp_ocsp;
1435 cb_arg->is_single = 0;
1436 cb_arg->single_kt = 0;
1437
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001438 pkey = X509_get_pubkey(x);
1439 key_type = EVP_PKEY_base_id(pkey);
1440 EVP_PKEY_free(pkey);
1441
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001442 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001443 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001444 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001445 iocsp->refcount++;
1446 }
yanbzhube2774d2015-12-10 15:07:30 -05001447 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001448
1449 ret = 0;
1450
1451 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001452 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001453 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001454 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001455 }
1456
1457out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001458 if (cid)
1459 OCSP_CERTID_free(cid);
1460
1461 if (ocsp)
1462 free(ocsp);
1463
1464 if (warn)
1465 free(warn);
1466
Emeric Brun4147b2e2014-06-16 18:36:30 +02001467 return ret;
1468}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001469#endif
1470
1471#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001472static 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 +02001473{
William Lallemand4a660132019-10-14 14:51:41 +02001474 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 +02001475}
1476#endif
1477
William Lallemand4a660132019-10-14 14:51:41 +02001478
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001479#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001480
1481#define CT_EXTENSION_TYPE 18
1482
William Lallemand03c331c2020-05-13 10:10:01 +02001483int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001484
1485int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1486{
Willy Tarreau83061a82018-07-13 11:56:34 +02001487 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001488
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001489 *out = (unsigned char *) sctl->area;
1490 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001491
1492 return 1;
1493}
1494
1495int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1496{
1497 return 1;
1498}
1499
William Lallemanda17f4112019-10-10 15:16:44 +02001500static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001501{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001502 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001503
William Lallemanda17f4112019-10-10 15:16:44 +02001504 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 +01001505 goto out;
1506
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001507 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1508
1509 ret = 0;
1510
1511out:
1512 return ret;
1513}
1514
1515#endif
1516
Emeric Brune1f38db2012-09-03 20:36:47 +02001517void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1518{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001519 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001520 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001521 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001522 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001523
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001524#ifndef SSL_OP_NO_RENEGOTIATION
1525 /* Please note that BoringSSL defines this macro to zero so don't
1526 * change this to #if and do not assign a default value to this macro!
1527 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001528 if (where & SSL_CB_HANDSHAKE_START) {
1529 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001530 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 +02001531 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001532 conn->err_code = CO_ER_SSL_RENEG;
1533 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001534 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001535#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001536
1537 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001538 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001539 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001540 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001541 consider that the buffering was activated,
1542 so we rise the output buffer size from 4k
1543 to 16k */
1544 write_bio = SSL_get_wbio(ssl);
1545 if (write_bio != SSL_get_rbio(ssl)) {
1546 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001547 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001548 }
1549 }
1550 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001551}
1552
Emeric Brune64aef12012-09-21 13:15:06 +02001553/* Callback is called for each certificate of the chain during a verify
1554 ok is set to 1 if preverify detect no error on current certificate.
1555 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001556int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001557{
1558 SSL *ssl;
1559 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001560 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001561 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001562 X509 *client_crt;
1563 STACK_OF(X509) *certs;
Emeric Brune64aef12012-09-21 13:15:06 +02001564
1565 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001566 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001567 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001568
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001569 ctx = conn->xprt_ctx;
1570
1571 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001572
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001573 depth = X509_STORE_CTX_get_error_depth(x_store);
1574 err = X509_STORE_CTX_get_error(x_store);
1575
Emeric Brun81c00f02012-09-21 14:31:21 +02001576 if (ok) /* no errors */
1577 return ok;
1578
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001579 /* Keep a reference to the client's certificate in order to be able to
1580 * dump some fetches values in a log even when the verification process
1581 * fails. */
1582 if (depth == 0) {
1583 X509_free(client_crt);
1584 client_crt = X509_STORE_CTX_get0_cert(x_store);
1585 if (client_crt) {
1586 X509_up_ref(client_crt);
1587 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1588 }
1589 }
1590 else {
1591 /* An error occurred on a CA certificate of the certificate
1592 * chain, we might never call this verify callback on the client
1593 * certificate's depth (which is 0) so we try to store the
1594 * reference right now. */
1595 if (X509_STORE_CTX_get0_chain(x_store) != NULL) {
1596 certs = X509_STORE_CTX_get1_chain(x_store);
1597 if (certs) {
1598 client_crt = sk_X509_value(certs, 0);
1599 if (client_crt) {
1600 X509_up_ref(client_crt);
1601 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1602 }
1603 }
1604 sk_X509_pop_free(certs, X509_free);
1605 }
1606 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001607
1608 /* check if CA error needs to be ignored */
1609 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001610 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1611 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1612 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001613 }
1614
Willy Tarreau731248f2020-02-04 14:02:02 +01001615 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001616 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001617 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001618 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001619 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001620
Willy Tarreau20879a02012-12-03 16:32:10 +01001621 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001622 return 0;
1623 }
1624
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001625 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1626 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001627
Emeric Brun81c00f02012-09-21 14:31:21 +02001628 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001629 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001630 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001631 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001632 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001633 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001634
Willy Tarreau20879a02012-12-03 16:32:10 +01001635 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001636 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001637}
1638
Dragan Dosen9ac98092020-05-11 15:51:45 +02001639#ifdef TLS1_RT_HEARTBEAT
1640static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1641 int content_type, const void *buf, size_t len,
1642 SSL *ssl)
1643{
1644 /* test heartbeat received (write_p is set to 0
1645 for a received record) */
1646 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1647 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1648 const unsigned char *p = buf;
1649 unsigned int payload;
1650
1651 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1652
1653 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1654 if (*p != TLS1_HB_REQUEST)
1655 return;
1656
1657 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1658 goto kill_it;
1659
1660 payload = (p[1] * 256) + p[2];
1661 if (3 + payload + 16 <= len)
1662 return; /* OK no problem */
1663 kill_it:
1664 /* We have a clear heartbleed attack (CVE-2014-0160), the
1665 * advertised payload is larger than the advertised packet
1666 * length, so we have garbage in the buffer between the
1667 * payload and the end of the buffer (p+len). We can't know
1668 * if the SSL stack is patched, and we don't know if we can
1669 * safely wipe out the area between p+3+len and payload.
1670 * So instead, we prevent the response from being sent by
1671 * setting the max_send_fragment to 0 and we report an SSL
1672 * error, which will kill this connection. It will be reported
1673 * above as SSL_ERROR_SSL while an other handshake failure with
1674 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1675 */
1676 ssl->max_send_fragment = 0;
1677 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1678 }
1679}
1680#endif
1681
1682static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1683 int content_type, const void *buf, size_t len,
1684 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001685{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001686 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001687 unsigned char *msg;
1688 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001689 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001690
1691 /* This function is called for "from client" and "to server"
1692 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001693 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001694 */
1695
1696 /* "write_p" is set to 0 is the bytes are received messages,
1697 * otherwise it is set to 1.
1698 */
1699 if (write_p != 0)
1700 return;
1701
1702 /* content_type contains the type of message received or sent
1703 * according with the SSL/TLS protocol spec. This message is
1704 * encoded with one byte. The value 256 (two bytes) is used
1705 * for designing the SSL/TLS record layer. According with the
1706 * rfc6101, the expected message (other than 256) are:
1707 * - change_cipher_spec(20)
1708 * - alert(21)
1709 * - handshake(22)
1710 * - application_data(23)
1711 * - (255)
1712 * We are interessed by the handshake and specially the client
1713 * hello.
1714 */
1715 if (content_type != 22)
1716 return;
1717
1718 /* The message length is at least 4 bytes, containing the
1719 * message type and the message length.
1720 */
1721 if (len < 4)
1722 return;
1723
1724 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001725 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001726 * - hello_request(0)
1727 * - client_hello(1)
1728 * - server_hello(2)
1729 * - certificate(11)
1730 * - server_key_exchange (12)
1731 * - certificate_request(13)
1732 * - server_hello_done(14)
1733 * We are interested by the client hello.
1734 */
1735 msg = (unsigned char *)buf;
1736 if (msg[0] != 1)
1737 return;
1738
1739 /* Next three bytes are the length of the message. The total length
1740 * must be this decoded length + 4. If the length given as argument
1741 * is not the same, we abort the protocol dissector.
1742 */
1743 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1744 if (len < rec_len + 4)
1745 return;
1746 msg += 4;
1747 end = msg + rec_len;
1748 if (end < msg)
1749 return;
1750
1751 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1752 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001753 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1754 */
1755 msg += 1 + 1 + 4 + 28;
1756 if (msg > end)
1757 return;
1758
1759 /* Next, is session id:
1760 * if present, we have to jump by length + 1 for the size information
1761 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001762 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001763 if (msg[0] > 0)
1764 msg += msg[0];
1765 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001766 if (msg > end)
1767 return;
1768
1769 /* Next two bytes are the ciphersuite length. */
1770 if (msg + 2 > end)
1771 return;
1772 rec_len = (msg[0] << 8) + msg[1];
1773 msg += 2;
1774 if (msg + rec_len > end || msg + rec_len < msg)
1775 return;
1776
Willy Tarreaub454e902021-03-22 15:09:41 +01001777 capture = pool_alloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001778 if (!capture)
1779 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001780 /* Compute the xxh64 of the ciphersuite. */
1781 capture->xxh64 = XXH64(msg, rec_len, 0);
1782
1783 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001784 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1785 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001786 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001787
1788 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001789}
William Lallemand7d42ef52020-07-06 11:41:30 +02001790
1791
William Lallemand722180a2021-06-09 16:46:12 +02001792#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001793static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1794 int content_type, const void *buf, size_t len,
1795 SSL *ssl)
1796{
1797 struct ssl_keylog *keylog;
1798
1799 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1800 return;
1801
Willy Tarreauf208ac02021-03-22 21:10:12 +01001802 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001803 if (!keylog)
1804 return;
1805
William Lallemand7d42ef52020-07-06 11:41:30 +02001806 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1807 pool_free(pool_head_ssl_keylog, keylog);
1808 return;
1809 }
1810}
1811#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001812
Emeric Brun29f037d2014-04-25 19:05:36 +02001813/* Callback is called for ssl protocol analyse */
1814void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1815{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001816 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1817 struct ssl_sock_msg_callback *cbk;
1818
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001819 /* Try to call all callback functions that were registered by using
1820 * ssl_sock_register_msg_callback().
1821 */
1822 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1823 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1824 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001825}
1826
Bernard Spil13c53f82018-02-15 13:34:58 +01001827#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001828static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1829 const unsigned char *in, unsigned int inlen,
1830 void *arg)
1831{
1832 struct server *srv = arg;
1833
1834 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1835 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1836 return SSL_TLSEXT_ERR_OK;
1837 return SSL_TLSEXT_ERR_NOACK;
1838}
1839#endif
1840
1841#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001842/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001843 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001844 */
1845static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1846 unsigned int *len, void *arg)
1847{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001848 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001849
1850 *data = (const unsigned char *)conf->npn_str;
1851 *len = conf->npn_len;
1852 return SSL_TLSEXT_ERR_OK;
1853}
1854#endif
1855
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001856#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001857/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001858 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001859 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001860static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1861 unsigned char *outlen,
1862 const unsigned char *server,
1863 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001864{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001865 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001866
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001867 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1868 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1869 return SSL_TLSEXT_ERR_NOACK;
1870 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001871 return SSL_TLSEXT_ERR_OK;
1872}
1873#endif
1874
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001875#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001876#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001877
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001878/* Configure a DNS SAN extenion on a certificate. */
1879int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1880 int failure = 0;
1881 X509_EXTENSION *san_ext = NULL;
1882 CONF *conf = NULL;
1883 struct buffer *san_name = get_trash_chunk();
1884
1885 conf = NCONF_new(NULL);
1886 if (!conf) {
1887 failure = 1;
1888 goto cleanup;
1889 }
1890
1891 /* Build an extension based on the DNS entry above */
1892 chunk_appendf(san_name, "DNS:%s", servername);
1893 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1894 if (!san_ext) {
1895 failure = 1;
1896 goto cleanup;
1897 }
1898
1899 /* Add the extension */
1900 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1901 failure = 1;
1902 goto cleanup;
1903 }
1904
1905 /* Success */
1906 failure = 0;
1907
1908cleanup:
1909 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1910 if (NULL != conf) NCONF_free(conf);
1911
1912 return failure;
1913}
1914
Christopher Faulet30548802015-06-11 13:39:32 +02001915/* Create a X509 certificate with the specified servername and serial. This
1916 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001917static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001918ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001919{
Shimi Gersner5846c492020-08-23 13:58:12 +03001920 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1921 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001922 SSL_CTX *ssl_ctx = NULL;
1923 X509 *newcrt = NULL;
1924 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001925 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001926 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001927 X509_NAME *name;
1928 const EVP_MD *digest;
1929 X509V3_CTX ctx;
1930 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001931 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001932
Christopher Faulet48a83322017-07-28 16:56:09 +02001933 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001934#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001935 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1936#else
1937 tmp_ssl = SSL_new(bind_conf->default_ctx);
1938 if (tmp_ssl)
1939 pkey = SSL_get_privatekey(tmp_ssl);
1940#endif
1941 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001942 goto mkcert_error;
1943
1944 /* Create the certificate */
1945 if (!(newcrt = X509_new()))
1946 goto mkcert_error;
1947
1948 /* Set version number for the certificate (X509v3) and the serial
1949 * number */
1950 if (X509_set_version(newcrt, 2L) != 1)
1951 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001952 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001953
1954 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001955 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1956 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001957 goto mkcert_error;
1958
1959 /* set public key in the certificate */
1960 if (X509_set_pubkey(newcrt, pkey) != 1)
1961 goto mkcert_error;
1962
1963 /* Set issuer name from the CA */
1964 if (!(name = X509_get_subject_name(cacert)))
1965 goto mkcert_error;
1966 if (X509_set_issuer_name(newcrt, name) != 1)
1967 goto mkcert_error;
1968
1969 /* Set the subject name using the same, but the CN */
1970 name = X509_NAME_dup(name);
1971 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1972 (const unsigned char *)servername,
1973 -1, -1, 0) != 1) {
1974 X509_NAME_free(name);
1975 goto mkcert_error;
1976 }
1977 if (X509_set_subject_name(newcrt, name) != 1) {
1978 X509_NAME_free(name);
1979 goto mkcert_error;
1980 }
1981 X509_NAME_free(name);
1982
1983 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001984 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001985 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1986 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1987 X509_EXTENSION *ext;
1988
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001989 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001990 goto mkcert_error;
1991 if (!X509_add_ext(newcrt, ext, -1)) {
1992 X509_EXTENSION_free(ext);
1993 goto mkcert_error;
1994 }
1995 X509_EXTENSION_free(ext);
1996 }
1997
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001998 /* Add SAN extension */
1999 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
2000 goto mkcert_error;
2001 }
2002
Christopher Faulet31af49d2015-06-09 17:29:50 +02002003 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002004
2005 key_type = EVP_PKEY_base_id(capkey);
2006
2007 if (key_type == EVP_PKEY_DSA)
2008 digest = EVP_sha1();
2009 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002010 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002011 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002012 digest = EVP_sha256();
2013 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002014#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002015 int nid;
2016
2017 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2018 goto mkcert_error;
2019 if (!(digest = EVP_get_digestbynid(nid)))
2020 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002021#else
2022 goto mkcert_error;
2023#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002024 }
2025
Christopher Faulet31af49d2015-06-09 17:29:50 +02002026 if (!(X509_sign(newcrt, capkey, digest)))
2027 goto mkcert_error;
2028
2029 /* Create and set the new SSL_CTX */
2030 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2031 goto mkcert_error;
2032 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2033 goto mkcert_error;
2034 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2035 goto mkcert_error;
2036 if (!SSL_CTX_check_private_key(ssl_ctx))
2037 goto mkcert_error;
2038
Shimi Gersner5846c492020-08-23 13:58:12 +03002039 /* Build chaining the CA cert and the rest of the chain, keep these order */
2040#if defined(SSL_CTX_add1_chain_cert)
2041 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2042 goto mkcert_error;
2043 }
2044
2045 if (bind_conf->ca_sign_ckch->chain) {
2046 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2047 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2048 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2049 goto mkcert_error;
2050 }
2051 }
2052 }
2053#endif
2054
Christopher Faulet31af49d2015-06-09 17:29:50 +02002055 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002056
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002057#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002058 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002059#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002060#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2061 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002062 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002063 EC_KEY *ecc;
2064 int nid;
2065
2066 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2067 goto end;
2068 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2069 goto end;
2070 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2071 EC_KEY_free(ecc);
2072 }
2073#endif
2074 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002075 return ssl_ctx;
2076
2077 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002078 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002079 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002080 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2081 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002082 return NULL;
2083}
2084
Christopher Faulet7969a332015-10-09 11:15:03 +02002085SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002086ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02002087{
Willy Tarreau07d94e42018-09-20 10:57:52 +02002088 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01002089 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002090
Olivier Houchard66ab4982019-02-26 18:37:15 +01002091 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02002092}
2093
Christopher Faulet30548802015-06-11 13:39:32 +02002094/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002095 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002096SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002097ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002098{
2099 struct lru64 *lru = NULL;
2100
2101 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002102 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002103 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002104 if (lru && lru->domain) {
2105 if (ssl)
2106 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002107 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002108 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002109 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002110 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002111 }
2112 return NULL;
2113}
2114
Emeric Brun821bb9b2017-06-15 16:37:39 +02002115/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2116 * function is not thread-safe, it should only be used to check if a certificate
2117 * exists in the lru cache (with no warranty it will not be removed by another
2118 * thread). It is kept for backward compatibility. */
2119SSL_CTX *
2120ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2121{
2122 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2123}
2124
Christopher Fauletd2cab922015-07-28 16:03:47 +02002125/* Set a certificate int the LRU cache used to store generated
2126 * certificate. Return 0 on success, otherwise -1 */
2127int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002128ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002129{
2130 struct lru64 *lru = NULL;
2131
2132 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002133 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002134 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002135 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002136 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002137 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002138 }
Christopher Faulet30548802015-06-11 13:39:32 +02002139 if (lru->domain && lru->data)
2140 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002141 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002142 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002143 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002144 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002145 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002146}
2147
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002148/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002149unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002150ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002151{
2152 return XXH32(data, len, ssl_ctx_lru_seed);
2153}
2154
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002155/* Generate a cert and immediately assign it to the SSL session so that the cert's
2156 * refcount is maintained regardless of the cert's presence in the LRU cache.
2157 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002158static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002159ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002160{
Shimi Gersner5846c492020-08-23 13:58:12 +03002161 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002162 SSL_CTX *ssl_ctx = NULL;
2163 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002164 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002165
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002166 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002167 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002168 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002169 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002170 if (lru && lru->domain)
2171 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002172 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002173 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002174 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002175 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002176 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002177 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002178 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002179 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002180 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002181 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002182 SSL_set_SSL_CTX(ssl, ssl_ctx);
2183 /* No LRU cache, this CTX will be released as soon as the session dies */
2184 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002185 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002186 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002187 return 0;
2188}
2189static int
2190ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2191{
2192 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002193 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002194
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002195 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002196 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002197 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002198 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002199 }
2200 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002201}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002202#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002203
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002204#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002205
2206static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002207{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002208#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002209 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002210 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2211#endif
2212}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002213static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2214 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002215 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2216}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002217static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002218#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002219 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002220 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2221#endif
2222}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002223static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002224#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002225 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002226 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2227#endif
2228}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002229/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002230static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2231/* Unusable in this context. */
2232static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2233static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2234static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2235static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2236static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002237#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002238
2239static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2240 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002241 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2242}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002243static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2244 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2245 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2246}
2247static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2248 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002249 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2250}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002251static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2252 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2253 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2254}
2255static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2256 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002257 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2258}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002259static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2260 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2261 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2262}
2263static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2264 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002265 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2266}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002267static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2268 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2269 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2270}
2271static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002272#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002273 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002274 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2275#endif
2276}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002277static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002278#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002279 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2280 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002281#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002282}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002283#endif
2284static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2285static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002286
William Lallemand7fd8b452020-05-07 15:20:43 +02002287struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002288 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2289 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2290 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2291 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2292 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2293 {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 +02002294};
2295
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002296static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2297{
2298 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2299 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2300 SSL_set_SSL_CTX(ssl, ctx);
2301}
2302
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002303#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002304
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002305int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002306{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002307 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002308 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002309
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002310 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2311 return SSL_TLSEXT_ERR_OK;
2312 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002313}
2314
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002315#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002316int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002317{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002318 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002319#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002320int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002321{
2322#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002323 struct connection *conn;
2324 struct bind_conf *s;
2325 const uint8_t *extension_data;
2326 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002327 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002328
2329 char *wildp = NULL;
2330 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002331 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002332 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002333 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002334 int i;
2335
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002336 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002337 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002338
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002339#ifdef USE_QUIC
2340 if (conn->qc) {
2341 /* Look for the QUIC transport parameters. */
2342#ifdef OPENSSL_IS_BORINGSSL
2343 if (!SSL_early_callback_ctx_extension_get(ctx, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2344 &extension_data, &extension_len))
2345#else
2346 if (!SSL_client_hello_get0_ext(ssl, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2347 &extension_data, &extension_len))
2348#endif
2349 goto abort;
2350
2351 if (!quic_transport_params_store(conn->qc, 0, extension_data,
2352 extension_data + extension_len))
2353 goto abort;
2354 }
2355#endif
2356
Olivier Houchard9679ac92017-10-27 14:58:08 +02002357 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002358 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002359#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002360 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2361 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002362#else
2363 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2364#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002365 /*
2366 * The server_name extension was given too much extensibility when it
2367 * was written, so parsing the normal case is a bit complex.
2368 */
2369 size_t len;
2370 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002371 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002372 /* Extract the length of the supplied list of names. */
2373 len = (*extension_data++) << 8;
2374 len |= *extension_data++;
2375 if (len + 2 != extension_len)
2376 goto abort;
2377 /*
2378 * The list in practice only has a single element, so we only consider
2379 * the first one.
2380 */
2381 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2382 goto abort;
2383 extension_len = len - 1;
2384 /* Now we can finally pull out the byte array with the actual hostname. */
2385 if (extension_len <= 2)
2386 goto abort;
2387 len = (*extension_data++) << 8;
2388 len |= *extension_data++;
2389 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2390 || memchr(extension_data, 0, len) != NULL)
2391 goto abort;
2392 servername = extension_data;
2393 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002394 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002395#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2396 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002397 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002398 }
2399#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002400 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002401 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002402 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002403 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002404 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002405 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002406 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002407 goto abort;
2408 }
2409
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002410 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002411#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002412 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002413#else
2414 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2415#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002416 uint8_t sign;
2417 size_t len;
2418 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002419 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002420 len = (*extension_data++) << 8;
2421 len |= *extension_data++;
2422 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002423 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002424 if (len % 2 != 0)
2425 goto abort;
2426 for (; len > 0; len -= 2) {
2427 extension_data++; /* hash */
2428 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002429 switch (sign) {
2430 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002431 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002432 break;
2433 case TLSEXT_signature_ecdsa:
2434 has_ecdsa_sig = 1;
2435 break;
2436 default:
2437 continue;
2438 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002439 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002440 break;
2441 }
2442 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002443 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002444 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002445 }
2446 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002447 const SSL_CIPHER *cipher;
2448 size_t len;
2449 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002450 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002451#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002452 len = ctx->cipher_suites_len;
2453 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002454#else
2455 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2456#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002457 if (len % 2 != 0)
2458 goto abort;
2459 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002460#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002461 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002462 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002463#else
2464 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2465#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002466 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002467 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002468 break;
2469 }
2470 }
2471 }
2472
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002473 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002474 trash.area[i] = tolower(servername[i]);
2475 if (!wildp && (trash.area[i] == '.'))
2476 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002477 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002478 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002479
William Lallemand150bfa82019-09-19 17:12:49 +02002480 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002481
William Lallemand94bd3192020-08-14 14:43:35 +02002482 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2483 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002484 for (i = 0; i < 2; i++) {
2485 if (i == 0) /* lookup in full qualified names */
2486 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002487 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002488 node = ebst_lookup(&s->sni_w_ctx, wildp);
2489 else
2490 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002491
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002492 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002493
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002494 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002495 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002496 struct sni_ctx *sni, *sni_tmp;
2497 int skip = 0;
2498
2499 if (i == 1 && wildp) { /* wildcard */
2500 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2501 sni = container_of(n, struct sni_ctx, name);
2502 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002503 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002504 skip = 1;
2505 break;
2506 }
2507 }
2508 if (skip)
2509 continue;
2510 }
2511
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002512 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002513 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002514 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002515 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002516 break;
2517 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002518 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002519 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002520 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002521 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002522 if (!node_anonymous)
2523 node_anonymous = n;
2524 break;
2525 }
2526 }
2527 }
William Lallemand94bd3192020-08-14 14:43:35 +02002528 }
2529 /* Once the certificates are found, select them depending on what is
2530 * supported in the client and by key_signature priority order: EDSA >
2531 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002532 if (has_ecdsa_sig && node_ecdsa)
2533 node = node_ecdsa;
2534 else if (has_rsa_sig && node_rsa)
2535 node = node_rsa;
2536 else if (node_anonymous)
2537 node = node_anonymous;
2538 else if (node_ecdsa)
2539 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2540 else
2541 node = node_rsa; /* no rsa signature case (far far away) */
2542
William Lallemand94bd3192020-08-14 14:43:35 +02002543 if (node) {
2544 /* switch ctx */
2545 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2546 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2547 if (conf) {
2548 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2549 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2550 if (conf->early_data)
2551 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002552 }
William Lallemand94bd3192020-08-14 14:43:35 +02002553 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2554 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002555 }
William Lallemand150bfa82019-09-19 17:12:49 +02002556
William Lallemand02010472019-10-18 11:02:19 +02002557 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002558#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002559 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002560 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002561 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002562 }
2563#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002564 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002565 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002566 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002567 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002568 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002569 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02002570allow_early:
2571#ifdef OPENSSL_IS_BORINGSSL
2572 if (allow_early)
2573 SSL_set_early_data_enabled(ssl, 1);
2574#else
2575 if (!allow_early)
2576 SSL_set_max_early_data(ssl, 0);
2577#endif
2578 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002579 abort:
2580 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2581 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002582#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002583 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002584#else
2585 *al = SSL_AD_UNRECOGNIZED_NAME;
2586 return 0;
2587#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002588}
2589
2590#else /* OPENSSL_IS_BORINGSSL */
2591
Emeric Brunfc0421f2012-09-07 17:30:07 +02002592/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2593 * warning when no match is found, which implies the default (first) cert
2594 * will keep being used.
2595 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002596static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002597{
2598 const char *servername;
2599 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002600 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002601 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002602 int i;
2603 (void)al; /* shut gcc stupid warning */
2604
2605 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002606 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002607#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002608 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2609 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002610#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002611 if (s->strict_sni)
2612 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002613 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002614 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002615 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002616 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002617 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002618
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002619 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002620 if (!servername[i])
2621 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002622 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002623 if (!wildp && (trash.area[i] == '.'))
2624 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002625 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002626 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002627
William Lallemand150bfa82019-09-19 17:12:49 +02002628 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002629 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002630 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002631 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2632 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002633 if (!container_of(n, struct sni_ctx, name)->neg) {
2634 node = n;
2635 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002636 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002637 }
2638 if (!node && wildp) {
2639 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002640 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2641 /* lookup a not neg filter */
2642 if (!container_of(n, struct sni_ctx, name)->neg) {
2643 node = n;
2644 break;
2645 }
2646 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002647 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002648 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002649#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002650 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2651 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002652 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002653 return SSL_TLSEXT_ERR_OK;
2654 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002655#endif
William Lallemand21724f02019-11-04 17:56:13 +01002656 if (s->strict_sni) {
2657 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002658 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002659 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002660 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002661 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002662 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002663 }
2664
2665 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002666 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002667 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002668 return SSL_TLSEXT_ERR_OK;
2669}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002670#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002671#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2672
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002673#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002674
2675static DH * ssl_get_dh_1024(void)
2676{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002677 static unsigned char dh1024_p[]={
2678 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2679 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2680 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2681 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2682 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2683 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2684 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2685 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2686 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2687 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2688 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2689 };
2690 static unsigned char dh1024_g[]={
2691 0x02,
2692 };
2693
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002694 BIGNUM *p;
2695 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002696 DH *dh = DH_new();
2697 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002698 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2699 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002700
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002701 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002702 DH_free(dh);
2703 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002704 } else {
2705 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002706 }
2707 }
2708 return dh;
2709}
2710
2711static DH *ssl_get_dh_2048(void)
2712{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002713 static unsigned char dh2048_p[]={
2714 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2715 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2716 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2717 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2718 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2719 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2720 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2721 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2722 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2723 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2724 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2725 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2726 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2727 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2728 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2729 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2730 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2731 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2732 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2733 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2734 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2735 0xB7,0x1F,0x77,0xF3,
2736 };
2737 static unsigned char dh2048_g[]={
2738 0x02,
2739 };
2740
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002741 BIGNUM *p;
2742 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002743 DH *dh = DH_new();
2744 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002745 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2746 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002747
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002748 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002749 DH_free(dh);
2750 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002751 } else {
2752 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002753 }
2754 }
2755 return dh;
2756}
2757
2758static DH *ssl_get_dh_4096(void)
2759{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002760 static unsigned char dh4096_p[]={
2761 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2762 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2763 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2764 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2765 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2766 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2767 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2768 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2769 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2770 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2771 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2772 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2773 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2774 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2775 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2776 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2777 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2778 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2779 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2780 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2781 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2782 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2783 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2784 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2785 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2786 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2787 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2788 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2789 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2790 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2791 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2792 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2793 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2794 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2795 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2796 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2797 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2798 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2799 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2800 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2801 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2802 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2803 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002804 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002805 static unsigned char dh4096_g[]={
2806 0x02,
2807 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002808
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002809 BIGNUM *p;
2810 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002811 DH *dh = DH_new();
2812 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002813 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2814 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002815
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002816 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002817 DH_free(dh);
2818 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002819 } else {
2820 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002821 }
2822 }
2823 return dh;
2824}
2825
2826/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002827 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002828static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2829{
2830 DH *dh = NULL;
2831 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002832 int type;
2833
2834 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002835
2836 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2837 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2838 */
2839 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2840 keylen = EVP_PKEY_bits(pkey);
2841 }
2842
Willy Tarreauef934602016-12-22 23:12:01 +01002843 if (keylen > global_ssl.default_dh_param) {
2844 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002845 }
2846
Remi Gacogned3a341a2015-05-29 16:26:17 +02002847 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002848 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002849 }
2850 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002851 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002852 }
2853 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002854 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002855 }
2856
2857 return dh;
2858}
2859
Remi Gacogne47783ef2015-05-29 15:53:22 +02002860static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002861{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002862 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002863 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002864
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002865 if (in == NULL)
2866 goto end;
2867
Remi Gacogne47783ef2015-05-29 15:53:22 +02002868 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002869 goto end;
2870
Remi Gacogne47783ef2015-05-29 15:53:22 +02002871 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2872
2873end:
2874 if (in)
2875 BIO_free(in);
2876
Emeric Brune1b4ed42018-08-16 15:14:12 +02002877 ERR_clear_error();
2878
Remi Gacogne47783ef2015-05-29 15:53:22 +02002879 return dh;
2880}
2881
2882int ssl_sock_load_global_dh_param_from_file(const char *filename)
2883{
2884 global_dh = ssl_sock_get_dh_from_file(filename);
2885
2886 if (global_dh) {
2887 return 0;
2888 }
2889
2890 return -1;
2891}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002892#endif
2893
William Lallemand9117de92019-10-04 00:29:42 +02002894/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002895static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002896 struct bind_conf *s, struct ssl_bind_conf *conf,
2897 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002898{
2899 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002900 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002901
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002902 if (*name == '!') {
2903 neg = 1;
2904 name++;
2905 }
2906 if (*name == '*') {
2907 wild = 1;
2908 name++;
2909 }
2910 /* !* filter is a nop */
2911 if (neg && wild)
2912 return order;
2913 if (*name) {
2914 int j, len;
2915 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002916 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02002917 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002918 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002919 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002920 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002921
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002922 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002923 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002924 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002925 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002926 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002927 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002928 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002929 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002930 sc->order = order++;
2931 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002932 sc->wild = wild;
2933 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002934 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02002935 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002936 }
2937 return order;
2938}
2939
William Lallemand6af03992019-07-23 15:00:54 +02002940/*
William Lallemand1d29c742019-10-04 00:53:29 +02002941 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2942 * This function can't return an error.
2943 *
2944 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2945 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002946void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002947{
2948
2949 struct sni_ctx *sc0, *sc0b, *sc1;
2950 struct ebmb_node *node;
2951
2952 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2953
2954 /* ignore if sc0 was already inserted in a tree */
2955 if (sc0->name.node.leaf_p)
2956 continue;
2957
2958 /* Check for duplicates. */
2959 if (sc0->wild)
2960 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2961 else
2962 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2963
2964 for (; node; node = ebmb_next_dup(node)) {
2965 sc1 = ebmb_entry(node, struct sni_ctx, name);
2966 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2967 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2968 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02002969 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002970 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002971 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02002972 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002973 }
2974 }
2975
2976 /* if duplicate, ignore the insertion */
2977 if (!sc0)
2978 continue;
2979
2980 if (sc0->wild)
2981 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
2982 else
2983 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01002984 }
William Lallemand21724f02019-11-04 17:56:13 +01002985
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01002986 /* replace the default_ctx if required with the instance's ctx. */
2987 if (ckch_inst->is_default) {
2988 SSL_CTX_free(bind_conf->default_ctx);
2989 SSL_CTX_up_ref(ckch_inst->ctx);
2990 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02002991 bind_conf->default_inst = ckch_inst;
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);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003427 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003428 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003429
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003430 /* Always keep a reference to the newly constructed SSL_CTX in the
3431 * instance. This way if the instance has no SNIs, the SSL_CTX will
3432 * still be linked. */
3433 SSL_CTX_up_ref(ctx);
3434 ckch_inst->ctx = ctx;
3435
William Lallemand9117de92019-10-04 00:29:42 +02003436 /* everything succeed, the ckch instance can be used */
3437 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003438 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003439 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003440
William Lallemand02e19a52020-04-08 16:11:26 +02003441 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3442
Emeric Brun054563d2019-10-17 13:16:58 +02003443 *ckchi = ckch_inst;
3444 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003445
3446error:
3447 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003448 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003449 if (ckch_inst->is_default)
3450 SSL_CTX_free(ctx);
3451
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003452 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003453 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003454 }
William Lallemandd9199372019-10-04 15:37:05 +02003455 SSL_CTX_free(ctx);
3456
Emeric Brun054563d2019-10-17 13:16:58 +02003457 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003458}
3459
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003460
3461/*
3462 * This function allocate a ckch_inst that will be used on the backend side
3463 * (server line)
3464 *
3465 * Returns a bitfield containing the flags:
3466 * ERR_FATAL in any fatal error case
3467 * ERR_ALERT if the reason of the error is available in err
3468 * ERR_WARN if a warning is available into err
3469 */
3470int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003471 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003472{
3473 SSL_CTX *ctx;
3474 struct cert_key_and_chain *ckch;
3475 struct ckch_inst *ckch_inst = NULL;
3476 int errcode = 0;
3477
3478 *ckchi = NULL;
3479
3480 if (!ckchs || !ckchs->ckch)
3481 return ERR_FATAL;
3482
3483 ckch = ckchs->ckch;
3484
3485 ctx = SSL_CTX_new(SSLv23_client_method());
3486 if (!ctx) {
3487 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3488 err && *err ? *err : "", path);
3489 errcode |= ERR_ALERT | ERR_FATAL;
3490 goto error;
3491 }
3492
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003493 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, ckch, ctx, err);
3494 if (errcode & ERR_CODE)
3495 goto error;
3496
3497 ckch_inst = ckch_inst_new();
3498 if (!ckch_inst) {
3499 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3500 err && *err ? *err : "", path);
3501 errcode |= ERR_ALERT | ERR_FATAL;
3502 goto error;
3503 }
3504
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003505 /* everything succeed, the ckch instance can be used */
3506 ckch_inst->bind_conf = NULL;
3507 ckch_inst->ssl_conf = NULL;
3508 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003509 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003510 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003511
3512 *ckchi = ckch_inst;
3513 return errcode;
3514
3515error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003516 SSL_CTX_free(ctx);
3517
3518 return errcode;
3519}
3520
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003521/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003522static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3523 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003524 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003525{
Emeric Brun054563d2019-10-17 13:16:58 +02003526 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003527
3528 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003529 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 +02003530
Emeric Brun054563d2019-10-17 13:16:58 +02003531 if (errcode & ERR_CODE)
3532 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003533
William Lallemand24bde432020-03-09 16:48:43 +01003534 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003535
3536 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003537 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003538 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003539}
3540
William Lallemanddb26e2b2021-01-26 12:01:46 +01003541/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3542 * fill the SSL_CTX of the server.
3543 *
3544 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003545static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003546 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003547{
3548 int errcode = 0;
3549
3550 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003551 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003552
3553 if (errcode & ERR_CODE)
3554 return errcode;
3555
William Lallemanddb26e2b2021-01-26 12:01:46 +01003556 (*ckch_inst)->server = server;
3557 /* Keep the reference to the SSL_CTX in the server. */
3558 SSL_CTX_up_ref((*ckch_inst)->ctx);
3559 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003560 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003561 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003562 return errcode;
3563}
3564
William Lallemand6be66ec2020-03-06 22:26:32 +01003565
William Lallemand4c68bba2020-03-30 18:45:10 +02003566
3567
3568/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3569 * done once. Zero is returned if the operation fails. No error is returned
3570 * if the random is said as not implemented, because we expect that openssl
3571 * will use another method once needed.
3572 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02003573int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02003574{
3575 unsigned char random;
3576 static int random_initialized = 0;
3577
3578 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3579 random_initialized = 1;
3580
3581 return random_initialized;
3582}
3583
William Lallemand2954c472020-03-06 21:54:13 +01003584/* Load a crt-list file, this is done in 2 parts:
3585 * - store the content of the file in a crtlist structure with crtlist_entry structures
3586 * - generate the instances by iterating on entries in the crtlist struct
3587 *
3588 * Nothing is locked there, this function is used in the configuration parser.
3589 *
3590 * Returns a set of ERR_* flags possibly with an error in <err>.
3591 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003592int 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 +01003593{
3594 struct crtlist *crtlist = NULL;
3595 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003596 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003597 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003598 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003599 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003600
William Lallemand79d31ec2020-03-25 15:10:49 +01003601 bind_conf_node = malloc(sizeof(*bind_conf_node));
3602 if (!bind_conf_node) {
3603 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3604 cfgerr |= ERR_FATAL | ERR_ALERT;
3605 goto error;
3606 }
3607 bind_conf_node->next = NULL;
3608 bind_conf_node->bind_conf = bind_conf;
3609
William Lallemand41ca9302020-04-08 13:15:18 +02003610 /* strip trailing slashes, including first one */
3611 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3612 *end = 0;
3613
William Lallemand2954c472020-03-06 21:54:13 +01003614 /* look for an existing crtlist or create one */
3615 eb = ebst_lookup(&crtlists_tree, file);
3616 if (eb) {
3617 crtlist = ebmb_entry(eb, struct crtlist, node);
3618 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003619 /* load a crt-list OR a directory */
3620 if (dir)
3621 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3622 else
3623 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3624
William Lallemand2954c472020-03-06 21:54:13 +01003625 if (!(cfgerr & ERR_CODE))
3626 ebst_insert(&crtlists_tree, &crtlist->node);
3627 }
3628
3629 if (cfgerr & ERR_CODE) {
3630 cfgerr |= ERR_FATAL | ERR_ALERT;
3631 goto error;
3632 }
3633
3634 /* generates ckch instance from the crtlist_entry */
3635 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3636 struct ckch_store *store;
3637 struct ckch_inst *ckch_inst = NULL;
3638
3639 store = entry->node.key;
3640 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3641 if (cfgerr & ERR_CODE) {
3642 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3643 goto error;
3644 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003645 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003646 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003647 }
William Lallemand2954c472020-03-06 21:54:13 +01003648
William Lallemand79d31ec2020-03-25 15:10:49 +01003649 /* add the bind_conf to the list */
3650 bind_conf_node->next = crtlist->bind_conf;
3651 crtlist->bind_conf = bind_conf_node;
3652
William Lallemand2954c472020-03-06 21:54:13 +01003653 return cfgerr;
3654error:
3655 {
William Lallemand49398312020-03-30 17:01:33 +02003656 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003657 struct ckch_inst *inst, *s_inst;
3658
William Lallemand49398312020-03-30 17:01:33 +02003659 lastentry = entry; /* which entry we tried to generate last */
3660 if (lastentry) {
3661 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3662 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3663 break;
3664
3665 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003666
William Lallemand49398312020-03-30 17:01:33 +02003667 /* this was not generated for this bind_conf, skip */
3668 if (inst->bind_conf != bind_conf)
3669 continue;
3670
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003671 /* free the sni_ctx and instance */
3672 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003673 }
William Lallemand2954c472020-03-06 21:54:13 +01003674 }
William Lallemand2954c472020-03-06 21:54:13 +01003675 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003676 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003677 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003678 return cfgerr;
3679}
3680
William Lallemand06b22a82020-03-16 14:45:55 +01003681/* Returns a set of ERR_* flags possibly with an error in <err>. */
3682int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3683{
3684 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003685 int cfgerr = 0;
3686 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003687 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003688 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003689
3690 if ((ckchs = ckchs_lookup(path))) {
3691 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003692 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3693 found++;
3694 } else if (stat(path, &buf) == 0) {
3695 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003696 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003697 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003698 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003699 cfgerr |= ERR_ALERT | ERR_FATAL;
3700 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003701 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003702 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003703 }
3704 } else {
3705 /* stat failed, could be a bundle */
3706 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003707 char fp[MAXPATHLEN+1] = {0};
3708 int n = 0;
3709
3710 /* Load all possible certs and keys in separate ckch_store */
3711 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3712 struct stat buf;
3713 int ret;
3714
3715 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3716 if (ret > sizeof(fp))
3717 continue;
3718
3719 if ((ckchs = ckchs_lookup(fp))) {
3720 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003721 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003722 } else {
3723 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003724 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003725 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003726 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003727 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003728 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3729 }
3730 }
3731 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003732#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3733 if (found) {
3734 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3735 err && *err ? *err : "", path);
3736 cfgerr |= ERR_ALERT | ERR_FATAL;
3737 }
3738#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003739 }
3740 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003741 if (!found) {
3742 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3743 err && *err ? *err : "", path, strerror(errno));
3744 cfgerr |= ERR_ALERT | ERR_FATAL;
3745 }
William Lallemand06b22a82020-03-16 14:45:55 +01003746
3747 return cfgerr;
3748}
3749
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003750
3751/* Create a full ssl context and ckch instance that will be used for a specific
3752 * backend server (server configuration line).
3753 * Returns a set of ERR_* flags possibly with an error in <err>.
3754 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003755int ssl_sock_load_srv_cert(char *path, struct server *server, int create_if_none, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003756{
3757 struct stat buf;
3758 int cfgerr = 0;
3759 struct ckch_store *ckchs;
3760 int found = 0; /* did we found a file to load ? */
3761
3762 if ((ckchs = ckchs_lookup(path))) {
3763 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01003764 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003765 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003766 } else {
3767 if (!create_if_none) {
3768 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
3769 err && *err ? *err : "", path);
3770 cfgerr |= ERR_ALERT | ERR_FATAL;
3771 goto out;
3772 }
3773
3774 if (stat(path, &buf) == 0) {
3775 /* We do not manage directories on backend side. */
3776 if (S_ISDIR(buf.st_mode) == 0) {
3777 ++found;
3778 ckchs = ckchs_load_cert_file(path, err);
3779 if (!ckchs)
3780 cfgerr |= ERR_ALERT | ERR_FATAL;
3781 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
3782 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003783 }
3784 }
3785 if (!found) {
3786 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3787 err && *err ? *err : "", path, strerror(errno));
3788 cfgerr |= ERR_ALERT | ERR_FATAL;
3789 }
3790
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003791out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003792 return cfgerr;
3793}
3794
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003795/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003796static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003797ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003798{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003799 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003800 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003801 SSL_OP_ALL | /* all known workarounds for bugs */
3802 SSL_OP_NO_SSLv2 |
3803 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003804 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003805 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003806 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003807 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003808 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003809 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003810 SSL_MODE_ENABLE_PARTIAL_WRITE |
3811 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003812 SSL_MODE_RELEASE_BUFFERS |
3813 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003814 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003815 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003816 int flags = MC_SSL_O_ALL;
3817 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003818 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003819
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003820 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003821 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003822
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003823 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003824 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3825 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3826 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003827 else
3828 flags = conf_ssl_methods->flags;
3829
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003830 min = conf_ssl_methods->min;
3831 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003832
3833 /* default minimum is TLSV12, */
3834 if (!min) {
3835 if (!max || (max >= default_min_ver)) {
3836 min = default_min_ver;
3837 } else {
3838 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). "
3839 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3840 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3841 min = max;
3842 }
3843 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003844 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003845 if (min)
3846 flags |= (methodVersions[min].flag - 1);
3847 if (max)
3848 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003849 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003850 min = max = CONF_TLSV_NONE;
3851 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003852 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003853 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003854 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003855 if (min) {
3856 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003857 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3858 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3859 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3860 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003861 hole = 0;
3862 }
3863 max = i;
3864 }
3865 else {
3866 min = max = i;
3867 }
3868 }
3869 else {
3870 if (min)
3871 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003872 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003873 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003874 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3875 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003876 cfgerr += 1;
3877 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003878 /* save real min/max in bind_conf */
3879 conf_ssl_methods->min = min;
3880 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003881
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003882#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003883 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003884 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003885 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003886 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003887 else
William Lallemandd0712f32020-06-11 17:34:00 +02003888 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
3889 /* clear every version flags in case SSL_CTX_new()
3890 * returns an SSL_CTX with disabled versions */
3891 SSL_CTX_clear_options(ctx, methodVersions[i].option);
3892
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003893 if (flags & methodVersions[i].flag)
3894 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02003895
3896 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003897#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003898 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003899 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3900 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003901#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003902
3903 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3904 options |= SSL_OP_NO_TICKET;
3905 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3906 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003907
3908#ifdef SSL_OP_NO_RENEGOTIATION
3909 options |= SSL_OP_NO_RENEGOTIATION;
3910#endif
3911
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003912 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003913
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05003914#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003915 if (global_ssl.async)
3916 mode |= SSL_MODE_ASYNC;
3917#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003918 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003919 if (global_ssl.life_time)
3920 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003921
3922#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3923#ifdef OPENSSL_IS_BORINGSSL
3924 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3925 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003926#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003927 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003928 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003929 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3930 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003931#else
3932 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003933#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003934 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003935#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003936 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003937}
3938
William Lallemand4f45bb92017-10-30 20:08:51 +01003939
3940static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3941{
3942 if (first == block) {
3943 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3944 if (first->len > 0)
3945 sh_ssl_sess_tree_delete(sh_ssl_sess);
3946 }
3947}
3948
3949/* return first block from sh_ssl_sess */
3950static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3951{
3952 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3953
3954}
3955
3956/* store a session into the cache
3957 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3958 * data: asn1 encoded session
3959 * data_len: asn1 encoded session length
3960 * Returns 1 id session was stored (else 0)
3961 */
3962static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3963{
3964 struct shared_block *first;
3965 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3966
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003967 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003968 if (!first) {
3969 /* Could not retrieve enough free blocks to store that session */
3970 return 0;
3971 }
3972
3973 /* STORE the key in the first elem */
3974 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3975 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3976 first->len = sizeof(struct sh_ssl_sess_hdr);
3977
3978 /* it returns the already existing node
3979 or current node if none, never returns null */
3980 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3981 if (oldsh_ssl_sess != sh_ssl_sess) {
3982 /* NOTE: Row couldn't be in use because we lock read & write function */
3983 /* release the reserved row */
3984 shctx_row_dec_hot(ssl_shctx, first);
3985 /* replace the previous session already in the tree */
3986 sh_ssl_sess = oldsh_ssl_sess;
3987 /* ignore the previous session data, only use the header */
3988 first = sh_ssl_sess_first_block(sh_ssl_sess);
3989 shctx_row_inc_hot(ssl_shctx, first);
3990 first->len = sizeof(struct sh_ssl_sess_hdr);
3991 }
3992
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003993 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01003994 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003995 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01003996 }
3997
3998 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003999
4000 return 1;
4001}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004002
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004003/* SSL callback used when a new session is created while connecting to a server */
4004static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4005{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004006 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004007 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004008
Willy Tarreau07d94e42018-09-20 10:57:52 +02004009 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004010
William Lallemand3ce6eed2021-02-08 10:43:44 +01004011 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4012 * one cache per thread, it only prevents to flush it from the CLI in
4013 * another thread */
4014
Olivier Houcharde6060c52017-11-16 17:42:52 +01004015 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4016 int len;
4017 unsigned char *ptr;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004018
Olivier Houcharde6060c52017-11-16 17:42:52 +01004019 len = i2d_SSL_SESSION(sess, NULL);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004020 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004021 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4022 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4023 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004024 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4025 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004026 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4027 }
4028 if (s->ssl_ctx.reused_sess[tid].ptr) {
4029 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4030 &ptr);
4031 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004032 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004033 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004034 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004035 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004036 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004037 }
4038
4039 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004040}
4041
Olivier Houcharde6060c52017-11-16 17:42:52 +01004042
William Lallemanded0b5ad2017-10-30 19:36:36 +01004043/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004044int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004045{
4046 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4047 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4048 unsigned char *p;
4049 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004050 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004051 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004052
4053 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004054 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004055 * note: SSL_SESSION_set1_id is using
4056 * a memcpy so we need to use a different pointer
4057 * than sid_data or sid_ctx_data to avoid valgrind
4058 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004059 */
4060
4061 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004062
4063 /* copy value in an other buffer */
4064 memcpy(encid, sid_data, sid_length);
4065
4066 /* pad with 0 */
4067 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4068 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4069
4070 /* force length to zero to avoid ASN1 encoding */
4071 SSL_SESSION_set1_id(sess, encid, 0);
4072
4073 /* force length to zero to avoid ASN1 encoding */
4074 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004075
4076 /* check if buffer is large enough for the ASN1 encoded session */
4077 data_len = i2d_SSL_SESSION(sess, NULL);
4078 if (data_len > SHSESS_MAX_DATA_LEN)
4079 goto err;
4080
4081 p = encsess;
4082
4083 /* process ASN1 session encoding before the lock */
4084 i2d_SSL_SESSION(sess, &p);
4085
William Lallemanded0b5ad2017-10-30 19:36:36 +01004086
William Lallemanda3c77cf2017-10-30 23:44:40 +01004087 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004088 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004089 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004090 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004091err:
4092 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004093 SSL_SESSION_set1_id(sess, encid, sid_length);
4094 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004095
4096 return 0; /* do not increment session reference count */
4097}
4098
4099/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004100SSL_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 +01004101{
William Lallemand4f45bb92017-10-30 20:08:51 +01004102 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004103 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4104 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004105 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004106 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004107
Willy Tarreau4c19e992021-06-15 16:39:22 +02004108 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004109
4110 /* allow the session to be freed automatically by openssl */
4111 *do_copy = 0;
4112
4113 /* tree key is zeros padded sessionid */
4114 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4115 memcpy(tmpkey, key, key_len);
4116 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4117 key = tmpkey;
4118 }
4119
4120 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004121 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004122
4123 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004124 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4125 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004126 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004127 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004128 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004129 return NULL;
4130 }
4131
William Lallemand4f45bb92017-10-30 20:08:51 +01004132 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4133 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004134
William Lallemand4f45bb92017-10-30 20:08:51 +01004135 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 +01004136
William Lallemanda3c77cf2017-10-30 23:44:40 +01004137 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004138
4139 /* decode ASN1 session */
4140 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004141 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004142 /* Reset session id and session id contenxt */
4143 if (sess) {
4144 SSL_SESSION_set1_id(sess, key, key_len);
4145 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4146 }
4147
4148 return sess;
4149}
4150
William Lallemand4f45bb92017-10-30 20:08:51 +01004151
William Lallemanded0b5ad2017-10-30 19:36:36 +01004152/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004153void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004154{
William Lallemand4f45bb92017-10-30 20:08:51 +01004155 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004156 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4157 unsigned int sid_length;
4158 const unsigned char *sid_data;
4159 (void)ctx;
4160
4161 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4162 /* tree key is zeros padded sessionid */
4163 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4164 memcpy(tmpkey, sid_data, sid_length);
4165 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4166 sid_data = tmpkey;
4167 }
4168
William Lallemanda3c77cf2017-10-30 23:44:40 +01004169 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004170
4171 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004172 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4173 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004174 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004175 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004176 }
4177
4178 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004179 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004180}
4181
4182/* Set session cache mode to server and disable openssl internal cache.
4183 * Set shared cache callbacks on an ssl context.
4184 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004185void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004186{
4187 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4188
4189 if (!ssl_shctx) {
4190 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4191 return;
4192 }
4193
4194 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4195 SSL_SESS_CACHE_NO_INTERNAL |
4196 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4197
4198 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004199 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4200 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4201 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004202}
William Lallemand7d42ef52020-07-06 11:41:30 +02004203
4204/*
4205 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4206 *
4207 * The format is:
4208 * * <Label> <space> <ClientRandom> <space> <Secret>
4209 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4210 */
4211
William Lallemand722180a2021-06-09 16:46:12 +02004212#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004213void SSL_CTX_keylog(const SSL *ssl, const char *line)
4214{
4215 struct ssl_keylog *keylog;
4216 char *lastarg = NULL;
4217 char *dst = NULL;
4218
4219 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4220 if (!keylog)
4221 return;
4222
4223 lastarg = strrchr(line, ' ');
4224 if (lastarg == NULL || ++lastarg == NULL)
4225 return;
4226
4227 dst = pool_alloc(pool_head_ssl_keylog_str);
4228 if (!dst)
4229 return;
4230
4231 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4232 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4233
4234 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4235 if (keylog->client_random)
4236 goto error;
4237 keylog->client_random = dst;
4238
4239 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4240 if (keylog->client_early_traffic_secret)
4241 goto error;
4242 keylog->client_early_traffic_secret = dst;
4243
4244 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4245 if(keylog->client_handshake_traffic_secret)
4246 goto error;
4247 keylog->client_handshake_traffic_secret = dst;
4248
4249 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4250 if (keylog->server_handshake_traffic_secret)
4251 goto error;
4252 keylog->server_handshake_traffic_secret = dst;
4253
4254 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4255 if (keylog->client_traffic_secret_0)
4256 goto error;
4257 keylog->client_traffic_secret_0 = dst;
4258
4259 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4260 if (keylog->server_traffic_secret_0)
4261 goto error;
4262 keylog->server_traffic_secret_0 = dst;
4263
4264 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4265 if (keylog->early_exporter_secret)
4266 goto error;
4267 keylog->early_exporter_secret = dst;
4268
4269 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4270 if (keylog->exporter_secret)
4271 goto error;
4272 keylog->exporter_secret = dst;
4273 } else {
4274 goto error;
4275 }
4276
4277 return;
4278
4279error:
4280 pool_free(pool_head_ssl_keylog_str, dst);
4281
4282 return;
4283}
4284#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004285
William Lallemand8b453912019-11-21 15:48:10 +01004286/*
4287 * This function applies the SSL configuration on a SSL_CTX
4288 * It returns an error code and fills the <err> buffer
4289 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004290static int ssl_sock_prepare_ctx(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf, SSL_CTX *ctx, char **err)
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004291{
4292 struct proxy *curproxy = bind_conf->frontend;
4293 int cfgerr = 0;
4294 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004295 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004296 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004297#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004298 const char *conf_ciphersuites;
4299#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004300 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004301
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004302 if (ssl_conf) {
4303 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4304 int i, min, max;
4305 int flags = MC_SSL_O_ALL;
4306
4307 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004308 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4309 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004310 if (min)
4311 flags |= (methodVersions[min].flag - 1);
4312 if (max)
4313 flags |= ~((methodVersions[max].flag << 1) - 1);
4314 min = max = CONF_TLSV_NONE;
4315 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4316 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4317 if (min)
4318 max = i;
4319 else
4320 min = max = i;
4321 }
4322 /* save real min/max */
4323 conf_ssl_methods->min = min;
4324 conf_ssl_methods->max = max;
4325 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004326 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4327 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004328 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004329 }
4330 }
4331
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004332 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004333 case SSL_SOCK_VERIFY_NONE:
4334 verify = SSL_VERIFY_NONE;
4335 break;
4336 case SSL_SOCK_VERIFY_OPTIONAL:
4337 verify = SSL_VERIFY_PEER;
4338 break;
4339 case SSL_SOCK_VERIFY_REQUIRED:
4340 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4341 break;
4342 }
4343 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4344 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004345 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 +01004346 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 +01004347 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 +01004348 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004349 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004350 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004351 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004352 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004353 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004354 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004355 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4356 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4357 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4358 cfgerr |= ERR_ALERT | ERR_FATAL;
4359 }
4360 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004361 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004362 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 +02004363 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004364 }
Emeric Brun850efd52014-01-29 12:24:34 +01004365 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004366 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4367 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004368 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004369 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004370#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004371 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004372 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4373
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004374 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004375 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4376 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004377 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004378 }
Emeric Brun561e5742012-10-02 15:20:55 +02004379 else {
4380 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4381 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004382 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004383#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004384 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004385 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004386#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004387 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004388 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004389 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4390 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004391 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004392 }
4393 }
4394#endif
4395
William Lallemand4f45bb92017-10-30 20:08:51 +01004396 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004397 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4398 if (conf_ciphers &&
4399 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004400 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4401 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004402 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004403 }
4404
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004405#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004406 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4407 if (conf_ciphersuites &&
4408 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004409 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4410 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004411 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004412 }
4413#endif
4414
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004415#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004416 /* If tune.ssl.default-dh-param has not been set,
4417 neither has ssl-default-dh-file and no static DH
4418 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004419 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004420 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004421 (ssl_dh_ptr_index == -1 ||
4422 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004423 /* default to dh-param 2048 */
4424 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004425 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004426
Willy Tarreauef934602016-12-22 23:12:01 +01004427 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004428 if (local_dh_1024 == NULL) {
4429 local_dh_1024 = ssl_get_dh_1024();
4430 }
Willy Tarreauef934602016-12-22 23:12:01 +01004431 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004432 if (local_dh_2048 == NULL) {
4433 local_dh_2048 = ssl_get_dh_2048();
4434 }
Willy Tarreauef934602016-12-22 23:12:01 +01004435 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004436 if (local_dh_4096 == NULL) {
4437 local_dh_4096 = ssl_get_dh_4096();
4438 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004439 }
4440 }
4441 }
4442#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004443
Emeric Brunfc0421f2012-09-07 17:30:07 +02004444 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004445#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004446 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004447#endif
William Lallemand722180a2021-06-09 16:46:12 +02004448#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004449 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
4450#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004451
Bernard Spil13c53f82018-02-15 13:34:58 +01004452#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004453 ssl_conf_cur = NULL;
4454 if (ssl_conf && ssl_conf->npn_str)
4455 ssl_conf_cur = ssl_conf;
4456 else if (bind_conf->ssl_conf.npn_str)
4457 ssl_conf_cur = &bind_conf->ssl_conf;
4458 if (ssl_conf_cur)
4459 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004460#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004461#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004462 ssl_conf_cur = NULL;
4463 if (ssl_conf && ssl_conf->alpn_str)
4464 ssl_conf_cur = ssl_conf;
4465 else if (bind_conf->ssl_conf.alpn_str)
4466 ssl_conf_cur = &bind_conf->ssl_conf;
4467 if (ssl_conf_cur)
4468 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004469#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004470#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004471 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4472 if (conf_curves) {
4473 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004474 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4475 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004476 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004477 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004478 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004479 }
4480#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004481#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004482 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004483 int i;
4484 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004485#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004486 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004487 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4488 NULL);
4489
4490 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004491 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004492 return cfgerr;
4493 }
4494#else
4495 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4496 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4497 ECDHE_DEFAULT_CURVE);
4498#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004499
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004500 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004501 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004502 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4503 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004504 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004505 }
4506 else {
4507 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4508 EC_KEY_free(ecdh);
4509 }
4510 }
4511#endif
4512
Emeric Brunfc0421f2012-09-07 17:30:07 +02004513 return cfgerr;
4514}
4515
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004516
4517/*
4518 * Prepare the SSL_CTX based on the bind line configuration.
4519 * Since the CA file loading is made depending on the verify option of the bind
4520 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4521 * If we want to create a link between the CA file entry and the corresponding
4522 * ckch instance (for CA file hot update), it needs to be done after
4523 * ssl_sock_prepare_ctx.
4524 * Returns 0 in case of success.
4525 */
4526int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4527 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4528{
4529 int errcode = 0;
4530
4531 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4532 if (!errcode && ckch_inst)
4533 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4534
4535 return errcode;
4536}
4537
Evan Broderbe554312013-06-27 00:05:25 -07004538static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4539{
4540 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4541 size_t prefixlen, suffixlen;
4542
4543 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004544 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004545 return 1;
4546
Evan Broderbe554312013-06-27 00:05:25 -07004547 /* The rest of this logic is based on RFC 6125, section 6.4.3
4548 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4549
Emeric Bruna848dae2013-10-08 11:27:28 +02004550 pattern_wildcard = NULL;
4551 pattern_left_label_end = pattern;
4552 while (*pattern_left_label_end != '.') {
4553 switch (*pattern_left_label_end) {
4554 case 0:
4555 /* End of label not found */
4556 return 0;
4557 case '*':
4558 /* If there is more than one wildcards */
4559 if (pattern_wildcard)
4560 return 0;
4561 pattern_wildcard = pattern_left_label_end;
4562 break;
4563 }
4564 pattern_left_label_end++;
4565 }
4566
4567 /* If it's not trivial and there is no wildcard, it can't
4568 * match */
4569 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004570 return 0;
4571
4572 /* Make sure all labels match except the leftmost */
4573 hostname_left_label_end = strchr(hostname, '.');
4574 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004575 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004576 return 0;
4577
4578 /* Make sure the leftmost label of the hostname is long enough
4579 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004580 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004581 return 0;
4582
4583 /* Finally compare the string on either side of the
4584 * wildcard */
4585 prefixlen = pattern_wildcard - pattern;
4586 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004587 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4588 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004589 return 0;
4590
4591 return 1;
4592}
4593
4594static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4595{
4596 SSL *ssl;
4597 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004598 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004599 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004600 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004601
4602 int depth;
4603 X509 *cert;
4604 STACK_OF(GENERAL_NAME) *alt_names;
4605 int i;
4606 X509_NAME *cert_subject;
4607 char *str;
4608
4609 if (ok == 0)
4610 return ok;
4611
4612 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004613 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004614 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004615
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004616 /* We're checking if the provided hostnames match the desired one. The
4617 * desired hostname comes from the SNI we presented if any, or if not
4618 * provided then it may have been explicitly stated using a "verifyhost"
4619 * directive. If neither is set, we don't care about the name so the
4620 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004621 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004622 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004623 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004624 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004625 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004626 if (!servername)
4627 return ok;
4628 }
Evan Broderbe554312013-06-27 00:05:25 -07004629
4630 /* We only need to verify the CN on the actual server cert,
4631 * not the indirect CAs */
4632 depth = X509_STORE_CTX_get_error_depth(ctx);
4633 if (depth != 0)
4634 return ok;
4635
4636 /* At this point, the cert is *not* OK unless we can find a
4637 * hostname match */
4638 ok = 0;
4639
4640 cert = X509_STORE_CTX_get_current_cert(ctx);
4641 /* It seems like this might happen if verify peer isn't set */
4642 if (!cert)
4643 return ok;
4644
4645 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4646 if (alt_names) {
4647 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4648 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4649 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004650#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004651 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4652#else
Evan Broderbe554312013-06-27 00:05:25 -07004653 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004654#endif
Evan Broderbe554312013-06-27 00:05:25 -07004655 ok = ssl_sock_srv_hostcheck(str, servername);
4656 OPENSSL_free(str);
4657 }
4658 }
4659 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004660 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004661 }
4662
4663 cert_subject = X509_get_subject_name(cert);
4664 i = -1;
4665 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4666 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004667 ASN1_STRING *value;
4668 value = X509_NAME_ENTRY_get_data(entry);
4669 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004670 ok = ssl_sock_srv_hostcheck(str, servername);
4671 OPENSSL_free(str);
4672 }
4673 }
4674
Willy Tarreau71d058c2017-07-26 20:09:56 +02004675 /* report the mismatch and indicate if SNI was used or not */
4676 if (!ok && !conn->err_code)
4677 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004678 return ok;
4679}
4680
Emeric Brun94324a42012-10-11 14:00:19 +02004681/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004682int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004683{
4684 int cfgerr = 0;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004685 SSL_CTX *ctx = srv->ssl_ctx.ctx;
Emeric Brun94324a42012-10-11 14:00:19 +02004686
Willy Tarreaufce03112015-01-15 21:32:40 +01004687 /* Automatic memory computations need to know we use SSL there */
4688 global.ssl_used_backend = 1;
4689
4690 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004691 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004692 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004693 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02004694 cfgerr++;
4695 return cfgerr;
4696 }
4697 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004698 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004699 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004700
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004701 /* The context will be uninitialized if there wasn't any "cert" option
4702 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004703 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004704 ctx = SSL_CTX_new(SSLv23_client_method());
4705 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004706 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004707 cfgerr++;
4708 return cfgerr;
4709 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004710
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004711 srv->ssl_ctx.ctx = ctx;
4712 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004713
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004714 cfgerr += ssl_sock_prep_srv_ctx_and_inst(srv, srv->ssl_ctx.ctx, srv->ssl_ctx.inst);
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004715
4716 return cfgerr;
4717}
4718
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004719/* Initialize an SSL context that will be used on the backend side.
4720 * Returns an error count.
4721 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004722static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004723{
4724 struct proxy *curproxy = srv->proxy;
4725 int cfgerr = 0;
4726 long options =
4727 SSL_OP_ALL | /* all known workarounds for bugs */
4728 SSL_OP_NO_SSLv2 |
4729 SSL_OP_NO_COMPRESSION;
4730 long mode =
4731 SSL_MODE_ENABLE_PARTIAL_WRITE |
4732 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4733 SSL_MODE_RELEASE_BUFFERS |
4734 SSL_MODE_SMALL_BUFFERS;
4735 int verify = SSL_VERIFY_NONE;
4736 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4737 int i, min, max, hole;
4738 int flags = MC_SSL_O_ALL;
4739
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004740 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004741 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
4742 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004743 else
4744 flags = conf_ssl_methods->flags;
4745
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004746 /* Real min and max should be determinate with configuration and openssl's capabilities */
4747 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004748 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004749 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004750 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004751
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004752 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004753 min = max = CONF_TLSV_NONE;
4754 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004755 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004756 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004757 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004758 if (min) {
4759 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02004760 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01004761 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4762 proxy_type_str(curproxy), curproxy->id, srv->id,
4763 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004764 hole = 0;
4765 }
4766 max = i;
4767 }
4768 else {
4769 min = max = i;
4770 }
4771 }
4772 else {
4773 if (min)
4774 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004775 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004776 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02004777 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004778 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004779 cfgerr += 1;
4780 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004781
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004782#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004783 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004784 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004785 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004786 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004787 else
4788 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4789 if (flags & methodVersions[i].flag)
4790 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004791#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004792 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004793 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4794 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004795#endif
4796
4797 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4798 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004799 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004800
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004801#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004802 if (global_ssl.async)
4803 mode |= SSL_MODE_ASYNC;
4804#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004805 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004806
Emeric Brun850efd52014-01-29 12:24:34 +01004807 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4808 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004809 switch (srv->ssl_ctx.verify) {
4810 case SSL_SOCK_VERIFY_NONE:
4811 verify = SSL_VERIFY_NONE;
4812 break;
4813 case SSL_SOCK_VERIFY_REQUIRED:
4814 verify = SSL_VERIFY_PEER;
4815 break;
4816 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004817 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004818 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004819 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004820 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004821 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004822 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004823 ha_alert("unable to set CA file '%s'.\n",
4824 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004825 cfgerr++;
4826 }
4827 }
Emeric Brun850efd52014-01-29 12:24:34 +01004828 else {
4829 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004830 ha_alert("verify is enabled by default but no CA file specified. If you're running on a LAN where you're certain to trust the server's certificate, please set an explicit 'verify none' statement on the 'server' line, or use 'ssl-server-verify none' in the global section to disable server-side verifications by default.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01004831 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004832 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01004833 cfgerr++;
4834 }
Emeric Brunef42d922012-10-11 16:11:36 +02004835#ifdef X509_V_FLAG_CRL_CHECK
4836 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004837 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02004838
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004839 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004840 ha_alert("unable to configure CRL file '%s'.\n",
4841 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004842 cfgerr++;
4843 }
4844 else {
4845 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4846 }
4847 }
4848#endif
4849 }
4850
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004851 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
4852 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004853 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004854 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004855 ha_alert("unable to set SSL cipher list to '%s'.\n",
4856 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004857 cfgerr++;
4858 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004859
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004860#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004861 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004862 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004863 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
4864 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004865 cfgerr++;
4866 }
4867#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004868#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4869 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004870 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01004871#endif
4872#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4873 if (srv->ssl_ctx.alpn_str)
4874 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4875#endif
4876
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004877
4878 return cfgerr;
4879}
4880
4881/*
4882 * Prepare the frontend's SSL_CTX based on the server line configuration.
4883 * Since the CA file loading is made depending on the verify option of the
4884 * server line, the link between the SSL_CTX and the CA file tree entry is
4885 * made here.
4886 * If we want to create a link between the CA file entry and the corresponding
4887 * ckch instance (for CA file hot update), it needs to be done after
4888 * ssl_sock_prepare_srv_ssl_ctx.
4889 * Returns an error count.
4890 */
4891int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
4892 struct ckch_inst *ckch_inst)
4893{
4894 int cfgerr = 0;
4895
4896 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
4897 if (!cfgerr && ckch_inst)
4898 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02004899
4900 return cfgerr;
4901}
4902
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004903
Frédéric Lécailleec216522020-11-23 14:33:30 +01004904/*
4905 * Create an initial CTX used to start the SSL connections.
4906 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
4907 * Returns 0 if succeeded, or something >0 if not.
4908 */
4909#ifdef USE_QUIC
4910static int ssl_initial_ctx(struct bind_conf *bind_conf)
4911{
4912 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
4913 return ssl_quic_initial_ctx(bind_conf);
4914 else
4915 return ssl_sock_initial_ctx(bind_conf);
4916}
4917#else
4918static int ssl_initial_ctx(struct bind_conf *bind_conf)
4919{
4920 return ssl_sock_initial_ctx(bind_conf);
4921}
4922#endif
4923
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004924/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004925 * be NULL, in which case nothing is done. Returns the number of errors
4926 * encountered.
4927 */
Willy Tarreau03209342016-12-22 17:08:28 +01004928int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004929{
4930 struct ebmb_node *node;
4931 struct sni_ctx *sni;
4932 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004933 int errcode = 0;
4934 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004935
Willy Tarreaufce03112015-01-15 21:32:40 +01004936 /* Automatic memory computations need to know we use SSL there */
4937 global.ssl_used_frontend = 1;
4938
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004939 /* Create initial_ctx used to start the ssl connection before do switchctx */
4940 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01004941 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004942 /* It should not be necessary to call this function, but it's
4943 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01004944 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004945 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
4946 }
4947 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02004948 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, bind_conf->default_inst, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004949 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004950
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004951 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004952 while (node) {
4953 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004954 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004955 /* only initialize the CTX on its first occurrence and
4956 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004957 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
4958 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004959 node = ebmb_next(node);
4960 }
4961
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004962 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004963 while (node) {
4964 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004965 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004966 /* only initialize the CTX on its first occurrence and
4967 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004968 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004969 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004970 node = ebmb_next(node);
4971 }
William Lallemand8b453912019-11-21 15:48:10 +01004972
4973 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004974 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004975 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004976 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004977 err++;
4978 }
4979
4980 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004981 return err;
4982}
4983
Willy Tarreau55d37912016-12-21 23:38:39 +01004984/* Prepares all the contexts for a bind_conf and allocates the shared SSL
4985 * context if needed. Returns < 0 on error, 0 on success. The warnings and
4986 * alerts are directly emitted since the rest of the stack does it below.
4987 */
4988int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
4989{
4990 struct proxy *px = bind_conf->frontend;
4991 int alloc_ctx;
4992 int err;
4993
4994 if (!bind_conf->is_ssl) {
4995 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004996 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
4997 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01004998 }
4999 return 0;
5000 }
5001 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005002 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005003 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5004 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005005 }
5006 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005007 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5008 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005009 return -1;
5010 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005011 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005012 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005013 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005014 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005015 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005016 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005017 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5018 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");
5019 else
5020 ha_alert("Unable to allocate SSL session cache.\n");
5021 return -1;
5022 }
5023 /* free block callback */
5024 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5025 /* init the root tree within the extra space */
5026 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5027 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005028 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005029 err = 0;
5030 /* initialize all certificate contexts */
5031 err += ssl_sock_prepare_all_ctx(bind_conf);
5032
5033 /* initialize CA variables if the certificates generation is enabled */
5034 err += ssl_sock_load_ca(bind_conf);
5035
5036 return -err;
5037}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005038
5039/* release ssl context allocated for servers. */
5040void ssl_sock_free_srv_ctx(struct server *srv)
5041{
Olivier Houchardc7566002018-11-20 23:33:50 +01005042#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5043 if (srv->ssl_ctx.alpn_str)
Willy Tarreaue709e822021-02-26 21:06:32 +01005044 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005045#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005046#ifdef OPENSSL_NPN_NEGOTIATED
Olivier Houchardc7566002018-11-20 23:33:50 +01005047 if (srv->ssl_ctx.npn_str)
Willy Tarreaue709e822021-02-26 21:06:32 +01005048 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005049#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005050 if (srv->ssl_ctx.reused_sess) {
5051 int i;
5052
5053 for (i = 0; i < global.nbthread; i++)
Willy Tarreaue709e822021-02-26 21:06:32 +01005054 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
5055 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005056 }
5057
Willy Tarreaue709e822021-02-26 21:06:32 +01005058 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005059 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005060 srv->ssl_ctx.ctx = NULL;
5061 }
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005062}
5063
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005064/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005065 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5066 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005067void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005068{
5069 struct ebmb_node *node, *back;
5070 struct sni_ctx *sni;
5071
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005072 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005073 while (node) {
5074 sni = ebmb_entry(node, struct sni_ctx, name);
5075 back = ebmb_next(node);
5076 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005077 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005078 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005079 free(sni);
5080 node = back;
5081 }
5082
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005083 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005084 while (node) {
5085 sni = ebmb_entry(node, struct sni_ctx, name);
5086 back = ebmb_next(node);
5087 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005088 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005089 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005090 free(sni);
5091 node = back;
5092 }
William Lallemandb2408692020-06-24 09:54:29 +02005093
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005094 SSL_CTX_free(bind_conf->initial_ctx);
5095 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005096 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005097 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005098 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005099 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005100}
William Lallemandb2408692020-06-24 09:54:29 +02005101
5102
5103void ssl_sock_deinit()
5104{
5105 crtlist_deinit(); /* must be free'd before the ckchs */
5106 ckch_deinit();
5107}
5108REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005109
Willy Tarreau795cdab2016-12-22 17:30:54 +01005110/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5111void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5112{
5113 ssl_sock_free_ca(bind_conf);
5114 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005115 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005116 free(bind_conf->ca_sign_file);
5117 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005118 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005119 free(bind_conf->keys_ref->filename);
5120 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005121 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005122 free(bind_conf->keys_ref);
5123 }
5124 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005125 bind_conf->ca_sign_pass = NULL;
5126 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005127}
5128
Christopher Faulet31af49d2015-06-09 17:29:50 +02005129/* Load CA cert file and private key used to generate certificates */
5130int
Willy Tarreau03209342016-12-22 17:08:28 +01005131ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005132{
Willy Tarreau03209342016-12-22 17:08:28 +01005133 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03005134 struct cert_key_and_chain *ckch = NULL;
5135 int ret = 0;
5136 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005137
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02005138 if (!bind_conf->generate_certs)
Shimi Gersner5846c492020-08-23 13:58:12 +03005139 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005140
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005141#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005142 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005143 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005144 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005145 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005146 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005147#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005148
Christopher Faulet31af49d2015-06-09 17:29:50 +02005149 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005150 ha_alert("Proxy '%s': cannot enable certificate generation, "
5151 "no CA certificate File configured at [%s:%d].\n",
5152 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005153 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005154 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005155
Shimi Gersner5846c492020-08-23 13:58:12 +03005156 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02005157 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03005158 if (!ckch) {
5159 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5160 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5161 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005162 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005163
5164 /* Try to parse file */
5165 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
5166 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5167 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005168 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005169 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005170 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005171
5172 /* Fail if missing cert or pkey */
5173 if ((!ckch->cert) || (!ckch->key)) {
5174 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5175 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5176 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005177 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005178
Shimi Gersner5846c492020-08-23 13:58:12 +03005179 /* Final assignment to bind */
5180 bind_conf->ca_sign_ckch = ckch;
5181 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005182
Shimi Gersner5846c492020-08-23 13:58:12 +03005183 failed:
5184 if (ckch) {
5185 ssl_sock_free_cert_key_and_chain_contents(ckch);
5186 free(ckch);
5187 }
5188
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005189 bind_conf->generate_certs = 0;
Shimi Gersner5846c492020-08-23 13:58:12 +03005190 ret++;
5191 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005192}
5193
5194/* Release CA cert and private key used to generate certificated */
5195void
5196ssl_sock_free_ca(struct bind_conf *bind_conf)
5197{
Shimi Gersner5846c492020-08-23 13:58:12 +03005198 if (bind_conf->ca_sign_ckch) {
5199 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005200 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005201 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005202}
5203
Emeric Brun46591952012-05-18 15:47:34 +02005204/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005205 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5206 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5207 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5208 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005209 * 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 +01005210 * as parameters to this function.
5211 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5212 * CO_ER_SSL_NO_MEM.
5213 */
5214int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5215 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5216{
5217 int retry = 1;
5218
5219 retry:
5220 /* Alloc a new SSL session. */
5221 *ssl = SSL_new(ssl_ctx);
5222 if (!*ssl) {
5223 if (!retry--)
5224 goto err;
5225
5226 pool_gc(NULL);
5227 goto retry;
5228 }
5229
5230 *bio = BIO_new(bio_meth);
5231 if (!*bio) {
5232 SSL_free(*ssl);
5233 *ssl = NULL;
5234 if (!retry--)
5235 goto err;
5236
5237 pool_gc(NULL);
5238 goto retry;
5239 }
5240
5241 BIO_set_data(*bio, ctx);
5242 SSL_set_bio(*ssl, *bio, *bio);
5243
5244 /* set connection pointer. */
5245 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5246 SSL_free(*ssl);
5247 *ssl = NULL;
5248 if (!retry--)
5249 goto err;
5250
5251 pool_gc(NULL);
5252 goto retry;
5253 }
5254
5255 return 0;
5256
5257 err:
5258 conn->err_code = CO_ER_SSL_NO_MEM;
5259 return -1;
5260}
5261
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005262/* This function is called when all the XPRT have been initialized. We can
5263 * now attempt to start the SSL handshake.
5264 */
5265static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5266{
5267 struct ssl_sock_ctx *ctx = xprt_ctx;
5268
5269 if (ctx->xprt->start) {
5270 int ret;
5271
5272 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5273 if (ret < 0)
5274 return ret;
5275 }
5276 tasklet_wakeup(ctx->wait_event.tasklet);
5277
5278 return 0;
5279}
5280
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005281/*
Emeric Brun46591952012-05-18 15:47:34 +02005282 * This function is called if SSL * context is not yet allocated. The function
5283 * is designed to be called before any other data-layer operation and sets the
5284 * handshake flag on the connection. It is safe to call it multiple times.
5285 * It returns 0 on success and -1 in error case.
5286 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005287static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005288{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005289 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005290 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005291 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005292 return 0;
5293
Olivier Houchard66ab4982019-02-26 18:37:15 +01005294 ctx = pool_alloc(ssl_sock_ctx_pool);
5295 if (!ctx) {
5296 conn->err_code = CO_ER_SSL_NO_MEM;
5297 return -1;
5298 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005299 ctx->wait_event.tasklet = tasklet_new();
5300 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005301 conn->err_code = CO_ER_SSL_NO_MEM;
5302 pool_free(ssl_sock_ctx_pool, ctx);
5303 return -1;
5304 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005305 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5306 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005307 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005308 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005309 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005310 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005311 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005312 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005313 ctx->xprt_st = 0;
5314 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02005315 ctx->hsk_error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005316
5317 /* Only work with sockets for now, this should be adapted when we'll
5318 * add QUIC support.
5319 */
5320 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005321 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005322 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5323 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005324 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005325
Willy Tarreau20879a02012-12-03 16:32:10 +01005326 if (global.maxsslconn && sslconns >= global.maxsslconn) {
5327 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005328 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005329 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005330
Emeric Brun46591952012-05-18 15:47:34 +02005331 /* If it is in client mode initiate SSL session
5332 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005333 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005334 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5335 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005336 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005337
Olivier Houchard66ab4982019-02-26 18:37:15 +01005338 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005339 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005340 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5341 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5342 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 +01005343 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005344 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005345 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005346 } else if (sess) {
5347 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005348 }
5349 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005350 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005351
Emeric Brun46591952012-05-18 15:47:34 +02005352 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005353 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
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 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005360 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005361 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005362
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005363 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5364 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005365 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005366
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005367#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005368 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005369 b_alloc(&ctx->early_buf);
5370 SSL_set_max_early_data(ctx->ssl,
5371 /* Only allow early data if we managed to allocate
5372 * a buffer.
5373 */
5374 (!b_is_null(&ctx->early_buf)) ?
5375 global.tune.bufsize - global.tune.maxrewrite : 0);
5376 }
5377#endif
5378
Olivier Houchard66ab4982019-02-26 18:37:15 +01005379 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005380
Emeric Brun46591952012-05-18 15:47:34 +02005381 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005382 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005383#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005384 if (bc->ssl_conf.early_data)
5385 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005386#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005387
Willy Tarreau4781b152021-04-06 13:53:36 +02005388 _HA_ATOMIC_INC(&sslconns);
5389 _HA_ATOMIC_INC(&totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005390 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005391 return 0;
5392 }
5393 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005394 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005395err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005396 if (ctx && ctx->wait_event.tasklet)
5397 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005398 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005399 return -1;
5400}
5401
5402
5403/* This is the callback which is used when an SSL handshake is pending. It
5404 * updates the FD status if it wants some polling before being called again.
5405 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5406 * otherwise it returns non-zero and removes itself from the connection's
5407 * flags (the bit is provided in <flag> by the caller).
5408 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005409static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005410{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005411 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005412 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005413 struct ssl_counters *counters = NULL;
5414 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005415 struct listener *li;
5416 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005417 socklen_t lskerr;
5418 int skerr;
5419
Emeric Brun46591952012-05-18 15:47:34 +02005420
Willy Tarreau3c728722014-01-23 13:50:42 +01005421 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005422 return 0;
5423
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005424 /* get counters */
5425 switch (obj_type(conn->target)) {
5426 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005427 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005428 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5429 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5430 &ssl_stats_module);
5431 break;
5432
5433 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005434 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005435 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5436 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5437 &ssl_stats_module);
5438 break;
5439
5440 default:
5441 break;
5442 }
5443
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005444 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005445 goto out_error;
5446
Willy Tarreau06300382021-02-02 15:42:25 +01005447 /* don't start calculating a handshake on a dead connection */
5448 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5449 goto out_error;
5450
5451 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5452 * status from the lower layers, so let's check the FD directly. Ideally
5453 * the xprt layers should provide some status indicating their knowledge
5454 * of shutdowns or error.
5455 */
5456 skerr = 0;
5457 lskerr = sizeof(skerr);
5458 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5459 skerr != 0)
5460 goto out_error;
5461
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005462#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005463 /*
5464 * Check if we have early data. If we do, we have to read them
5465 * before SSL_do_handshake() is called, And there's no way to
5466 * detect early data, except to try to read them
5467 */
5468 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005469 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005470
Olivier Houchard54907bb2019-12-19 15:02:39 +01005471 while (1) {
5472 ret = SSL_read_early_data(ctx->ssl,
5473 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5474 &read_data);
5475 if (ret == SSL_READ_EARLY_DATA_ERROR)
5476 goto check_error;
5477 if (read_data > 0) {
5478 conn->flags |= CO_FL_EARLY_DATA;
5479 b_add(&ctx->early_buf, read_data);
5480 }
5481 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5482 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5483 if (!b_data(&ctx->early_buf))
5484 b_free(&ctx->early_buf);
5485 break;
5486 }
5487 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005488 }
5489#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005490 /* If we use SSL_do_handshake to process a reneg initiated by
5491 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5492 * Usually SSL_write and SSL_read are used and process implicitly
5493 * the reneg handshake.
5494 * Here we use SSL_peek as a workaround for reneg.
5495 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005496 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005497 char c;
5498
Olivier Houchard66ab4982019-02-26 18:37:15 +01005499 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005500 if (ret <= 0) {
5501 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005502 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005503
Emeric Brun674b7432012-11-08 19:21:55 +01005504 if (ret == SSL_ERROR_WANT_WRITE) {
5505 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005506 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005507 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005508 return 0;
5509 }
5510 else if (ret == SSL_ERROR_WANT_READ) {
5511 /* handshake may have been completed but we have
5512 * no more data to read.
5513 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005514 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005515 ret = 1;
5516 goto reneg_ok;
5517 }
5518 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005519 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005520 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005521 return 0;
5522 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005523#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005524 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005525 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005526 return 0;
5527 }
5528#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005529 else if (ret == SSL_ERROR_SYSCALL) {
5530 /* if errno is null, then connection was successfully established */
5531 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5532 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005533 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005534#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5535 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005536 conn->err_code = CO_ER_SSL_HANDSHAKE;
5537#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005538 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005539#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005540 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005541 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005542 empty_handshake = state == TLS_ST_BEFORE;
5543#else
Lukas Tribus49799162019-07-08 14:29:15 +02005544 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5545 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005546#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005547 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005548 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005549 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005550 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5551 else
5552 conn->err_code = CO_ER_SSL_EMPTY;
5553 }
5554 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005555 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005556 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5557 else
5558 conn->err_code = CO_ER_SSL_ABORT;
5559 }
5560 }
5561 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005562 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005563 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005564 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005565 conn->err_code = CO_ER_SSL_HANDSHAKE;
5566 }
Lukas Tribus49799162019-07-08 14:29:15 +02005567#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005568 }
Emeric Brun674b7432012-11-08 19:21:55 +01005569 goto out_error;
5570 }
5571 else {
5572 /* Fail on all other handshake errors */
5573 /* Note: OpenSSL may leave unread bytes in the socket's
5574 * buffer, causing an RST to be emitted upon close() on
5575 * TCP sockets. We first try to drain possibly pending
5576 * data to avoid this as much as possible.
5577 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005578 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005579 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005580 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005581 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005582 goto out_error;
5583 }
5584 }
5585 /* read some data: consider handshake completed */
5586 goto reneg_ok;
5587 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005588 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005589check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005590 if (ret != 1) {
5591 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005592 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005593
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02005594 if (!ctx->hsk_error_code)
5595 ctx->hsk_error_code = ERR_peek_error();
5596
Emeric Brun46591952012-05-18 15:47:34 +02005597 if (ret == SSL_ERROR_WANT_WRITE) {
5598 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005599 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005600 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005601 return 0;
5602 }
5603 else if (ret == SSL_ERROR_WANT_READ) {
5604 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005605 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005606 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5607 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005608 return 0;
5609 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005610#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005611 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005612 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005613 return 0;
5614 }
5615#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005616 else if (ret == SSL_ERROR_SYSCALL) {
5617 /* if errno is null, then connection was successfully established */
5618 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5619 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005620 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005621#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5622 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005623 conn->err_code = CO_ER_SSL_HANDSHAKE;
5624#else
5625 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005626#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005627 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005628 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005629 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005630#else
Lukas Tribus49799162019-07-08 14:29:15 +02005631 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5632 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005633#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005634 if (empty_handshake) {
5635 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005636 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005637 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5638 else
5639 conn->err_code = CO_ER_SSL_EMPTY;
5640 }
5641 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005642 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005643 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5644 else
5645 conn->err_code = CO_ER_SSL_ABORT;
5646 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005647 }
5648 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005649 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005650 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5651 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005652 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005653 }
Lukas Tribus49799162019-07-08 14:29:15 +02005654#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005655 }
Willy Tarreau89230192012-09-28 20:22:13 +02005656 goto out_error;
5657 }
Emeric Brun46591952012-05-18 15:47:34 +02005658 else {
5659 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005660 /* Note: OpenSSL may leave unread bytes in the socket's
5661 * buffer, causing an RST to be emitted upon close() on
5662 * TCP sockets. We first try to drain possibly pending
5663 * data to avoid this as much as possible.
5664 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005665 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005666 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005667 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005668 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005669 goto out_error;
5670 }
5671 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005672#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005673 else {
5674 /*
5675 * If the server refused the early data, we have to send a
5676 * 425 to the client, as we no longer have the data to sent
5677 * them again.
5678 */
5679 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005680 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005681 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5682 goto out_error;
5683 }
5684 }
5685 }
5686#endif
5687
Emeric Brun46591952012-05-18 15:47:34 +02005688
Emeric Brun674b7432012-11-08 19:21:55 +01005689reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005690
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005691#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005692 /* ASYNC engine API doesn't support moving read/write
5693 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005694 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005695 */
5696 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005697 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005698#endif
Emeric Brun46591952012-05-18 15:47:34 +02005699 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005700 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005701 if (objt_server(conn->target)) {
5702 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5703 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5704 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005705 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005706 else {
5707 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5708 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5709 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5710 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005711
Willy Tarreau42995282020-11-06 13:19:18 +01005712 if (counters) {
5713 ++counters->sess;
5714 ++counters_px->sess;
5715 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005716 }
Willy Tarreau42995282020-11-06 13:19:18 +01005717 else if (counters) {
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005718 ++counters->reused_sess;
5719 ++counters_px->reused_sess;
Emeric Brun46591952012-05-18 15:47:34 +02005720 }
5721
5722 /* The connection is now established at both layers, it's time to leave */
5723 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5724 return 1;
5725
5726 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005727 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005728 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005729 ERR_clear_error();
5730
Emeric Brun9fa89732012-10-04 17:09:56 +02005731 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01005732 if (objt_server(conn->target)) {
5733 struct server *s = __objt_server(conn->target);
5734 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
5735 * one cache per thread, it only prevents to flush it from the CLI in
5736 * another thread */
5737
5738 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005739 if (s->ssl_ctx.reused_sess[tid].ptr)
5740 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005741 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02005742 }
5743
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005744 if (counters) {
5745 ++counters->failed_handshake;
5746 ++counters_px->failed_handshake;
5747 }
5748
Emeric Brun46591952012-05-18 15:47:34 +02005749 /* Fail on all other handshake errors */
5750 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005751 if (!conn->err_code)
5752 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005753 return 0;
5754}
5755
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005756/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5757 * event subscriber <es> is not allowed to change from a previous call as long
5758 * as at least one event is still subscribed. The <event_type> must only be a
5759 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5760 * unless the transport layer was already released.
5761 */
5762static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005763{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005764 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005765
Olivier Houchard0ff28652019-06-24 18:57:39 +02005766 if (!ctx)
5767 return -1;
5768
Willy Tarreau113d52b2020-01-10 09:20:26 +01005769 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005770 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005771
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005772 ctx->subs = es;
5773 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005774
5775 /* we may have to subscribe to lower layers for new events */
5776 event_type &= ~ctx->wait_event.events;
5777 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5778 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005779 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005780}
5781
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005782/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5783 * The <es> pointer is not allowed to differ from the one passed to the
5784 * subscribe() call. It always returns zero.
5785 */
5786static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005787{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005788 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005789
Willy Tarreau113d52b2020-01-10 09:20:26 +01005790 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005791 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005792
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005793 es->events &= ~event_type;
5794 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005795 ctx->subs = NULL;
5796
5797 /* If we subscribed, and we're not doing the handshake,
5798 * then we subscribed because the upper layer asked for it,
5799 * as the upper layer is no longer interested, we can
5800 * unsubscribe too.
5801 */
5802 event_type &= ctx->wait_event.events;
5803 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5804 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005805
5806 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005807}
5808
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005809/* The connection has been taken over, so destroy the old tasklet and create
5810 * a new one. The original thread ID must be passed into orig_tid
5811 * It should be called with the takeover lock for the old thread held.
5812 * Returns 0 on success, and -1 on failure
5813 */
5814static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
5815{
5816 struct ssl_sock_ctx *ctx = xprt_ctx;
5817 struct tasklet *tl = tasklet_new();
5818
5819 if (!tl)
5820 return -1;
5821
5822 ctx->wait_event.tasklet->context = NULL;
5823 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
5824 ctx->wait_event.tasklet = tl;
5825 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5826 ctx->wait_event.tasklet->context = ctx;
5827 return 0;
5828}
5829
Willy Tarreau41491682021-03-02 17:29:56 +01005830/* notify the next xprt that the connection is about to become idle and that it
5831 * may be stolen at any time after the function returns and that any tasklet in
5832 * the chain must be careful before dereferencing its context.
5833 */
5834static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
5835{
5836 struct ssl_sock_ctx *ctx = xprt_ctx;
5837
5838 if (!ctx || !ctx->wait_event.tasklet)
5839 return;
5840
5841 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5842 if (ctx->xprt)
5843 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
5844}
5845
5846/* notify the next xprt that the connection is not idle anymore and that it may
5847 * not be stolen before the next xprt_set_idle().
5848 */
5849static void ssl_set_used(struct connection *conn, void *xprt_ctx)
5850{
5851 struct ssl_sock_ctx *ctx = xprt_ctx;
5852
5853 if (!ctx || !ctx->wait_event.tasklet)
5854 return;
5855
5856 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5857 if (ctx->xprt)
5858 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
5859}
5860
Olivier Houchard2e055482019-05-27 19:50:12 +02005861/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5862 * Returns 0 on success, and non-zero on failure.
5863 */
5864static 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)
5865{
5866 struct ssl_sock_ctx *ctx = xprt_ctx;
5867
5868 if (oldxprt_ops != NULL)
5869 *oldxprt_ops = ctx->xprt;
5870 if (oldxprt_ctx != NULL)
5871 *oldxprt_ctx = ctx->xprt_ctx;
5872 ctx->xprt = toadd_ops;
5873 ctx->xprt_ctx = toadd_ctx;
5874 return 0;
5875}
5876
Olivier Houchard5149b592019-05-23 17:47:36 +02005877/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5878 * return 0, otherwise just call the remove_xprt method from the underlying
5879 * XPRT.
5880 */
5881static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5882{
5883 struct ssl_sock_ctx *ctx = xprt_ctx;
5884
5885 if (ctx->xprt_ctx == toremove_ctx) {
5886 ctx->xprt_ctx = newctx;
5887 ctx->xprt = newops;
5888 return 0;
5889 }
5890 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5891}
5892
Willy Tarreau144f84a2021-03-02 16:09:26 +01005893struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02005894{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005895 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005896 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005897 struct connection *conn;
5898 int conn_in_list;
5899 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005900
Willy Tarreau41491682021-03-02 17:29:56 +01005901 if (state & TASK_F_USR1) {
5902 /* the tasklet was idling on an idle connection, it might have
5903 * been stolen, let's be careful!
5904 */
5905 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5906 if (tl->context == NULL) {
5907 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5908 tasklet_free(tl);
5909 return NULL;
5910 }
5911 conn = ctx->conn;
5912 conn_in_list = conn->flags & CO_FL_LIST_MASK;
5913 if (conn_in_list)
5914 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005915 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01005916 } else {
5917 conn = ctx->conn;
5918 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005919 }
Willy Tarreau41491682021-03-02 17:29:56 +01005920
Olivier Houchardea8dd942019-05-20 14:02:16 +02005921 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01005922 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005923 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005924 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5925 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01005926 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005927 }
5928 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005929 /* If we had an error, or the handshake is done and I/O is available,
5930 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005931 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005932 * we can't be sure conn_fd_handler() will be called again.
5933 */
5934 if ((ctx->conn->flags & CO_FL_ERROR) ||
5935 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005936 int woke = 0;
5937
5938 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005939 if (ctx->subs) {
5940 tasklet_wakeup(ctx->subs->tasklet);
5941 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005942 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005943 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005944 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005945
Olivier Houchardea8dd942019-05-20 14:02:16 +02005946 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005947 * upper layers know. If we have no mux, create it,
5948 * and once we have a mux, call its wake method if we didn't
5949 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005950 */
5951 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005952 if (!ctx->conn->mux)
5953 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005954 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005955 ret = ctx->conn->mux->wake(ctx->conn);
5956 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005957 }
5958 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05005959#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01005960 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005961 else if (b_data(&ctx->early_buf) && ctx->subs &&
5962 ctx->subs->events & SUB_RETRY_RECV) {
5963 tasklet_wakeup(ctx->subs->tasklet);
5964 ctx->subs->events &= ~SUB_RETRY_RECV;
5965 if (!ctx->subs->events)
5966 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005967 }
5968#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005969leave:
5970 if (!ret && conn_in_list) {
5971 struct server *srv = objt_server(conn->target);
5972
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005973 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005974 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau430bf4a2021-03-04 09:45:32 +01005975 ebmb_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005976 else
Willy Tarreau430bf4a2021-03-04 09:45:32 +01005977 ebmb_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005978 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005979 }
Willy Tarreau74163142021-03-13 11:30:19 +01005980 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005981}
5982
Emeric Brun46591952012-05-18 15:47:34 +02005983/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01005984 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02005985 * buffer wraps, in which case a second call may be performed. The connection's
5986 * flags are updated with whatever special event is detected (error, read0,
5987 * empty). The caller is responsible for taking care of those events and
5988 * avoiding the call if inappropriate. The function does not call the
5989 * connection's polling update function, so the caller is responsible for this.
5990 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005991static 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 +02005992{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005993 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02005994 ssize_t ret;
5995 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02005996
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005997 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005998 goto out_error;
5999
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006000#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006001 if (b_data(&ctx->early_buf)) {
6002 try = b_contig_space(buf);
6003 if (try > b_data(&ctx->early_buf))
6004 try = b_data(&ctx->early_buf);
6005 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6006 b_add(buf, try);
6007 b_del(&ctx->early_buf, try);
6008 if (b_data(&ctx->early_buf) == 0)
6009 b_free(&ctx->early_buf);
6010 return try;
6011 }
6012#endif
6013
Willy Tarreau911db9b2020-01-23 16:27:54 +01006014 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006015 /* a handshake was requested */
6016 return 0;
6017
Emeric Brun46591952012-05-18 15:47:34 +02006018 /* read the largest possible block. For this, we perform only one call
6019 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6020 * in which case we accept to do it once again. A new attempt is made on
6021 * EINTR too.
6022 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006023 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006024
Willy Tarreau591d4452018-06-15 17:21:00 +02006025 try = b_contig_space(buf);
6026 if (!try)
6027 break;
6028
Willy Tarreauabf08d92014-01-14 11:31:27 +01006029 if (try > count)
6030 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006031
Olivier Houchard66ab4982019-02-26 18:37:15 +01006032 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006033
Emeric Brune1f38db2012-09-03 20:36:47 +02006034 if (conn->flags & CO_FL_ERROR) {
6035 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006036 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006037 }
Emeric Brun46591952012-05-18 15:47:34 +02006038 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006039 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006040 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006041 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006042 }
Emeric Brun46591952012-05-18 15:47:34 +02006043 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006044 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006045 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006046 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006047 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006048 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006049#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006050 /* Async mode can be re-enabled, because we're leaving data state.*/
6051 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006052 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006053#endif
Emeric Brun46591952012-05-18 15:47:34 +02006054 break;
6055 }
6056 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006057 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006058 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6059 SUB_RETRY_RECV,
6060 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006061 /* handshake is running, and it may need to re-enable read */
6062 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006063#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006064 /* Async mode can be re-enabled, because we're leaving data state.*/
6065 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006066 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006067#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006068 break;
6069 }
Emeric Brun46591952012-05-18 15:47:34 +02006070 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006071 } else if (ret == SSL_ERROR_ZERO_RETURN)
6072 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006073 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6074 * stack before shutting down the connection for
6075 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006076 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
6077 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006078 /* otherwise it's a real error */
6079 goto out_error;
6080 }
6081 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006082 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006083 return done;
6084
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006085 clear_ssl_error:
6086 /* Clear openssl global errors stack */
6087 ssl_sock_dump_errors(conn);
6088 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006089 read0:
6090 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006091 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006092
Emeric Brun46591952012-05-18 15:47:34 +02006093 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006094 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006095 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006096 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006097 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006098 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006099}
6100
6101
Willy Tarreau787db9a2018-06-14 18:31:46 +02006102/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6103 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6104 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006105 * Only one call to send() is performed, unless the buffer wraps, in which case
6106 * a second call may be performed. The connection's flags are updated with
6107 * whatever special event is detected (error, empty). The caller is responsible
6108 * for taking care of those events and avoiding the call if inappropriate. The
6109 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006110 * is responsible for this. The buffer's output is not adjusted, it's up to the
6111 * caller to take care of this. It's up to the caller to update the buffer's
6112 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006113 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006114static 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 +02006115{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006116 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006117 ssize_t ret;
6118 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006119
6120 done = 0;
6121
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006122 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006123 goto out_error;
6124
Willy Tarreau911db9b2020-01-23 16:27:54 +01006125 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006126 /* a handshake was requested */
6127 return 0;
6128
6129 /* send the largest possible block. For this we perform only one call
6130 * to send() unless the buffer wraps and we exactly fill the first hunk,
6131 * in which case we accept to do it once again.
6132 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006133 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006134#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006135 size_t written_data;
6136#endif
6137
Willy Tarreau787db9a2018-06-14 18:31:46 +02006138 try = b_contig_data(buf, done);
6139 if (try > count)
6140 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006141
Willy Tarreau7bed9452014-02-02 02:00:24 +01006142 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006143 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006144 global_ssl.max_record && try > global_ssl.max_record) {
6145 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006146 }
6147 else {
6148 /* we need to keep the information about the fact that
6149 * we're not limiting the upcoming send(), because if it
6150 * fails, we'll have to retry with at least as many data.
6151 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006152 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006153 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006154
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006155#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006156 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006157 unsigned int max_early;
6158
Olivier Houchard522eea72017-11-03 16:27:47 +01006159 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006160 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006161 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006162 if (SSL_get0_session(ctx->ssl))
6163 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006164 else
6165 max_early = 0;
6166 }
6167
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006168 if (try + ctx->sent_early_data > max_early) {
6169 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006170 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006171 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006172 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006173 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006174 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006175 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006176 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006177 if (ret == 1) {
6178 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006179 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006180 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006181 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006182 /* Initiate the handshake, now */
6183 tasklet_wakeup(ctx->wait_event.tasklet);
6184 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006185
Olivier Houchardc2aae742017-09-22 18:26:28 +02006186 }
6187
6188 } else
6189#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006190 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006191
Emeric Brune1f38db2012-09-03 20:36:47 +02006192 if (conn->flags & CO_FL_ERROR) {
6193 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006194 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006195 }
Emeric Brun46591952012-05-18 15:47:34 +02006196 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006197 /* A send succeeded, so we can consider ourself connected */
6198 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006199 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006200 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006201 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006202 }
6203 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006204 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006205
Emeric Brun46591952012-05-18 15:47:34 +02006206 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006207 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006208 /* handshake is running, and it may need to re-enable write */
6209 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006210 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006211#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006212 /* Async mode can be re-enabled, because we're leaving data state.*/
6213 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006214 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006215#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006216 break;
6217 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006218
Emeric Brun46591952012-05-18 15:47:34 +02006219 break;
6220 }
6221 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006222 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006223 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006224 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6225 SUB_RETRY_RECV,
6226 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006227#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006228 /* Async mode can be re-enabled, because we're leaving data state.*/
6229 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006230 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006231#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006232 break;
6233 }
Emeric Brun46591952012-05-18 15:47:34 +02006234 goto out_error;
6235 }
6236 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006237 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006238 return done;
6239
6240 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006241 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006242 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006243 ERR_clear_error();
6244
Emeric Brun46591952012-05-18 15:47:34 +02006245 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006246 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006247}
6248
Willy Tarreau832e2422021-05-13 10:11:03 +02006249void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006250
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006251 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006252
Olivier Houchardea8dd942019-05-20 14:02:16 +02006253
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006254 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006255 if (ctx->wait_event.events != 0)
6256 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6257 ctx->wait_event.events,
6258 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006259 if (ctx->subs) {
6260 ctx->subs->events = 0;
6261 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006262 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006263
Olivier Houchard692c1d02019-05-23 18:41:47 +02006264 if (ctx->xprt->close)
6265 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006266#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006267 if (global_ssl.async) {
6268 OSSL_ASYNC_FD all_fd[32], afd;
6269 size_t num_all_fds = 0;
6270 int i;
6271
Olivier Houchard66ab4982019-02-26 18:37:15 +01006272 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006273 if (num_all_fds > 32) {
6274 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6275 return;
6276 }
6277
Olivier Houchard66ab4982019-02-26 18:37:15 +01006278 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006279
6280 /* If an async job is pending, we must try to
6281 to catch the end using polling before calling
6282 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006283 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006284 for (i=0 ; i < num_all_fds ; i++) {
6285 /* switch on an handler designed to
6286 * handle the SSL_free
6287 */
6288 afd = all_fd[i];
6289 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006290 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006291 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006292 /* To ensure that the fd cache won't be used
6293 * and we'll catch a real RD event.
6294 */
6295 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006296 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006297 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006298 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006299 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006300 return;
6301 }
Emeric Brun3854e012017-05-17 20:42:48 +02006302 /* Else we can remove the fds from the fdtab
6303 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006304 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006305 * because the fd is owned by the engine.
6306 * the engine is responsible to close
6307 */
6308 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +02006309 fd_stop_both(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006310 }
6311#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006312 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006313 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006314 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006315 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006316 _HA_ATOMIC_DEC(&sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006317 }
Emeric Brun46591952012-05-18 15:47:34 +02006318}
6319
6320/* This function tries to perform a clean shutdown on an SSL connection, and in
6321 * any case, flags the connection as reusable if no handshake was in progress.
6322 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006323static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006324{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006325 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006326
Willy Tarreau911db9b2020-01-23 16:27:54 +01006327 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006328 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006329 if (!clean)
6330 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006331 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006332 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006333 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006334 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006335 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006336 ERR_clear_error();
6337 }
Emeric Brun46591952012-05-18 15:47:34 +02006338}
6339
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006340
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006341/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006342int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6343{
6344 struct ssl_sock_ctx *ctx;
6345 X509 *crt;
6346
6347 if (!ssl_sock_is_ssl(conn))
6348 return 0;
6349
6350 ctx = conn->xprt_ctx;
6351
6352 crt = SSL_get_certificate(ctx->ssl);
6353 if (!crt)
6354 return 0;
6355
6356 return cert_get_pkey_algo(crt, out);
6357}
6358
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006359/* used for ppv2 cert signature (can be used for logging) */
6360const char *ssl_sock_get_cert_sig(struct connection *conn)
6361{
Christopher Faulet82004142019-09-10 10:12:03 +02006362 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006363
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006364 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6365 X509 *crt;
6366
6367 if (!ssl_sock_is_ssl(conn))
6368 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006369 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006370 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006371 if (!crt)
6372 return NULL;
6373 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6374 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6375}
6376
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006377/* used for ppv2 authority */
6378const char *ssl_sock_get_sni(struct connection *conn)
6379{
6380#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006381 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006382
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006383 if (!ssl_sock_is_ssl(conn))
6384 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006385 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006386 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006387#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006388 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006389#endif
6390}
6391
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006392/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006393const char *ssl_sock_get_cipher_name(struct connection *conn)
6394{
Christopher Faulet82004142019-09-10 10:12:03 +02006395 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006396
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006397 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006398 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006399 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006400 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006401}
6402
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006403/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006404const char *ssl_sock_get_proto_version(struct connection *conn)
6405{
Christopher Faulet82004142019-09-10 10:12:03 +02006406 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006407
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006408 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006409 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006410 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006411 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006412}
6413
Olivier Houchardab28a322018-12-21 19:45:40 +01006414void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6415{
6416#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02006417 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006418
Olivier Houcharde488ea82019-06-28 14:10:33 +02006419 if (!ssl_sock_is_ssl(conn))
6420 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006421 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006422 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006423#endif
6424}
6425
Willy Tarreau119a4082016-12-22 21:58:38 +01006426/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6427 * to disable SNI.
6428 */
Willy Tarreau63076412015-07-10 11:33:32 +02006429void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6430{
6431#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006432 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006433
Willy Tarreau119a4082016-12-22 21:58:38 +01006434 char *prev_name;
6435
Willy Tarreau63076412015-07-10 11:33:32 +02006436 if (!ssl_sock_is_ssl(conn))
6437 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006438 ctx = conn->xprt_ctx;
Willy Tarreau63076412015-07-10 11:33:32 +02006439
Willy Tarreau119a4082016-12-22 21:58:38 +01006440 /* if the SNI changes, we must destroy the reusable context so that a
6441 * new connection will present a new SNI. As an optimization we could
6442 * later imagine having a small cache of ssl_ctx to hold a few SNI per
6443 * server.
6444 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006445 prev_name = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau119a4082016-12-22 21:58:38 +01006446 if ((!prev_name && hostname) ||
6447 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006448 SSL_set_session(ctx->ssl, NULL);
Willy Tarreau119a4082016-12-22 21:58:38 +01006449
Olivier Houchard66ab4982019-02-26 18:37:15 +01006450 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006451#endif
6452}
6453
Emeric Brun0abf8362014-06-24 18:26:41 +02006454/* Extract peer certificate's common name into the chunk dest
6455 * Returns
6456 * the len of the extracted common name
6457 * or 0 if no CN found in DN
6458 * or -1 on error case (i.e. no peer certificate)
6459 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006460int ssl_sock_get_remote_common_name(struct connection *conn,
6461 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006462{
Christopher Faulet82004142019-09-10 10:12:03 +02006463 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04006464 X509 *crt = NULL;
6465 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006466 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006467 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006468 .area = (char *)&find_cn,
6469 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006470 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006471 int result = -1;
David Safb76832014-05-08 23:42:08 -04006472
6473 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02006474 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02006475 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006476
6477 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006478 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006479 if (!crt)
6480 goto out;
6481
6482 name = X509_get_subject_name(crt);
6483 if (!name)
6484 goto out;
David Safb76832014-05-08 23:42:08 -04006485
Emeric Brun0abf8362014-06-24 18:26:41 +02006486 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6487out:
David Safb76832014-05-08 23:42:08 -04006488 if (crt)
6489 X509_free(crt);
6490
6491 return result;
6492}
6493
Dave McCowan328fb582014-07-30 10:39:13 -04006494/* returns 1 if client passed a certificate for this session, 0 if not */
6495int ssl_sock_get_cert_used_sess(struct connection *conn)
6496{
Christopher Faulet82004142019-09-10 10:12:03 +02006497 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006498 X509 *crt = NULL;
6499
6500 if (!ssl_sock_is_ssl(conn))
6501 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006502 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006503
6504 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006505 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006506 if (!crt)
6507 return 0;
6508
6509 X509_free(crt);
6510 return 1;
6511}
6512
6513/* returns 1 if client passed a certificate for this connection, 0 if not */
6514int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006515{
Christopher Faulet82004142019-09-10 10:12:03 +02006516 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006517
David Safb76832014-05-08 23:42:08 -04006518 if (!ssl_sock_is_ssl(conn))
6519 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006520 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006521 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006522}
6523
6524/* returns result from SSL verify */
6525unsigned int ssl_sock_get_verify_result(struct connection *conn)
6526{
Christopher Faulet82004142019-09-10 10:12:03 +02006527 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006528
David Safb76832014-05-08 23:42:08 -04006529 if (!ssl_sock_is_ssl(conn))
6530 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006531 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006532 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006533}
6534
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006535/* Returns the application layer protocol name in <str> and <len> when known.
6536 * Zero is returned if the protocol name was not found, otherwise non-zero is
6537 * returned. The string is allocated in the SSL context and doesn't have to be
6538 * freed by the caller. NPN is also checked if available since older versions
6539 * of openssl (1.0.1) which are more common in field only support this one.
6540 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006541static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006542{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006543#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6544 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006545 struct ssl_sock_ctx *ctx = xprt_ctx;
6546 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006547 return 0;
6548
6549 *str = NULL;
6550
6551#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006552 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006553 if (*str)
6554 return 1;
6555#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006556#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006557 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006558 if (*str)
6559 return 1;
6560#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006561#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006562 return 0;
6563}
6564
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006565/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006566int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006567{
6568 X509 *ca;
6569 X509_NAME *name = NULL;
6570 ASN1_OCTET_STRING *skid = NULL;
6571 STACK_OF(X509) *chain = NULL;
6572 struct issuer_chain *issuer;
6573 struct eb64_node *node;
6574 char *path;
6575 u64 key;
6576 int ret = 0;
6577
6578 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6579 if (chain == NULL) {
6580 chain = sk_X509_new_null();
6581 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6582 name = X509_get_subject_name(ca);
6583 }
6584 if (!sk_X509_push(chain, ca)) {
6585 X509_free(ca);
6586 goto end;
6587 }
6588 }
6589 if (!chain) {
6590 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6591 goto end;
6592 }
6593 if (!skid) {
6594 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6595 goto end;
6596 }
6597 if (!name) {
6598 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6599 goto end;
6600 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006601 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006602 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006603 issuer = container_of(node, typeof(*issuer), node);
6604 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6605 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6606 goto end;
6607 }
6608 }
6609 issuer = calloc(1, sizeof *issuer);
6610 path = strdup(fp);
6611 if (!issuer || !path) {
6612 free(issuer);
6613 free(path);
6614 goto end;
6615 }
6616 issuer->node.key = key;
6617 issuer->path = path;
6618 issuer->chain = chain;
6619 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006620 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006621 ret = 1;
6622 end:
6623 if (skid)
6624 ASN1_OCTET_STRING_free(skid);
6625 if (chain)
6626 sk_X509_pop_free(chain, X509_free);
6627 return ret;
6628}
6629
William Lallemandda8584c2020-05-14 10:14:37 +02006630 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006631{
6632 AUTHORITY_KEYID *akid;
6633 struct issuer_chain *issuer = NULL;
6634
6635 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006636 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006637 struct eb64_node *node;
6638 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006639 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006640 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6641 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6642 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6643 issuer = ti;
6644 break;
6645 }
6646 }
6647 AUTHORITY_KEYID_free(akid);
6648 }
6649 return issuer;
6650}
6651
William Lallemanddad31052020-05-14 17:47:32 +02006652void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006653{
6654 struct eb64_node *node, *back;
6655 struct issuer_chain *issuer;
6656
William Lallemande0f3fd52020-02-25 14:53:06 +01006657 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006658 while (node) {
6659 issuer = container_of(node, typeof(*issuer), node);
6660 back = eb64_next(node);
6661 eb64_delete(node);
6662 free(issuer->path);
6663 sk_X509_pop_free(issuer->chain, X509_free);
6664 free(issuer);
6665 node = back;
6666 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006667}
6668
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006669#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006670static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006671 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006672
Emeric Brun3854e012017-05-17 20:42:48 +02006673 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006674 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006675 err_code = ERR_ABORT;
6676 }
6677 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006678}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006679#endif
6680
Willy Tarreaude5675a2021-01-20 14:41:29 +01006681/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006682 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006683 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006684static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006685{
6686 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006687 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006688
6689 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006690 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006691
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006692 if (sctx->conn != conn) {
6693 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6694 ret = 1;
6695 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01006696 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6697
6698 if (sctx->xprt) {
6699 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6700 if (sctx->xprt_ctx)
6701 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6702 }
6703
6704 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006705
6706 /* as soon as a shutdown is reported the lower layer unregisters its
6707 * subscriber, so the situations below are transient and rare enough to
6708 * be reported as suspicious. In any case they shouldn't last.
6709 */
6710 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
6711 ret = 1;
6712 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
6713 ret = 1;
6714
Willy Tarreaude5675a2021-01-20 14:41:29 +01006715 chunk_appendf(&trash, " .subs=%p", sctx->subs);
6716 if (sctx->subs) {
6717 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006718 if (sctx->subs->tasklet->calls >= 1000000)
6719 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006720 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
6721 sctx->subs->tasklet->calls,
6722 sctx->subs->tasklet->context);
6723 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
6724 chunk_appendf(&trash, ")");
6725 }
6726 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
6727 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006728 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006729}
6730
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006731#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02006732/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006733 * each reference. The variable <ref> must point to the current node's list
6734 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02006735 */
William Lallemand32af2032016-10-29 18:09:35 +02006736static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006737struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02006738{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006739 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006740 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02006741
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006742 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006743 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006744 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02006745
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006746 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02006747}
6748
6749static inline
6750struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6751{
6752 int id;
6753 char *error;
6754
6755 /* If the reference starts by a '#', this is numeric id. */
6756 if (reference[0] == '#') {
6757 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6758 id = strtol(reference + 1, &error, 10);
6759 if (*error != '\0')
6760 return NULL;
6761
6762 /* Perform the unique id lookup. */
6763 return tlskeys_ref_lookupid(id);
6764 }
6765
6766 /* Perform the string lookup. */
6767 return tlskeys_ref_lookup(reference);
6768}
6769#endif
6770
6771
6772#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6773
6774static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6775
6776static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6777 return cli_io_handler_tlskeys_files(appctx);
6778}
6779
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006780/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6781 * (next index to be dumped), and cli.p0 (next key reference).
6782 */
William Lallemand32af2032016-10-29 18:09:35 +02006783static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6784
6785 struct stream_interface *si = appctx->owner;
6786
6787 switch (appctx->st2) {
6788 case STAT_ST_INIT:
6789 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006790 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006791 * later and restart at the state "STAT_ST_INIT".
6792 */
6793 chunk_reset(&trash);
6794
6795 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6796 chunk_appendf(&trash, "# id secret\n");
6797 else
6798 chunk_appendf(&trash, "# id (file)\n");
6799
Willy Tarreau06d80a92017-10-19 14:32:15 +02006800 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006801 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006802 return 0;
6803 }
6804
William Lallemand32af2032016-10-29 18:09:35 +02006805 /* Now, we start the browsing of the references lists.
6806 * Note that the following call to LIST_ELEM return bad pointer. The only
6807 * available field of this pointer is <list>. It is used with the function
6808 * tlskeys_list_get_next() for retruning the first available entry
6809 */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006810 if (appctx->ctx.cli.p0 == NULL)
6811 appctx->ctx.cli.p0 = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006812
6813 appctx->st2 = STAT_ST_LIST;
6814 /* fall through */
6815
6816 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006817 while (appctx->ctx.cli.p0) {
6818 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006819
6820 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006821 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006822 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006823
6824 if (appctx->ctx.cli.i1 == 0)
6825 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6826
William Lallemand32af2032016-10-29 18:09:35 +02006827 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006828 int head;
6829
6830 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6831 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006832 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006833 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006834
6835 chunk_reset(t2);
6836 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006837 if (ref->key_size_bits == 128) {
6838 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6839 sizeof(struct tls_sess_key_128),
6840 t2->area, t2->size);
6841 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6842 t2->area);
6843 }
6844 else if (ref->key_size_bits == 256) {
6845 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6846 sizeof(struct tls_sess_key_256),
6847 t2->area, t2->size);
6848 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6849 t2->area);
6850 }
6851 else {
6852 /* This case should never happen */
6853 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6854 }
William Lallemand32af2032016-10-29 18:09:35 +02006855
Willy Tarreau06d80a92017-10-19 14:32:15 +02006856 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006857 /* let's try again later from this stream. We add ourselves into
6858 * this stream's users so that it can remove us upon termination.
6859 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006860 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006861 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006862 return 0;
6863 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006864 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006865 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006866 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006867 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006868 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006869 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006870 /* let's try again later from this stream. We add ourselves into
6871 * this stream's users so that it can remove us upon termination.
6872 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006873 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006874 return 0;
6875 }
6876
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006877 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006878 break;
6879
6880 /* get next list entry and check the end of the list */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006881 appctx->ctx.cli.p0 = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006882 }
6883
6884 appctx->st2 = STAT_ST_FIN;
6885 /* fall through */
6886
6887 default:
6888 appctx->st2 = STAT_ST_FIN;
6889 return 1;
6890 }
6891 return 0;
6892}
6893
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006894/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006895static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006896{
William Lallemand32af2032016-10-29 18:09:35 +02006897 /* no parameter, shows only file list */
6898 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006899 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006900 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006901 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006902 }
6903
6904 if (args[2][0] == '*') {
6905 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006906 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006907 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006908 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006909 if (!appctx->ctx.cli.p0)
6910 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006911 }
William Lallemand32af2032016-10-29 18:09:35 +02006912 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006913 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006914}
6915
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006916static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006917{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006918 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006919 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006920
William Lallemand32af2032016-10-29 18:09:35 +02006921 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006922 if (!*args[3] || !*args[4])
6923 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 +02006924
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006925 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006926 if (!ref)
6927 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006928
Willy Tarreau1c913e42018-08-22 05:26:57 +02006929 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006930 if (ret < 0)
6931 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006932
Willy Tarreau1c913e42018-08-22 05:26:57 +02006933 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006934 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6935 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006936
Willy Tarreau9d008692019-08-09 11:21:01 +02006937 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006938}
William Lallemandd4f946c2019-12-05 10:26:40 +01006939#endif
William Lallemand419e6342020-04-08 12:05:39 +02006940
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006941static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006942{
6943#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6944 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006945 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006946
6947 if (!payload)
6948 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006949
6950 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006951 if (!*payload)
6952 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006953
6954 /* remove \r and \n from the payload */
6955 for (i = 0, j = 0; payload[i]; i++) {
6956 if (payload[i] == '\r' || payload[i] == '\n')
6957 continue;
6958 payload[j++] = payload[i];
6959 }
6960 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006961
Willy Tarreau1c913e42018-08-22 05:26:57 +02006962 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006963 if (ret < 0)
6964 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006965
Willy Tarreau1c913e42018-08-22 05:26:57 +02006966 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02006967 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02006968 if (err)
6969 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
6970 else
6971 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006972 }
Willy Tarreau9d008692019-08-09 11:21:01 +02006973
6974 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006975#else
Willy Tarreau9d008692019-08-09 11:21:01 +02006976 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 +02006977#endif
6978
Elliot Otchet71f82972020-01-15 08:12:14 -05006979}
6980
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02006981
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02006982#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02006983static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx);
6984#endif
6985
6986/* parsing function for 'show ssl ocsp-response [id]' */
6987static int cli_parse_show_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
6988{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02006989#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02006990 if (*args[3]) {
6991 struct certificate_ocsp *ocsp = NULL;
6992 char *key = NULL;
6993 int key_length = 0;
6994
6995 if (strlen(args[3]) > OCSP_MAX_CERTID_ASN1_LENGTH*2) {
6996 return cli_err(appctx, "'show ssl ocsp-response' received a too big key.\n");
6997 }
6998
6999 if (parse_binary(args[3], &key, &key_length, NULL)) {
7000
7001 char full_key[OCSP_MAX_CERTID_ASN1_LENGTH] = {};
7002 memcpy(full_key, key, key_length);
7003
7004 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, full_key, OCSP_MAX_CERTID_ASN1_LENGTH);
7005 }
7006 if (key)
7007 ha_free(&key);
7008
7009 if (!ocsp) {
7010 return cli_err(appctx, "Certificate ID does not match any certificate.\n");
7011 }
7012
7013 appctx->ctx.cli.p0 = ocsp;
7014 appctx->io_handler = cli_io_handler_show_ocspresponse_detail;
7015 }
7016
7017 return 0;
7018
7019#else
7020 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7021#endif
7022}
7023
7024
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007025#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007026/*
7027 * This function dumps the details of an OCSP_CERTID. It is based on
7028 * ocsp_certid_print in OpenSSL.
7029 */
7030static inline int ocsp_certid_print(BIO *bp, OCSP_CERTID *certid, int indent)
7031{
7032 ASN1_OCTET_STRING *piNameHash = NULL;
7033 ASN1_OCTET_STRING *piKeyHash = NULL;
7034 ASN1_INTEGER *pSerial = NULL;
7035
7036 if (OCSP_id_get0_info(&piNameHash, NULL, &piKeyHash, &pSerial, certid)) {
7037
7038 BIO_printf(bp, "%*sCertificate ID:\n", indent, "");
7039 indent += 2;
7040 BIO_printf(bp, "\n%*sIssuer Name Hash: ", indent, "");
7041 i2a_ASN1_STRING(bp, piNameHash, 0);
7042 BIO_printf(bp, "\n%*sIssuer Key Hash: ", indent, "");
7043 i2a_ASN1_STRING(bp, piKeyHash, 0);
7044 BIO_printf(bp, "\n%*sSerial Number: ", indent, "");
7045 i2a_ASN1_INTEGER(bp, pSerial);
7046 BIO_printf(bp, "\n");
7047 }
7048 return 1;
7049}
7050#endif
7051
7052/*
7053 * IO handler of "show ssl ocsp-response". The command taking a specific ID
7054 * is managed in cli_io_handler_show_ocspresponse_detail.
7055 */
7056static int cli_io_handler_show_ocspresponse(struct appctx *appctx)
7057{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007058#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007059 struct buffer *trash = alloc_trash_chunk();
7060 struct buffer *tmp = NULL;
7061 struct ebmb_node *node;
7062 struct stream_interface *si = appctx->owner;
7063 struct certificate_ocsp *ocsp = NULL;
7064 BIO *bio = NULL;
7065 int write = -1;
7066
7067 if (trash == NULL)
7068 return 1;
7069
7070 tmp = alloc_trash_chunk();
7071 if (!tmp)
7072 goto end;
7073
7074 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7075 goto end;
7076
7077 if (!appctx->ctx.cli.p0) {
7078 chunk_appendf(trash, "# Certificate IDs\n");
7079 node = ebmb_first(&cert_ocsp_tree);
7080 } else {
7081 node = &((struct certificate_ocsp *)appctx->ctx.cli.p0)->key;
7082 }
7083
7084 while (node) {
7085 OCSP_CERTID *certid = NULL;
7086 const unsigned char *p = NULL;
7087 int i;
7088
7089 ocsp = ebmb_entry(node, struct certificate_ocsp, key);
7090
7091 /* Dump the key in hexadecimal */
7092 chunk_appendf(trash, "Certificate ID key : ");
7093 for (i = 0; i < ocsp->key_length; ++i) {
7094 chunk_appendf(trash, "%02x", ocsp->key_data[i]);
7095 }
7096 chunk_appendf(trash, "\n");
7097
7098 p = ocsp->key_data;
7099
7100 /* Decode the certificate ID (serialized into the key). */
7101 d2i_OCSP_CERTID(&certid, &p, ocsp->key_length);
7102
7103 /* Dump the CERTID info */
7104 ocsp_certid_print(bio, certid, 1);
7105 write = BIO_read(bio, tmp->area, tmp->size-1);
7106 tmp->area[write] = '\0';
7107
7108 chunk_appendf(trash, "%s\n", tmp->area);
7109
7110 node = ebmb_next(node);
7111 if (ci_putchk(si_ic(si), trash) == -1) {
7112 si_rx_room_blk(si);
7113 goto yield;
7114 }
7115 }
7116
7117end:
7118 appctx->ctx.cli.p0 = NULL;
7119 if (trash)
7120 free_trash_chunk(trash);
7121 if (tmp)
7122 free_trash_chunk(tmp);
7123 if (bio)
7124 BIO_free(bio);
7125 return 1;
7126
7127yield:
7128
7129 if (trash)
7130 free_trash_chunk(trash);
7131 if (tmp)
7132 free_trash_chunk(tmp);
7133 if (bio)
7134 BIO_free(bio);
7135 appctx->ctx.cli.p0 = ocsp;
7136 return 0;
7137#else
7138 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7139#endif
7140}
7141
7142
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007143#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007144/*
7145 * Dump the details about an OCSP response in DER format stored in
7146 * <ocsp_response> into buffer <out>.
7147 * Returns 0 in case of success.
7148 */
7149int ssl_ocsp_response_print(struct buffer *ocsp_response, struct buffer *out)
7150{
7151 BIO *bio = NULL;
7152 int write = -1;
7153 OCSP_RESPONSE *resp;
7154 const unsigned char *p;
7155
7156 if (!ocsp_response)
7157 return -1;
7158
7159 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7160 return -1;
7161
7162 p = (const unsigned char*)ocsp_response->area;
7163
7164 resp = d2i_OCSP_RESPONSE(NULL, &p, ocsp_response->data);
7165 if (!resp) {
7166 chunk_appendf(out, "Unable to parse OCSP response");
7167 return -1;
7168 }
7169
7170 if (OCSP_RESPONSE_print(bio, resp, 0) != 0) {
7171 write = BIO_read(bio, out->area, out->size - 1);
7172 out->area[write] = '\0';
7173 out->data = write;
7174 }
7175
7176 if (bio)
7177 BIO_free(bio);
7178
7179 return 0;
7180}
7181
7182/*
7183 * Dump the details of the OCSP response of ID <ocsp_certid> into buffer <out>.
7184 * Returns 0 in case of success.
7185 */
7186int ssl_get_ocspresponse_detail(unsigned char *ocsp_certid, struct buffer *out)
7187{
7188 struct certificate_ocsp *ocsp;
7189
7190 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, ocsp_certid, OCSP_MAX_CERTID_ASN1_LENGTH);
7191 if (!ocsp)
7192 return -1;
7193
7194 return ssl_ocsp_response_print(&ocsp->response, out);
7195}
7196
7197
7198/* IO handler of details "show ssl ocsp-response <id>". */
7199static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx)
7200{
7201 struct buffer *trash = alloc_trash_chunk();
7202 struct certificate_ocsp *ocsp = NULL;
7203 struct stream_interface *si = appctx->owner;
7204
7205 ocsp = appctx->ctx.cli.p0;
7206
7207 if (trash == NULL)
7208 return 1;
7209
7210 ssl_ocsp_response_print(&ocsp->response, trash);
7211
7212 if (ci_putchk(si_ic(si), trash) == -1) {
7213 si_rx_room_blk(si);
7214 goto yield;
7215 }
7216 appctx->ctx.cli.p0 = NULL;
7217 if (trash)
7218 free_trash_chunk(trash);
7219 return 1;
7220
7221yield:
7222 if (trash)
7223 free_trash_chunk(trash);
7224
7225 return 0;
7226}
7227#endif
7228
William Lallemand32af2032016-10-29 18:09:35 +02007229/* register cli keywords */
7230static struct cli_kw_list cli_kws = {{ },{
7231#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007232 { { "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 },
7233 { { "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 +02007234#endif
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007235 { { "set", "ssl", "ocsp-response", NULL }, "set ssl ocsp-response <resp|payload> : update a certificate's OCSP Response from a base64-encode DER", cli_parse_set_ocspresponse, NULL },
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007236
7237 { { "show", "ssl", "ocsp-response", NULL },"show ssl ocsp-response [id] : display the IDs of the OCSP responses used in memory, or the details of a single OCSP response", cli_parse_show_ocspresponse, cli_io_handler_show_ocspresponse, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02007238 { { NULL }, NULL, NULL, NULL }
7239}};
7240
Willy Tarreau0108d902018-11-25 19:14:37 +01007241INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007242
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007243/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007244struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007245 .snd_buf = ssl_sock_from_buf,
7246 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007247 .subscribe = ssl_subscribe,
7248 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007249 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007250 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007251 .rcv_pipe = NULL,
7252 .snd_pipe = NULL,
7253 .shutr = NULL,
7254 .shutw = ssl_sock_shutw,
7255 .close = ssl_sock_close,
7256 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007257 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007258 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007259 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007260 .prepare_srv = ssl_sock_prepare_srv_ctx,
7261 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007262 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007263 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007264 .set_idle = ssl_set_idle,
7265 .set_used = ssl_set_used,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007266 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007267 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007268};
7269
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007270enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7271 struct session *sess, struct stream *s, int flags)
7272{
7273 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007274 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007275
7276 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007277 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007278
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007279 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007280 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007281 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007282 s->req.flags |= CF_READ_NULL;
7283 return ACT_RET_YIELD;
7284 }
7285 }
7286 return (ACT_RET_CONT);
7287}
7288
7289static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7290{
7291 rule->action_ptr = ssl_action_wait_for_hs;
7292
7293 return ACT_RET_PRS_OK;
7294}
7295
7296static struct action_kw_list http_req_actions = {ILH, {
7297 { "wait-for-handshake", ssl_parse_wait_for_hs },
7298 { /* END */ }
7299}};
7300
Willy Tarreau0108d902018-11-25 19:14:37 +01007301INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7302
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007303#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007304
7305static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7306{
7307 if (ptr) {
7308 chunk_destroy(ptr);
7309 free(ptr);
7310 }
7311}
7312
7313#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007314
7315#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7316static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7317{
7318 struct ocsp_cbk_arg *ocsp_arg;
7319
7320 if (ptr) {
7321 ocsp_arg = ptr;
7322
7323 if (ocsp_arg->is_single) {
7324 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
7325 ocsp_arg->s_ocsp = NULL;
7326 } else {
7327 int i;
7328
7329 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
7330 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
7331 ocsp_arg->m_ocsp[i] = NULL;
7332 }
7333 }
7334 free(ocsp_arg);
7335 }
7336}
7337#endif
7338
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007339static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7340{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007341 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007342}
William Lallemand7d42ef52020-07-06 11:41:30 +02007343
William Lallemand722180a2021-06-09 16:46:12 +02007344#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007345static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7346{
7347 struct ssl_keylog *keylog;
7348
7349 if (!ptr)
7350 return;
7351
7352 keylog = ptr;
7353
7354 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7355 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7356 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7357 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7358 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7359 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7360 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7361 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7362
7363 pool_free(pool_head_ssl_keylog, ptr);
7364}
7365#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007366
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007367static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7368{
7369 if (!ptr)
7370 return;
7371
7372 X509_free((X509*)ptr);
7373}
7374
Emeric Brun46591952012-05-18 15:47:34 +02007375__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02007376static void __ssl_sock_init(void)
7377{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007378#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007379 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007380 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007381#endif
Emeric Brun46591952012-05-18 15:47:34 +02007382
Willy Tarreauef934602016-12-22 23:12:01 +01007383 if (global_ssl.listen_default_ciphers)
7384 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7385 if (global_ssl.connect_default_ciphers)
7386 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007387#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007388 if (global_ssl.listen_default_ciphersuites)
7389 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7390 if (global_ssl.connect_default_ciphersuites)
7391 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7392#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007393
Willy Tarreau13e14102016-12-22 20:25:26 +01007394 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007395#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007396 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007397#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007398#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007399 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007400 n = sk_SSL_COMP_num(cm);
7401 while (n--) {
7402 (void) sk_SSL_COMP_pop(cm);
7403 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007404#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007405
Willy Tarreau5db847a2019-05-09 14:13:35 +02007406#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007407 ssl_locking_init();
7408#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007409#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007410 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7411#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007412
7413#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7414 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7415#endif
7416
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007417 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007418 ssl_capture_ptr_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_capture_free_func);
William Lallemand722180a2021-06-09 16:46:12 +02007419#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007420 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7421#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007422 ssl_client_crt_ref_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_clt_crt_free_func);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007423#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007424 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007425 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007426#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007427#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7428 hap_register_post_check(tlskeys_finalize_config);
7429#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007430
7431 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7432 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7433
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007434 hap_register_post_deinit(ssl_free_global_issuers);
7435
Willy Tarreau80713382018-11-26 10:19:54 +01007436#ifndef OPENSSL_NO_DH
7437 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7438 hap_register_post_deinit(ssl_free_dh);
7439#endif
7440#ifndef OPENSSL_NO_ENGINE
7441 hap_register_post_deinit(ssl_free_engines);
7442#endif
7443 /* Load SSL string for the verbose & debug mode. */
7444 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02007445 ha_meth = BIO_meth_new(0x666, "ha methods");
7446 BIO_meth_set_write(ha_meth, ha_ssl_write);
7447 BIO_meth_set_read(ha_meth, ha_ssl_read);
7448 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7449 BIO_meth_set_create(ha_meth, ha_ssl_new);
7450 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7451 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7452 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007453
7454 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007455
Dragan Dosen9ac98092020-05-11 15:51:45 +02007456 /* Try to register dedicated SSL/TLS protocol message callbacks for
7457 * heartbleed attack (CVE-2014-0160) and clienthello.
7458 */
7459 hap_register_post_check(ssl_sock_register_msg_callbacks);
7460
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007461 /* Try to free all callbacks that were registered by using
7462 * ssl_sock_register_msg_callback().
7463 */
7464 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007465}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007466
Willy Tarreau80713382018-11-26 10:19:54 +01007467/* Compute and register the version string */
7468static void ssl_register_build_options()
7469{
7470 char *ptr = NULL;
7471 int i;
7472
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007473 memprintf(&ptr, "Built with OpenSSL version : "
7474#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007475 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007476#else /* OPENSSL_IS_BORINGSSL */
7477 OPENSSL_VERSION_TEXT
7478 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007479 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007480 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007481#endif
7482 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007483#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007484 "no (library version too old)"
7485#elif defined(OPENSSL_NO_TLSEXT)
7486 "no (disabled via OPENSSL_NO_TLSEXT)"
7487#else
7488 "yes"
7489#endif
7490 "", ptr);
7491
7492 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7493#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7494 "yes"
7495#else
7496#ifdef OPENSSL_NO_TLSEXT
7497 "no (because of OPENSSL_NO_TLSEXT)"
7498#else
7499 "no (version might be too old, 0.9.8f min needed)"
7500#endif
7501#endif
7502 "", ptr);
7503
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007504 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7505 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7506 if (methodVersions[i].option)
7507 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007508
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007509 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007510}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007511
Willy Tarreau80713382018-11-26 10:19:54 +01007512INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007513
Emeric Brun46591952012-05-18 15:47:34 +02007514
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007515#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007516void ssl_free_engines(void) {
7517 struct ssl_engine_list *wl, *wlb;
7518 /* free up engine list */
7519 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7520 ENGINE_finish(wl->e);
7521 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007522 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007523 free(wl);
7524 }
7525}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007526#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007527
Remi Gacogned3a23c32015-05-28 16:39:47 +02007528#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007529void ssl_free_dh(void) {
7530 if (local_dh_1024) {
7531 DH_free(local_dh_1024);
7532 local_dh_1024 = NULL;
7533 }
7534 if (local_dh_2048) {
7535 DH_free(local_dh_2048);
7536 local_dh_2048 = NULL;
7537 }
7538 if (local_dh_4096) {
7539 DH_free(local_dh_4096);
7540 local_dh_4096 = NULL;
7541 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007542 if (global_dh) {
7543 DH_free(global_dh);
7544 global_dh = NULL;
7545 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007546}
7547#endif
7548
7549__attribute__((destructor))
7550static void __ssl_sock_deinit(void)
7551{
7552#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007553 if (ssl_ctx_lru_tree) {
7554 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007555 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007556 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007557#endif
7558
Willy Tarreau5db847a2019-05-09 14:13:35 +02007559#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007560 ERR_remove_state(0);
7561 ERR_free_strings();
7562
7563 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007564#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007565
Willy Tarreau5db847a2019-05-09 14:13:35 +02007566#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007567 CRYPTO_cleanup_all_ex_data();
7568#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007569 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007570}
7571
William Dauchyf6370442020-11-14 19:25:33 +01007572/* Activate ssl on server <s>.
7573 * do nothing if there is no change to apply
7574 *
7575 * Must be called with the server lock held.
7576 */
7577void ssl_sock_set_srv(struct server *s, signed char use_ssl)
7578{
7579 if (s->use_ssl == use_ssl)
7580 return;
7581
7582 s->use_ssl = use_ssl;
7583 if (s->use_ssl == 1)
7584 s->xprt = &ssl_sock;
7585 else
7586 s->xprt = s->check.xprt = s->agent.xprt = xprt_get(XPRT_RAW);
7587}
7588
Emeric Brun46591952012-05-18 15:47:34 +02007589/*
7590 * Local variables:
7591 * c-indent-level: 8
7592 * c-basic-offset: 8
7593 * End:
7594 */