blob: 3b92ec130f4e1c7a81cb8dbdc48ee49a73d2a7d5 [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
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200446#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
447struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
448#endif
449
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200450#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200451unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000452struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
453struct ssl_engine_list {
454 struct list list;
455 ENGINE *e;
456};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200457#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000458
Remi Gacogne8de54152014-07-15 11:36:40 +0200459#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200460static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200461static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200462static DH *local_dh_1024 = NULL;
463static DH *local_dh_2048 = NULL;
464static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100465static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200466#endif /* OPENSSL_NO_DH */
467
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100468#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200469/* X509V3 Extensions that will be added on generated certificates */
470#define X509V3_EXT_SIZE 5
471static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
472 "basicConstraints",
473 "nsComment",
474 "subjectKeyIdentifier",
475 "authorityKeyIdentifier",
476 "keyUsage",
477};
478static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
479 "CA:FALSE",
480 "\"OpenSSL Generated Certificate\"",
481 "hash",
482 "keyid,issuer:always",
483 "nonRepudiation,digitalSignature,keyEncipherment"
484};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200485/* LRU cache to store generated certificate */
486static struct lru64_head *ssl_ctx_lru_tree = NULL;
487static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200488static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100489__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200490
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200491#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
492
yanbzhube2774d2015-12-10 15:07:30 -0500493/* The order here matters for picking a default context,
494 * keep the most common keytype at the bottom of the list
495 */
496const char *SSL_SOCK_KEYTYPE_NAMES[] = {
497 "dsa",
498 "ecdsa",
499 "rsa"
500};
yanbzhube2774d2015-12-10 15:07:30 -0500501
William Lallemandc3cd35f2017-11-28 11:04:43 +0100502static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100503static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
504
Dragan Dosen9ac98092020-05-11 15:51:45 +0200505/* Dedicated callback functions for heartbeat and clienthello.
506 */
507#ifdef TLS1_RT_HEARTBEAT
508static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
509 int content_type, const void *buf, size_t len,
510 SSL *ssl);
511#endif
512static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
513 int content_type, const void *buf, size_t len,
514 SSL *ssl);
515
William Lallemand722180a2021-06-09 16:46:12 +0200516#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200517static void ssl_init_keylog(struct connection *conn, int write_p, int version,
518 int content_type, const void *buf, size_t len,
519 SSL *ssl);
520#endif
521
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200522/* List head of all registered SSL/TLS protocol message callbacks. */
523struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
524
525/* Registers the function <func> in order to be called on SSL/TLS protocol
526 * message processing. It will return 0 if the function <func> is not set
527 * or if it fails to allocate memory.
528 */
529int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
530{
531 struct ssl_sock_msg_callback *cbk;
532
533 if (!func)
534 return 0;
535
536 cbk = calloc(1, sizeof(*cbk));
537 if (!cbk) {
538 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
539 return 0;
540 }
541
542 cbk->func = func;
543
Willy Tarreau2b718102021-04-21 07:32:39 +0200544 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200545
546 return 1;
547}
548
Dragan Dosen9ac98092020-05-11 15:51:45 +0200549/* Used to register dedicated SSL/TLS protocol message callbacks.
550 */
551static int ssl_sock_register_msg_callbacks(void)
552{
553#ifdef TLS1_RT_HEARTBEAT
554 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
555 return ERR_ABORT;
556#endif
557 if (global_ssl.capture_cipherlist > 0) {
558 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
559 return ERR_ABORT;
560 }
William Lallemand722180a2021-06-09 16:46:12 +0200561#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200562 if (global_ssl.keylog > 0) {
563 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
564 return ERR_ABORT;
565 }
566#endif
567
Christopher Fauletfc633b62020-11-06 15:24:23 +0100568 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200569}
570
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200571/* Used to free all SSL/TLS protocol message callbacks that were
572 * registered by using ssl_sock_register_msg_callback().
573 */
574static void ssl_sock_unregister_msg_callbacks(void)
575{
576 struct ssl_sock_msg_callback *cbk, *cbkback;
577
578 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200579 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200580 free(cbk);
581 }
582}
583
Dragan Doseneb607fe2020-05-11 17:17:06 +0200584SSL *ssl_sock_get_ssl_object(struct connection *conn)
585{
586 if (!ssl_sock_is_ssl(conn))
587 return NULL;
588
589 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
590}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100591/*
592 * This function gives the detail of the SSL error. It is used only
593 * if the debug mode and the verbose mode are activated. It dump all
594 * the SSL error until the stack was empty.
595 */
596static forceinline void ssl_sock_dump_errors(struct connection *conn)
597{
598 unsigned long ret;
599
600 if (unlikely(global.mode & MODE_DEBUG)) {
601 while(1) {
602 ret = ERR_get_error();
603 if (ret == 0)
604 return;
Willy Tarreau566cebc2021-03-02 19:32:39 +0100605 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
606 conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100607 ERR_func_error_string(ret), ERR_reason_error_string(ret));
608 }
609 }
610}
611
yanbzhube2774d2015-12-10 15:07:30 -0500612
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200613#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200614int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000615{
616 int err_code = ERR_ABORT;
617 ENGINE *engine;
618 struct ssl_engine_list *el;
619
620 /* grab the structural reference to the engine */
621 engine = ENGINE_by_id(engine_id);
622 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100623 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000624 goto fail_get;
625 }
626
627 if (!ENGINE_init(engine)) {
628 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100629 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000630 goto fail_init;
631 }
632
633 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100634 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000635 goto fail_set_method;
636 }
637
638 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200639 if (!el)
640 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000641 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200642 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100643 nb_engines++;
644 if (global_ssl.async)
645 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000646 return 0;
647
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200648fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000649fail_set_method:
650 /* release the functional reference from ENGINE_init() */
651 ENGINE_finish(engine);
652
653fail_init:
654 /* release the structural reference from ENGINE_by_id() */
655 ENGINE_free(engine);
656
657fail_get:
658 return err_code;
659}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200660#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000661
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500662#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200663/*
664 * openssl async fd handler
665 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200666void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000667{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200668 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000669
Emeric Brun3854e012017-05-17 20:42:48 +0200670 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000671 * to poll this fd until it is requested
672 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000673 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000674 fd_cant_recv(fd);
675
676 /* crypto engine is available, let's notify the associated
677 * connection that it can pursue its processing.
678 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200679 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000680}
681
Emeric Brun3854e012017-05-17 20:42:48 +0200682/*
683 * openssl async delayed SSL_free handler
684 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200685void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000686{
687 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200688 OSSL_ASYNC_FD all_fd[32];
689 size_t num_all_fds = 0;
690 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000691
Emeric Brun3854e012017-05-17 20:42:48 +0200692 /* We suppose that the async job for a same SSL *
693 * are serialized. So if we are awake it is
694 * because the running job has just finished
695 * and we can remove all async fds safely
696 */
697 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
698 if (num_all_fds > 32) {
699 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
700 return;
701 }
702
703 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
704 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200705 fd_stop_both(all_fd[i]);
Emeric Brun3854e012017-05-17 20:42:48 +0200706
707 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000708 SSL_free(ssl);
Willy Tarreau4781b152021-04-06 13:53:36 +0200709 _HA_ATOMIC_DEC(&sslconns);
710 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000711}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000712/*
Emeric Brun3854e012017-05-17 20:42:48 +0200713 * function used to manage a returned SSL_ERROR_WANT_ASYNC
714 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000715 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200716static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000717{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100718 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200719 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200720 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000721 size_t num_add_fds = 0;
722 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200723 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000724
725 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
726 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200727 if (num_add_fds > 32 || num_del_fds > 32) {
728 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 +0000729 return;
730 }
731
Emeric Brun3854e012017-05-17 20:42:48 +0200732 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000733
Emeric Brun3854e012017-05-17 20:42:48 +0200734 /* We remove unused fds from the fdtab */
735 for (i=0 ; i < num_del_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200736 fd_stop_both(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000737
Emeric Brun3854e012017-05-17 20:42:48 +0200738 /* We add new fds to the fdtab */
739 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200740 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000741 }
742
Emeric Brun3854e012017-05-17 20:42:48 +0200743 num_add_fds = 0;
744 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
745 if (num_add_fds > 32) {
746 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
747 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000748 }
Emeric Brun3854e012017-05-17 20:42:48 +0200749
750 /* We activate the polling for all known async fds */
751 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000752 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200753 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000754 /* To ensure that the fd cache won't be used
755 * We'll prefer to catch a real RD event
756 * because handling an EAGAIN on this fd will
757 * result in a context switch and also
758 * some engines uses a fd in blocking mode.
759 */
760 fd_cant_recv(add_fd[i]);
761 }
Emeric Brun3854e012017-05-17 20:42:48 +0200762
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000763}
764#endif
765
William Lallemand104a7a62019-10-14 14:14:59 +0200766#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200767/*
768 * This function returns the number of seconds elapsed
769 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
770 * date presented un ASN1_GENERALIZEDTIME.
771 *
772 * In parsing error case, it returns -1.
773 */
774static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
775{
776 long epoch;
777 char *p, *end;
778 const unsigned short month_offset[12] = {
779 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
780 };
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +0200781 unsigned long year, month;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200782
783 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
784
785 p = (char *)d->data;
786 end = p + d->length;
787
788 if (end - p < 4) return -1;
789 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
790 p += 4;
791 if (end - p < 2) return -1;
792 month = 10 * (p[0] - '0') + p[1] - '0';
793 if (month < 1 || month > 12) return -1;
794 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
795 We consider leap years and the current month (<marsh or not) */
796 epoch = ( ((year - 1970) * 365)
797 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
798 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
799 + month_offset[month-1]
800 ) * 24 * 60 * 60;
801 p += 2;
802 if (end - p < 2) return -1;
803 /* Add the number of seconds of completed days of current month */
804 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
805 p += 2;
806 if (end - p < 2) return -1;
807 /* Add the completed hours of the current day */
808 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
809 p += 2;
810 if (end - p < 2) return -1;
811 /* Add the completed minutes of the current hour */
812 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
813 p += 2;
814 if (p == end) return -1;
815 /* Test if there is available seconds */
816 if (p[0] < '0' || p[0] > '9')
817 goto nosec;
818 if (end - p < 2) return -1;
819 /* Add the seconds of the current minute */
820 epoch += 10 * (p[0] - '0') + p[1] - '0';
821 p += 2;
822 if (p == end) return -1;
823 /* Ignore seconds float part if present */
824 if (p[0] == '.') {
825 do {
826 if (++p == end) return -1;
827 } while (p[0] >= '0' && p[0] <= '9');
828 }
829
830nosec:
831 if (p[0] == 'Z') {
832 if (end - p != 1) return -1;
833 return epoch;
834 }
835 else if (p[0] == '+') {
836 if (end - p != 5) return -1;
837 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700838 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 +0200839 }
840 else if (p[0] == '-') {
841 if (end - p != 5) return -1;
842 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700843 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 +0200844 }
845
846 return -1;
847}
848
William Lallemand104a7a62019-10-14 14:14:59 +0200849/*
850 * struct alignment works here such that the key.key is the same as key_data
851 * Do not change the placement of key_data
852 */
853struct certificate_ocsp {
854 struct ebmb_node key;
855 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
856 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200857 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200858 long expire;
859};
860
861struct ocsp_cbk_arg {
862 int is_single;
863 int single_kt;
864 union {
865 struct certificate_ocsp *s_ocsp;
866 /*
867 * m_ocsp will have multiple entries dependent on key type
868 * Entry 0 - DSA
869 * Entry 1 - ECDSA
870 * Entry 2 - RSA
871 */
872 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
873 };
874};
875
Emeric Brun1d3865b2014-06-20 15:37:32 +0200876static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200877
878/* This function starts to check if the OCSP response (in DER format) contained
879 * in chunk 'ocsp_response' is valid (else exits on error).
880 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
881 * contained in the OCSP Response and exits on error if no match.
882 * If it's a valid OCSP Response:
883 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
884 * pointed by 'ocsp'.
885 * If 'ocsp' is NULL, the function looks up into the OCSP response's
886 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
887 * from the response) and exits on error if not found. Finally, If an OCSP response is
888 * already present in the container, it will be overwritten.
889 *
890 * Note: OCSP response containing more than one OCSP Single response is not
891 * considered valid.
892 *
893 * Returns 0 on success, 1 in error case.
894 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200895static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
896 struct certificate_ocsp *ocsp,
897 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200898{
899 OCSP_RESPONSE *resp;
900 OCSP_BASICRESP *bs = NULL;
901 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200902 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200903 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200904 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200905 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200906 int reason;
907 int ret = 1;
908
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200909 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
910 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200911 if (!resp) {
912 memprintf(err, "Unable to parse OCSP response");
913 goto out;
914 }
915
916 rc = OCSP_response_status(resp);
917 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
918 memprintf(err, "OCSP response status not successful");
919 goto out;
920 }
921
922 bs = OCSP_response_get1_basic(resp);
923 if (!bs) {
924 memprintf(err, "Failed to get basic response from OCSP Response");
925 goto out;
926 }
927
928 count_sr = OCSP_resp_count(bs);
929 if (count_sr > 1) {
930 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
931 goto out;
932 }
933
934 sr = OCSP_resp_get0(bs, 0);
935 if (!sr) {
936 memprintf(err, "Failed to get OCSP single response");
937 goto out;
938 }
939
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200940 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
941
Emeric Brun4147b2e2014-06-16 18:36:30 +0200942 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200943 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200944 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200945 goto out;
946 }
947
Emeric Brun13a6b482014-06-20 15:44:34 +0200948 if (!nextupd) {
949 memprintf(err, "OCSP single response: missing nextupdate");
950 goto out;
951 }
952
Emeric Brunc8b27b62014-06-19 14:16:17 +0200953 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200954 if (!rc) {
955 memprintf(err, "OCSP single response: no longer valid.");
956 goto out;
957 }
958
959 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200960 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +0200961 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
962 goto out;
963 }
964 }
965
966 if (!ocsp) {
967 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
968 unsigned char *p;
969
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200970 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200971 if (!rc) {
972 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
973 goto out;
974 }
975
976 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
977 memprintf(err, "OCSP single response: Certificate ID too long");
978 goto out;
979 }
980
981 p = key;
982 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200983 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200984 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
985 if (!ocsp) {
986 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
987 goto out;
988 }
989 }
990
991 /* According to comments on "chunk_dup", the
992 previous chunk buffer will be freed */
993 if (!chunk_dup(&ocsp->response, ocsp_response)) {
994 memprintf(err, "OCSP response: Memory allocation error");
995 goto out;
996 }
997
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200998 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +0200999 if (ocsp->expire < 0) {
1000 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1001 goto out;
1002 }
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001003
Emeric Brun4147b2e2014-06-16 18:36:30 +02001004 ret = 0;
1005out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001006 ERR_clear_error();
1007
Emeric Brun4147b2e2014-06-16 18:36:30 +02001008 if (bs)
1009 OCSP_BASICRESP_free(bs);
1010
1011 if (resp)
1012 OCSP_RESPONSE_free(resp);
1013
1014 return ret;
1015}
1016/*
1017 * External function use to update the OCSP response in the OCSP response's
1018 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1019 * to update in DER format.
1020 *
1021 * Returns 0 on success, 1 in error case.
1022 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001023int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001024{
1025 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1026}
1027
William Lallemand4a660132019-10-14 14:51:41 +02001028#endif
1029
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001030#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1031static 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)
1032{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001033 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001034 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001035 struct connection *conn;
1036 int head;
1037 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001038 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001039
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001040 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001041 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001042 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1043
1044 keys = ref->tlskeys;
1045 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001046
1047 if (enc) {
1048 memcpy(key_name, keys[head].name, 16);
1049
1050 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001051 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001052
Emeric Brun9e754772019-01-10 17:51:55 +01001053 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001054
Emeric Brun9e754772019-01-10 17:51:55 +01001055 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1056 goto end;
1057
Willy Tarreau9356dac2019-05-10 09:22:53 +02001058 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001059 ret = 1;
1060 }
1061 else if (ref->key_size_bits == 256 ) {
1062
1063 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1064 goto end;
1065
Willy Tarreau9356dac2019-05-10 09:22:53 +02001066 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001067 ret = 1;
1068 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001069 } else {
1070 for (i = 0; i < TLS_TICKETS_NO; i++) {
1071 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1072 goto found;
1073 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001074 ret = 0;
1075 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001076
Christopher Faulet16f45c82018-02-16 11:23:49 +01001077 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001078 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001079 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 +01001080 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1081 goto end;
1082 /* 2 for key renewal, 1 if current key is still valid */
1083 ret = i ? 2 : 1;
1084 }
1085 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001086 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 +01001087 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1088 goto end;
1089 /* 2 for key renewal, 1 if current key is still valid */
1090 ret = i ? 2 : 1;
1091 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001092 }
Emeric Brun9e754772019-01-10 17:51:55 +01001093
Christopher Faulet16f45c82018-02-16 11:23:49 +01001094 end:
1095 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1096 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001097}
1098
1099struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1100{
1101 struct tls_keys_ref *ref;
1102
1103 list_for_each_entry(ref, &tlskeys_reference, list)
1104 if (ref->filename && strcmp(filename, ref->filename) == 0)
1105 return ref;
1106 return NULL;
1107}
1108
1109struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1110{
1111 struct tls_keys_ref *ref;
1112
1113 list_for_each_entry(ref, &tlskeys_reference, list)
1114 if (ref->unique_id == unique_id)
1115 return ref;
1116 return NULL;
1117}
1118
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001119/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001120 * match existing ones, this function returns -1
1121 * else it returns 0 on success.
1122 */
1123int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001124 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001125{
Emeric Brun9e754772019-01-10 17:51:55 +01001126 if (ref->key_size_bits == 128) {
1127 if (tlskey->data != sizeof(struct tls_sess_key_128))
1128 return -1;
1129 }
1130 else if (ref->key_size_bits == 256) {
1131 if (tlskey->data != sizeof(struct tls_sess_key_256))
1132 return -1;
1133 }
1134 else
1135 return -1;
1136
Christopher Faulet16f45c82018-02-16 11:23:49 +01001137 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001138 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1139 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001140 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1141 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001142
1143 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001144}
1145
Willy Tarreau83061a82018-07-13 11:56:34 +02001146int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001147{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001148 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1149
1150 if(!ref) {
1151 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1152 return 1;
1153 }
Emeric Brun9e754772019-01-10 17:51:55 +01001154 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1155 memprintf(err, "Invalid key size");
1156 return 1;
1157 }
1158
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001159 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001160}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001161
1162/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001163 * automatic ids. It's called just after the basic checks. It returns
1164 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001165 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001166static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001167{
1168 int i = 0;
1169 struct tls_keys_ref *ref, *ref2, *ref3;
1170 struct list tkr = LIST_HEAD_INIT(tkr);
1171
1172 list_for_each_entry(ref, &tlskeys_reference, list) {
1173 if (ref->unique_id == -1) {
1174 /* Look for the first free id. */
1175 while (1) {
1176 list_for_each_entry(ref2, &tlskeys_reference, list) {
1177 if (ref2->unique_id == i) {
1178 i++;
1179 break;
1180 }
1181 }
1182 if (&ref2->list == &tlskeys_reference)
1183 break;
1184 }
1185
1186 /* Uses the unique id and increment it for the next entry. */
1187 ref->unique_id = i;
1188 i++;
1189 }
1190 }
1191
1192 /* This sort the reference list by id. */
1193 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001194 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001195 list_for_each_entry(ref3, &tkr, list) {
1196 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001197 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001198 break;
1199 }
1200 }
1201 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001202 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001203 }
1204
1205 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001206 LIST_INSERT(&tkr, &tlskeys_reference);
1207 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001208 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001209}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001210#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1211
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001212#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001213int ocsp_ex_index = -1;
1214
yanbzhube2774d2015-12-10 15:07:30 -05001215int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1216{
1217 switch (evp_keytype) {
1218 case EVP_PKEY_RSA:
1219 return 2;
1220 case EVP_PKEY_DSA:
1221 return 0;
1222 case EVP_PKEY_EC:
1223 return 1;
1224 }
1225
1226 return -1;
1227}
1228
Emeric Brun4147b2e2014-06-16 18:36:30 +02001229/*
1230 * Callback used to set OCSP status extension content in server hello.
1231 */
1232int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1233{
yanbzhube2774d2015-12-10 15:07:30 -05001234 struct certificate_ocsp *ocsp;
1235 struct ocsp_cbk_arg *ocsp_arg;
1236 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001237 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001238 EVP_PKEY *ssl_pkey;
1239 int key_type;
1240 int index;
1241
William Lallemand76b4a122020-08-04 17:41:39 +02001242 ctx = SSL_get_SSL_CTX(ssl);
1243 if (!ctx)
1244 return SSL_TLSEXT_ERR_NOACK;
1245
1246 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1247 if (!ocsp_arg)
1248 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001249
1250 ssl_pkey = SSL_get_privatekey(ssl);
1251 if (!ssl_pkey)
1252 return SSL_TLSEXT_ERR_NOACK;
1253
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001254 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001255
1256 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1257 ocsp = ocsp_arg->s_ocsp;
1258 else {
1259 /* For multiple certs per context, we have to find the correct OCSP response based on
1260 * the certificate type
1261 */
1262 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1263
1264 if (index < 0)
1265 return SSL_TLSEXT_ERR_NOACK;
1266
1267 ocsp = ocsp_arg->m_ocsp[index];
1268
1269 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001270
1271 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001272 !ocsp->response.area ||
1273 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001274 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001275 return SSL_TLSEXT_ERR_NOACK;
1276
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001277 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001278 if (!ssl_buf)
1279 return SSL_TLSEXT_ERR_NOACK;
1280
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001281 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1282 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001283
1284 return SSL_TLSEXT_ERR_OK;
1285}
1286
William Lallemand4a660132019-10-14 14:51:41 +02001287#endif
1288
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001289#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001290
1291
1292/*
1293 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1294 * used anymore. Also removes it from the tree if free'd.
1295 */
1296static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1297{
1298 if (!ocsp)
1299 return;
1300
1301 ocsp->refcount--;
1302 if (ocsp->refcount <= 0) {
1303 ebmb_delete(&ocsp->key);
1304 chunk_destroy(&ocsp->response);
1305 free(ocsp);
1306 }
1307}
1308
1309
Emeric Brun4147b2e2014-06-16 18:36:30 +02001310/*
1311 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001312 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1313 * status extension, the issuer's certificate is mandatory. It should be
1314 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001315 *
William Lallemand246c0242019-10-11 08:59:13 +02001316 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1317 * OCSP response. If file is empty or content is not a valid OCSP response,
1318 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1319 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001320 *
1321 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001322 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001323 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001324static 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 +02001325{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001326 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001327 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001328 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001329 struct certificate_ocsp *ocsp = NULL, *iocsp;
1330 char *warn = NULL;
1331 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001332 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001333
Emeric Brun4147b2e2014-06-16 18:36:30 +02001334
William Lallemand246c0242019-10-11 08:59:13 +02001335 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001336 if (!x)
1337 goto out;
1338
William Lallemand246c0242019-10-11 08:59:13 +02001339 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001340 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1341 if (chain) {
1342 /* check if one of the certificate of the chain is the issuer */
1343 for (i = 0; i < sk_X509_num(chain); i++) {
1344 X509 *ti = sk_X509_value(chain, i);
1345 if (X509_check_issued(ti, x) == X509_V_OK) {
1346 issuer = ti;
1347 break;
1348 }
1349 }
1350 }
William Lallemand246c0242019-10-11 08:59:13 +02001351 if (!issuer)
1352 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001353
1354 cid = OCSP_cert_to_id(0, x, issuer);
1355 if (!cid)
1356 goto out;
1357
1358 i = i2d_OCSP_CERTID(cid, NULL);
1359 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1360 goto out;
1361
Vincent Bernat02779b62016-04-03 13:48:43 +02001362 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001363 if (!ocsp)
1364 goto out;
1365
1366 p = ocsp->key_data;
1367 i2d_OCSP_CERTID(cid, &p);
1368
1369 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1370 if (iocsp == ocsp)
1371 ocsp = NULL;
1372
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001373#ifndef SSL_CTX_get_tlsext_status_cb
1374# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1375 *cb = (void (*) (void))ctx->tlsext_status_cb;
1376#endif
1377 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1378
1379 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001380 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001381 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001382
William Lallemanda560c062020-07-31 11:43:20 +02001383 cb_arg = calloc(1, sizeof(*cb_arg));
1384 if (!cb_arg)
1385 goto out;
1386
yanbzhube2774d2015-12-10 15:07:30 -05001387 cb_arg->is_single = 1;
1388 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001389 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001390
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001391 pkey = X509_get_pubkey(x);
1392 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1393 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001394
1395 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001396 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 */
1397
yanbzhube2774d2015-12-10 15:07:30 -05001398 } else {
1399 /*
1400 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1401 * Update that cb_arg with the new cert's staple
1402 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001403 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001404 struct certificate_ocsp *tmp_ocsp;
1405 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001406 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001407 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001408
William Lallemand76b4a122020-08-04 17:41:39 +02001409 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001410
1411 /*
1412 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1413 * the order of operations below matter, take care when changing it
1414 */
1415 tmp_ocsp = cb_arg->s_ocsp;
1416 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1417 cb_arg->s_ocsp = NULL;
1418 cb_arg->m_ocsp[index] = tmp_ocsp;
1419 cb_arg->is_single = 0;
1420 cb_arg->single_kt = 0;
1421
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001422 pkey = X509_get_pubkey(x);
1423 key_type = EVP_PKEY_base_id(pkey);
1424 EVP_PKEY_free(pkey);
1425
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001426 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001427 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001428 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001429 iocsp->refcount++;
1430 }
yanbzhube2774d2015-12-10 15:07:30 -05001431 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001432
1433 ret = 0;
1434
1435 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001436 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001437 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001438 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001439 }
1440
1441out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001442 if (cid)
1443 OCSP_CERTID_free(cid);
1444
1445 if (ocsp)
1446 free(ocsp);
1447
1448 if (warn)
1449 free(warn);
1450
Emeric Brun4147b2e2014-06-16 18:36:30 +02001451 return ret;
1452}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001453#endif
1454
1455#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001456static 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 +02001457{
William Lallemand4a660132019-10-14 14:51:41 +02001458 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 +02001459}
1460#endif
1461
William Lallemand4a660132019-10-14 14:51:41 +02001462
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001463#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001464
1465#define CT_EXTENSION_TYPE 18
1466
William Lallemand03c331c2020-05-13 10:10:01 +02001467int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001468
1469int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1470{
Willy Tarreau83061a82018-07-13 11:56:34 +02001471 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001472
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001473 *out = (unsigned char *) sctl->area;
1474 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001475
1476 return 1;
1477}
1478
1479int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1480{
1481 return 1;
1482}
1483
William Lallemanda17f4112019-10-10 15:16:44 +02001484static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001485{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001486 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001487
William Lallemanda17f4112019-10-10 15:16:44 +02001488 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 +01001489 goto out;
1490
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001491 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1492
1493 ret = 0;
1494
1495out:
1496 return ret;
1497}
1498
1499#endif
1500
Emeric Brune1f38db2012-09-03 20:36:47 +02001501void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1502{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001503 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001504 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001505 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001506 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001507
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001508#ifndef SSL_OP_NO_RENEGOTIATION
1509 /* Please note that BoringSSL defines this macro to zero so don't
1510 * change this to #if and do not assign a default value to this macro!
1511 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001512 if (where & SSL_CB_HANDSHAKE_START) {
1513 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001514 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 +02001515 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001516 conn->err_code = CO_ER_SSL_RENEG;
1517 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001518 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001519#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001520
1521 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001522 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001523 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001524 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001525 consider that the buffering was activated,
1526 so we rise the output buffer size from 4k
1527 to 16k */
1528 write_bio = SSL_get_wbio(ssl);
1529 if (write_bio != SSL_get_rbio(ssl)) {
1530 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001531 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001532 }
1533 }
1534 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001535}
1536
Emeric Brune64aef12012-09-21 13:15:06 +02001537/* Callback is called for each certificate of the chain during a verify
1538 ok is set to 1 if preverify detect no error on current certificate.
1539 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001540int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001541{
1542 SSL *ssl;
1543 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001544 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001545 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001546
1547 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001548 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001549
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001550 ctx = conn->xprt_ctx;
1551
1552 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001553
Emeric Brun81c00f02012-09-21 14:31:21 +02001554 if (ok) /* no errors */
1555 return ok;
1556
1557 depth = X509_STORE_CTX_get_error_depth(x_store);
1558 err = X509_STORE_CTX_get_error(x_store);
1559
1560 /* check if CA error needs to be ignored */
1561 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001562 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1563 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1564 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001565 }
1566
Willy Tarreau731248f2020-02-04 14:02:02 +01001567 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001568 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001569 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001570 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001571 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001572
Willy Tarreau20879a02012-12-03 16:32:10 +01001573 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001574 return 0;
1575 }
1576
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001577 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1578 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001579
Emeric Brun81c00f02012-09-21 14:31:21 +02001580 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001581 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001582 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001583 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001584 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001585 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001586
Willy Tarreau20879a02012-12-03 16:32:10 +01001587 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001588 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001589}
1590
Dragan Dosen9ac98092020-05-11 15:51:45 +02001591#ifdef TLS1_RT_HEARTBEAT
1592static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1593 int content_type, const void *buf, size_t len,
1594 SSL *ssl)
1595{
1596 /* test heartbeat received (write_p is set to 0
1597 for a received record) */
1598 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1599 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1600 const unsigned char *p = buf;
1601 unsigned int payload;
1602
1603 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1604
1605 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1606 if (*p != TLS1_HB_REQUEST)
1607 return;
1608
1609 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1610 goto kill_it;
1611
1612 payload = (p[1] * 256) + p[2];
1613 if (3 + payload + 16 <= len)
1614 return; /* OK no problem */
1615 kill_it:
1616 /* We have a clear heartbleed attack (CVE-2014-0160), the
1617 * advertised payload is larger than the advertised packet
1618 * length, so we have garbage in the buffer between the
1619 * payload and the end of the buffer (p+len). We can't know
1620 * if the SSL stack is patched, and we don't know if we can
1621 * safely wipe out the area between p+3+len and payload.
1622 * So instead, we prevent the response from being sent by
1623 * setting the max_send_fragment to 0 and we report an SSL
1624 * error, which will kill this connection. It will be reported
1625 * above as SSL_ERROR_SSL while an other handshake failure with
1626 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1627 */
1628 ssl->max_send_fragment = 0;
1629 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1630 }
1631}
1632#endif
1633
1634static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1635 int content_type, const void *buf, size_t len,
1636 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001637{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001638 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001639 unsigned char *msg;
1640 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001641 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001642
1643 /* This function is called for "from client" and "to server"
1644 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001645 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001646 */
1647
1648 /* "write_p" is set to 0 is the bytes are received messages,
1649 * otherwise it is set to 1.
1650 */
1651 if (write_p != 0)
1652 return;
1653
1654 /* content_type contains the type of message received or sent
1655 * according with the SSL/TLS protocol spec. This message is
1656 * encoded with one byte. The value 256 (two bytes) is used
1657 * for designing the SSL/TLS record layer. According with the
1658 * rfc6101, the expected message (other than 256) are:
1659 * - change_cipher_spec(20)
1660 * - alert(21)
1661 * - handshake(22)
1662 * - application_data(23)
1663 * - (255)
1664 * We are interessed by the handshake and specially the client
1665 * hello.
1666 */
1667 if (content_type != 22)
1668 return;
1669
1670 /* The message length is at least 4 bytes, containing the
1671 * message type and the message length.
1672 */
1673 if (len < 4)
1674 return;
1675
1676 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001677 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001678 * - hello_request(0)
1679 * - client_hello(1)
1680 * - server_hello(2)
1681 * - certificate(11)
1682 * - server_key_exchange (12)
1683 * - certificate_request(13)
1684 * - server_hello_done(14)
1685 * We are interested by the client hello.
1686 */
1687 msg = (unsigned char *)buf;
1688 if (msg[0] != 1)
1689 return;
1690
1691 /* Next three bytes are the length of the message. The total length
1692 * must be this decoded length + 4. If the length given as argument
1693 * is not the same, we abort the protocol dissector.
1694 */
1695 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1696 if (len < rec_len + 4)
1697 return;
1698 msg += 4;
1699 end = msg + rec_len;
1700 if (end < msg)
1701 return;
1702
1703 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1704 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001705 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1706 */
1707 msg += 1 + 1 + 4 + 28;
1708 if (msg > end)
1709 return;
1710
1711 /* Next, is session id:
1712 * if present, we have to jump by length + 1 for the size information
1713 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001714 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001715 if (msg[0] > 0)
1716 msg += msg[0];
1717 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001718 if (msg > end)
1719 return;
1720
1721 /* Next two bytes are the ciphersuite length. */
1722 if (msg + 2 > end)
1723 return;
1724 rec_len = (msg[0] << 8) + msg[1];
1725 msg += 2;
1726 if (msg + rec_len > end || msg + rec_len < msg)
1727 return;
1728
Willy Tarreaub454e902021-03-22 15:09:41 +01001729 capture = pool_alloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001730 if (!capture)
1731 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001732 /* Compute the xxh64 of the ciphersuite. */
1733 capture->xxh64 = XXH64(msg, rec_len, 0);
1734
1735 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001736 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1737 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001738 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001739
1740 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001741}
William Lallemand7d42ef52020-07-06 11:41:30 +02001742
1743
William Lallemand722180a2021-06-09 16:46:12 +02001744#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001745static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1746 int content_type, const void *buf, size_t len,
1747 SSL *ssl)
1748{
1749 struct ssl_keylog *keylog;
1750
1751 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1752 return;
1753
Willy Tarreauf208ac02021-03-22 21:10:12 +01001754 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001755 if (!keylog)
1756 return;
1757
William Lallemand7d42ef52020-07-06 11:41:30 +02001758 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1759 pool_free(pool_head_ssl_keylog, keylog);
1760 return;
1761 }
1762}
1763#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001764
Emeric Brun29f037d2014-04-25 19:05:36 +02001765/* Callback is called for ssl protocol analyse */
1766void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1767{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001768 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1769 struct ssl_sock_msg_callback *cbk;
1770
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001771 /* Try to call all callback functions that were registered by using
1772 * ssl_sock_register_msg_callback().
1773 */
1774 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1775 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1776 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001777}
1778
Bernard Spil13c53f82018-02-15 13:34:58 +01001779#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001780static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1781 const unsigned char *in, unsigned int inlen,
1782 void *arg)
1783{
1784 struct server *srv = arg;
1785
1786 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1787 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1788 return SSL_TLSEXT_ERR_OK;
1789 return SSL_TLSEXT_ERR_NOACK;
1790}
1791#endif
1792
1793#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001794/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001795 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001796 */
1797static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1798 unsigned int *len, void *arg)
1799{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001800 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001801
1802 *data = (const unsigned char *)conf->npn_str;
1803 *len = conf->npn_len;
1804 return SSL_TLSEXT_ERR_OK;
1805}
1806#endif
1807
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001808#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001809/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001810 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001811 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001812static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1813 unsigned char *outlen,
1814 const unsigned char *server,
1815 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001816{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001817 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001818
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001819 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1820 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1821 return SSL_TLSEXT_ERR_NOACK;
1822 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001823 return SSL_TLSEXT_ERR_OK;
1824}
1825#endif
1826
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001827#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001828#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001829
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001830/* Configure a DNS SAN extenion on a certificate. */
1831int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1832 int failure = 0;
1833 X509_EXTENSION *san_ext = NULL;
1834 CONF *conf = NULL;
1835 struct buffer *san_name = get_trash_chunk();
1836
1837 conf = NCONF_new(NULL);
1838 if (!conf) {
1839 failure = 1;
1840 goto cleanup;
1841 }
1842
1843 /* Build an extension based on the DNS entry above */
1844 chunk_appendf(san_name, "DNS:%s", servername);
1845 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1846 if (!san_ext) {
1847 failure = 1;
1848 goto cleanup;
1849 }
1850
1851 /* Add the extension */
1852 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1853 failure = 1;
1854 goto cleanup;
1855 }
1856
1857 /* Success */
1858 failure = 0;
1859
1860cleanup:
1861 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1862 if (NULL != conf) NCONF_free(conf);
1863
1864 return failure;
1865}
1866
Christopher Faulet30548802015-06-11 13:39:32 +02001867/* Create a X509 certificate with the specified servername and serial. This
1868 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001869static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001870ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001871{
Shimi Gersner5846c492020-08-23 13:58:12 +03001872 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1873 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001874 SSL_CTX *ssl_ctx = NULL;
1875 X509 *newcrt = NULL;
1876 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001877 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001878 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001879 X509_NAME *name;
1880 const EVP_MD *digest;
1881 X509V3_CTX ctx;
1882 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001883 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001884
Christopher Faulet48a83322017-07-28 16:56:09 +02001885 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001886#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001887 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1888#else
1889 tmp_ssl = SSL_new(bind_conf->default_ctx);
1890 if (tmp_ssl)
1891 pkey = SSL_get_privatekey(tmp_ssl);
1892#endif
1893 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001894 goto mkcert_error;
1895
1896 /* Create the certificate */
1897 if (!(newcrt = X509_new()))
1898 goto mkcert_error;
1899
1900 /* Set version number for the certificate (X509v3) and the serial
1901 * number */
1902 if (X509_set_version(newcrt, 2L) != 1)
1903 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001904 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001905
1906 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001907 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1908 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001909 goto mkcert_error;
1910
1911 /* set public key in the certificate */
1912 if (X509_set_pubkey(newcrt, pkey) != 1)
1913 goto mkcert_error;
1914
1915 /* Set issuer name from the CA */
1916 if (!(name = X509_get_subject_name(cacert)))
1917 goto mkcert_error;
1918 if (X509_set_issuer_name(newcrt, name) != 1)
1919 goto mkcert_error;
1920
1921 /* Set the subject name using the same, but the CN */
1922 name = X509_NAME_dup(name);
1923 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1924 (const unsigned char *)servername,
1925 -1, -1, 0) != 1) {
1926 X509_NAME_free(name);
1927 goto mkcert_error;
1928 }
1929 if (X509_set_subject_name(newcrt, name) != 1) {
1930 X509_NAME_free(name);
1931 goto mkcert_error;
1932 }
1933 X509_NAME_free(name);
1934
1935 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001936 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001937 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1938 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1939 X509_EXTENSION *ext;
1940
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001941 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001942 goto mkcert_error;
1943 if (!X509_add_ext(newcrt, ext, -1)) {
1944 X509_EXTENSION_free(ext);
1945 goto mkcert_error;
1946 }
1947 X509_EXTENSION_free(ext);
1948 }
1949
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001950 /* Add SAN extension */
1951 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
1952 goto mkcert_error;
1953 }
1954
Christopher Faulet31af49d2015-06-09 17:29:50 +02001955 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001956
1957 key_type = EVP_PKEY_base_id(capkey);
1958
1959 if (key_type == EVP_PKEY_DSA)
1960 digest = EVP_sha1();
1961 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001962 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001963 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001964 digest = EVP_sha256();
1965 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05001966#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02001967 int nid;
1968
1969 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1970 goto mkcert_error;
1971 if (!(digest = EVP_get_digestbynid(nid)))
1972 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02001973#else
1974 goto mkcert_error;
1975#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02001976 }
1977
Christopher Faulet31af49d2015-06-09 17:29:50 +02001978 if (!(X509_sign(newcrt, capkey, digest)))
1979 goto mkcert_error;
1980
1981 /* Create and set the new SSL_CTX */
1982 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
1983 goto mkcert_error;
1984 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1985 goto mkcert_error;
1986 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
1987 goto mkcert_error;
1988 if (!SSL_CTX_check_private_key(ssl_ctx))
1989 goto mkcert_error;
1990
Shimi Gersner5846c492020-08-23 13:58:12 +03001991 /* Build chaining the CA cert and the rest of the chain, keep these order */
1992#if defined(SSL_CTX_add1_chain_cert)
1993 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
1994 goto mkcert_error;
1995 }
1996
1997 if (bind_conf->ca_sign_ckch->chain) {
1998 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
1999 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2000 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2001 goto mkcert_error;
2002 }
2003 }
2004 }
2005#endif
2006
Christopher Faulet31af49d2015-06-09 17:29:50 +02002007 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002008
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002009#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002010 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002011#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002012#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2013 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002014 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002015 EC_KEY *ecc;
2016 int nid;
2017
2018 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2019 goto end;
2020 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2021 goto end;
2022 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2023 EC_KEY_free(ecc);
2024 }
2025#endif
2026 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002027 return ssl_ctx;
2028
2029 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002030 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002031 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002032 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2033 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002034 return NULL;
2035}
2036
Christopher Faulet7969a332015-10-09 11:15:03 +02002037SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002038ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02002039{
Willy Tarreau07d94e42018-09-20 10:57:52 +02002040 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01002041 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002042
Olivier Houchard66ab4982019-02-26 18:37:15 +01002043 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02002044}
2045
Christopher Faulet30548802015-06-11 13:39:32 +02002046/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002047 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002048SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002049ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002050{
2051 struct lru64 *lru = NULL;
2052
2053 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002054 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002055 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002056 if (lru && lru->domain) {
2057 if (ssl)
2058 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002059 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002060 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002061 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002062 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002063 }
2064 return NULL;
2065}
2066
Emeric Brun821bb9b2017-06-15 16:37:39 +02002067/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2068 * function is not thread-safe, it should only be used to check if a certificate
2069 * exists in the lru cache (with no warranty it will not be removed by another
2070 * thread). It is kept for backward compatibility. */
2071SSL_CTX *
2072ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2073{
2074 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2075}
2076
Christopher Fauletd2cab922015-07-28 16:03:47 +02002077/* Set a certificate int the LRU cache used to store generated
2078 * certificate. Return 0 on success, otherwise -1 */
2079int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002080ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002081{
2082 struct lru64 *lru = NULL;
2083
2084 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002085 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002086 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002087 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002088 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002089 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002090 }
Christopher Faulet30548802015-06-11 13:39:32 +02002091 if (lru->domain && lru->data)
2092 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002093 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002094 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002095 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002096 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002097 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002098}
2099
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002100/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002101unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002102ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002103{
2104 return XXH32(data, len, ssl_ctx_lru_seed);
2105}
2106
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002107/* Generate a cert and immediately assign it to the SSL session so that the cert's
2108 * refcount is maintained regardless of the cert's presence in the LRU cache.
2109 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002110static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002111ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002112{
Shimi Gersner5846c492020-08-23 13:58:12 +03002113 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002114 SSL_CTX *ssl_ctx = NULL;
2115 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002116 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002117
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002118 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002119 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002120 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002121 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002122 if (lru && lru->domain)
2123 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002124 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002125 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002126 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002127 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002128 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002129 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002130 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002131 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002132 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002133 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002134 SSL_set_SSL_CTX(ssl, ssl_ctx);
2135 /* No LRU cache, this CTX will be released as soon as the session dies */
2136 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002137 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002138 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002139 return 0;
2140}
2141static int
2142ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2143{
2144 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002145 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002146
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002147 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002148 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002149 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002150 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002151 }
2152 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002153}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002154#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002155
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002156#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002157
2158static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002159{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002160#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002161 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002162 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2163#endif
2164}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002165static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2166 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002167 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2168}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002169static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002170#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002171 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002172 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2173#endif
2174}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002175static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002176#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002177 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002178 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2179#endif
2180}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002181/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002182static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2183/* Unusable in this context. */
2184static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2185static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2186static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2187static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2188static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002189#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002190
2191static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2192 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002193 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2194}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002195static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2196 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2197 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2198}
2199static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2200 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002201 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2202}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002203static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2204 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2205 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2206}
2207static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2208 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002209 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2210}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002211static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2212 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2213 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2214}
2215static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2216 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002217 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2218}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002219static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2220 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2221 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2222}
2223static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002224#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002225 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002226 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2227#endif
2228}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002229static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002230#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002231 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2232 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002233#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002234}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002235#endif
2236static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2237static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002238
William Lallemand7fd8b452020-05-07 15:20:43 +02002239struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002240 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2241 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2242 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2243 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2244 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2245 {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 +02002246};
2247
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002248static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2249{
2250 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2251 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2252 SSL_set_SSL_CTX(ssl, ctx);
2253}
2254
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002255#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002256
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002257int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002258{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002259 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002260 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002261
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002262 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2263 return SSL_TLSEXT_ERR_OK;
2264 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002265}
2266
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002267#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002268int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002269{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002270 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002271#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002272int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002273{
2274#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002275 struct connection *conn;
2276 struct bind_conf *s;
2277 const uint8_t *extension_data;
2278 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002279 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002280
2281 char *wildp = NULL;
2282 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002283 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002284 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002285 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002286 int i;
2287
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002288 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002289 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002290
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002291#ifdef USE_QUIC
2292 if (conn->qc) {
2293 /* Look for the QUIC transport parameters. */
2294#ifdef OPENSSL_IS_BORINGSSL
2295 if (!SSL_early_callback_ctx_extension_get(ctx, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2296 &extension_data, &extension_len))
2297#else
2298 if (!SSL_client_hello_get0_ext(ssl, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2299 &extension_data, &extension_len))
2300#endif
2301 goto abort;
2302
2303 if (!quic_transport_params_store(conn->qc, 0, extension_data,
2304 extension_data + extension_len))
2305 goto abort;
2306 }
2307#endif
2308
Olivier Houchard9679ac92017-10-27 14:58:08 +02002309 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002310 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002311#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002312 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2313 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002314#else
2315 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2316#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002317 /*
2318 * The server_name extension was given too much extensibility when it
2319 * was written, so parsing the normal case is a bit complex.
2320 */
2321 size_t len;
2322 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002323 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002324 /* Extract the length of the supplied list of names. */
2325 len = (*extension_data++) << 8;
2326 len |= *extension_data++;
2327 if (len + 2 != extension_len)
2328 goto abort;
2329 /*
2330 * The list in practice only has a single element, so we only consider
2331 * the first one.
2332 */
2333 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2334 goto abort;
2335 extension_len = len - 1;
2336 /* Now we can finally pull out the byte array with the actual hostname. */
2337 if (extension_len <= 2)
2338 goto abort;
2339 len = (*extension_data++) << 8;
2340 len |= *extension_data++;
2341 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2342 || memchr(extension_data, 0, len) != NULL)
2343 goto abort;
2344 servername = extension_data;
2345 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002346 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002347#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2348 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002349 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002350 }
2351#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002352 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002353 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002354 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002355 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002356 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002357 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002358 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002359 goto abort;
2360 }
2361
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002362 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002363#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002364 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002365#else
2366 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2367#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002368 uint8_t sign;
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 len = (*extension_data++) << 8;
2373 len |= *extension_data++;
2374 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002375 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002376 if (len % 2 != 0)
2377 goto abort;
2378 for (; len > 0; len -= 2) {
2379 extension_data++; /* hash */
2380 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002381 switch (sign) {
2382 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002383 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002384 break;
2385 case TLSEXT_signature_ecdsa:
2386 has_ecdsa_sig = 1;
2387 break;
2388 default:
2389 continue;
2390 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002391 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002392 break;
2393 }
2394 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002395 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002396 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002397 }
2398 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002399 const SSL_CIPHER *cipher;
2400 size_t len;
2401 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002402 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002403#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002404 len = ctx->cipher_suites_len;
2405 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002406#else
2407 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2408#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002409 if (len % 2 != 0)
2410 goto abort;
2411 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002412#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002413 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002414 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002415#else
2416 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2417#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002418 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002419 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002420 break;
2421 }
2422 }
2423 }
2424
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002425 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002426 trash.area[i] = tolower(servername[i]);
2427 if (!wildp && (trash.area[i] == '.'))
2428 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002429 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002430 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002431
William Lallemand150bfa82019-09-19 17:12:49 +02002432 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002433
William Lallemand94bd3192020-08-14 14:43:35 +02002434 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2435 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002436 for (i = 0; i < 2; i++) {
2437 if (i == 0) /* lookup in full qualified names */
2438 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002439 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002440 node = ebst_lookup(&s->sni_w_ctx, wildp);
2441 else
2442 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002443
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002444 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002445
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002446 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002447 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002448 struct sni_ctx *sni, *sni_tmp;
2449 int skip = 0;
2450
2451 if (i == 1 && wildp) { /* wildcard */
2452 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2453 sni = container_of(n, struct sni_ctx, name);
2454 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002455 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002456 skip = 1;
2457 break;
2458 }
2459 }
2460 if (skip)
2461 continue;
2462 }
2463
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002464 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002465 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002466 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002467 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002468 break;
2469 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002470 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002471 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002472 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002473 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002474 if (!node_anonymous)
2475 node_anonymous = n;
2476 break;
2477 }
2478 }
2479 }
William Lallemand94bd3192020-08-14 14:43:35 +02002480 }
2481 /* Once the certificates are found, select them depending on what is
2482 * supported in the client and by key_signature priority order: EDSA >
2483 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002484 if (has_ecdsa_sig && node_ecdsa)
2485 node = node_ecdsa;
2486 else if (has_rsa_sig && node_rsa)
2487 node = node_rsa;
2488 else if (node_anonymous)
2489 node = node_anonymous;
2490 else if (node_ecdsa)
2491 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2492 else
2493 node = node_rsa; /* no rsa signature case (far far away) */
2494
William Lallemand94bd3192020-08-14 14:43:35 +02002495 if (node) {
2496 /* switch ctx */
2497 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2498 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2499 if (conf) {
2500 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2501 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2502 if (conf->early_data)
2503 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002504 }
William Lallemand94bd3192020-08-14 14:43:35 +02002505 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2506 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002507 }
William Lallemand150bfa82019-09-19 17:12:49 +02002508
William Lallemand02010472019-10-18 11:02:19 +02002509 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002510#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002511 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002512 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002513 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002514 }
2515#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002516 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002517 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002518 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002519 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002520 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002521 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02002522allow_early:
2523#ifdef OPENSSL_IS_BORINGSSL
2524 if (allow_early)
2525 SSL_set_early_data_enabled(ssl, 1);
2526#else
2527 if (!allow_early)
2528 SSL_set_max_early_data(ssl, 0);
2529#endif
2530 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002531 abort:
2532 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2533 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002534#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002535 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002536#else
2537 *al = SSL_AD_UNRECOGNIZED_NAME;
2538 return 0;
2539#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002540}
2541
2542#else /* OPENSSL_IS_BORINGSSL */
2543
Emeric Brunfc0421f2012-09-07 17:30:07 +02002544/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2545 * warning when no match is found, which implies the default (first) cert
2546 * will keep being used.
2547 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002548static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002549{
2550 const char *servername;
2551 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002552 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002553 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002554 int i;
2555 (void)al; /* shut gcc stupid warning */
2556
2557 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002558 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002559#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002560 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2561 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002562#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002563 if (s->strict_sni)
2564 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002565 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002566 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002567 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002568 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002569 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002570
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002571 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002572 if (!servername[i])
2573 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002574 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002575 if (!wildp && (trash.area[i] == '.'))
2576 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002577 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002578 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002579
William Lallemand150bfa82019-09-19 17:12:49 +02002580 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002581 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002582 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002583 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2584 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002585 if (!container_of(n, struct sni_ctx, name)->neg) {
2586 node = n;
2587 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002588 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002589 }
2590 if (!node && wildp) {
2591 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002592 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2593 /* lookup a not neg filter */
2594 if (!container_of(n, struct sni_ctx, name)->neg) {
2595 node = n;
2596 break;
2597 }
2598 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002599 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002600 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002601#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002602 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2603 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002604 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002605 return SSL_TLSEXT_ERR_OK;
2606 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002607#endif
William Lallemand21724f02019-11-04 17:56:13 +01002608 if (s->strict_sni) {
2609 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002610 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002611 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002612 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002613 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002614 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002615 }
2616
2617 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002618 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002619 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002620 return SSL_TLSEXT_ERR_OK;
2621}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002622#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002623#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2624
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002625#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002626
2627static DH * ssl_get_dh_1024(void)
2628{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002629 static unsigned char dh1024_p[]={
2630 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2631 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2632 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2633 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2634 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2635 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2636 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2637 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2638 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2639 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2640 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2641 };
2642 static unsigned char dh1024_g[]={
2643 0x02,
2644 };
2645
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002646 BIGNUM *p;
2647 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002648 DH *dh = DH_new();
2649 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002650 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2651 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002652
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002653 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002654 DH_free(dh);
2655 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002656 } else {
2657 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002658 }
2659 }
2660 return dh;
2661}
2662
2663static DH *ssl_get_dh_2048(void)
2664{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002665 static unsigned char dh2048_p[]={
2666 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2667 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2668 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2669 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2670 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2671 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2672 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2673 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2674 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2675 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2676 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2677 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2678 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2679 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2680 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2681 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2682 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2683 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2684 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2685 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2686 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2687 0xB7,0x1F,0x77,0xF3,
2688 };
2689 static unsigned char dh2048_g[]={
2690 0x02,
2691 };
2692
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002693 BIGNUM *p;
2694 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002695 DH *dh = DH_new();
2696 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002697 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2698 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002699
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002700 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002701 DH_free(dh);
2702 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002703 } else {
2704 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002705 }
2706 }
2707 return dh;
2708}
2709
2710static DH *ssl_get_dh_4096(void)
2711{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002712 static unsigned char dh4096_p[]={
2713 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2714 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2715 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2716 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2717 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2718 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2719 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2720 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2721 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2722 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2723 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2724 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2725 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2726 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2727 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2728 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2729 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2730 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2731 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2732 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2733 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2734 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2735 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2736 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2737 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2738 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2739 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2740 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2741 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2742 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2743 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2744 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2745 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2746 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2747 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2748 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2749 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2750 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2751 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2752 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2753 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2754 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2755 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002756 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002757 static unsigned char dh4096_g[]={
2758 0x02,
2759 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002760
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002761 BIGNUM *p;
2762 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002763 DH *dh = DH_new();
2764 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002765 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2766 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002767
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002768 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002769 DH_free(dh);
2770 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002771 } else {
2772 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002773 }
2774 }
2775 return dh;
2776}
2777
2778/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002779 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002780static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2781{
2782 DH *dh = NULL;
2783 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002784 int type;
2785
2786 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002787
2788 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2789 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2790 */
2791 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2792 keylen = EVP_PKEY_bits(pkey);
2793 }
2794
Willy Tarreauef934602016-12-22 23:12:01 +01002795 if (keylen > global_ssl.default_dh_param) {
2796 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002797 }
2798
Remi Gacogned3a341a2015-05-29 16:26:17 +02002799 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002800 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002801 }
2802 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002803 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002804 }
2805 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002806 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002807 }
2808
2809 return dh;
2810}
2811
Remi Gacogne47783ef2015-05-29 15:53:22 +02002812static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002813{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002814 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002815 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002816
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002817 if (in == NULL)
2818 goto end;
2819
Remi Gacogne47783ef2015-05-29 15:53:22 +02002820 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002821 goto end;
2822
Remi Gacogne47783ef2015-05-29 15:53:22 +02002823 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2824
2825end:
2826 if (in)
2827 BIO_free(in);
2828
Emeric Brune1b4ed42018-08-16 15:14:12 +02002829 ERR_clear_error();
2830
Remi Gacogne47783ef2015-05-29 15:53:22 +02002831 return dh;
2832}
2833
2834int ssl_sock_load_global_dh_param_from_file(const char *filename)
2835{
2836 global_dh = ssl_sock_get_dh_from_file(filename);
2837
2838 if (global_dh) {
2839 return 0;
2840 }
2841
2842 return -1;
2843}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002844#endif
2845
William Lallemand9117de92019-10-04 00:29:42 +02002846/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002847static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002848 struct bind_conf *s, struct ssl_bind_conf *conf,
2849 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002850{
2851 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002852 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002853
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002854 if (*name == '!') {
2855 neg = 1;
2856 name++;
2857 }
2858 if (*name == '*') {
2859 wild = 1;
2860 name++;
2861 }
2862 /* !* filter is a nop */
2863 if (neg && wild)
2864 return order;
2865 if (*name) {
2866 int j, len;
2867 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002868 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02002869 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002870 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002871 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002872 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002873
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002874 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002875 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002876 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002877 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002878 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002879 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002880 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002881 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002882 sc->order = order++;
2883 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002884 sc->wild = wild;
2885 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002886 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02002887 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002888 }
2889 return order;
2890}
2891
William Lallemand6af03992019-07-23 15:00:54 +02002892/*
William Lallemand1d29c742019-10-04 00:53:29 +02002893 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2894 * This function can't return an error.
2895 *
2896 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2897 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002898void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002899{
2900
2901 struct sni_ctx *sc0, *sc0b, *sc1;
2902 struct ebmb_node *node;
2903
2904 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2905
2906 /* ignore if sc0 was already inserted in a tree */
2907 if (sc0->name.node.leaf_p)
2908 continue;
2909
2910 /* Check for duplicates. */
2911 if (sc0->wild)
2912 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2913 else
2914 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2915
2916 for (; node; node = ebmb_next_dup(node)) {
2917 sc1 = ebmb_entry(node, struct sni_ctx, name);
2918 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2919 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2920 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02002921 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002922 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002923 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02002924 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002925 }
2926 }
2927
2928 /* if duplicate, ignore the insertion */
2929 if (!sc0)
2930 continue;
2931
2932 if (sc0->wild)
2933 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
2934 else
2935 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01002936 }
William Lallemand21724f02019-11-04 17:56:13 +01002937
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01002938 /* replace the default_ctx if required with the instance's ctx. */
2939 if (ckch_inst->is_default) {
2940 SSL_CTX_free(bind_conf->default_ctx);
2941 SSL_CTX_up_ref(ckch_inst->ctx);
2942 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02002943 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02002944 }
2945}
2946
2947/*
William Lallemande3af8fb2019-10-08 11:36:53 +02002948 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02002949 */
William Lallemande3af8fb2019-10-08 11:36:53 +02002950struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02002951
William Lallemand2954c472020-03-06 21:54:13 +01002952/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02002953struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02002954
Emeric Brun7a883362019-10-17 13:27:40 +02002955/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002956 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02002957 * DH parameter is loaded into the SSL_CTX and if there is no
2958 * DH parameter available in ckchs nor in global, the default
2959 * DH parameters are applied on the SSL_CTX.
2960 * Returns a bitfield containing the flags:
2961 * ERR_FATAL in any fatal error case
2962 * ERR_ALERT if a reason of the error is availabine in err
2963 * ERR_WARN if a warning is available into err
2964 * The value 0 means there is no error nor warning and
2965 * the operation succeed.
2966 */
William Lallemandfa892222019-07-23 16:06:08 +02002967#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02002968static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
2969 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02002970{
Emeric Brun7a883362019-10-17 13:27:40 +02002971 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02002972 DH *dh = NULL;
2973
William Lallemanda8c73742019-07-31 18:31:34 +02002974 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02002975 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02002976 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
2977 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
2978 err && *err ? *err : "", path);
2979#if defined(SSL_CTX_set_dh_auto)
2980 SSL_CTX_set_dh_auto(ctx, 1);
2981 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2982 err && *err ? *err : "");
2983#else
2984 memprintf(err, "%s, DH ciphers won't be available.\n",
2985 err && *err ? *err : "");
2986#endif
2987 ret |= ERR_WARN;
2988 goto end;
2989 }
William Lallemandfa892222019-07-23 16:06:08 +02002990
2991 if (ssl_dh_ptr_index >= 0) {
2992 /* store a pointer to the DH params to avoid complaining about
2993 ssl-default-dh-param not being set for this SSL_CTX */
2994 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
2995 }
2996 }
2997 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02002998 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
2999 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3000 err && *err ? *err : "", path);
3001#if defined(SSL_CTX_set_dh_auto)
3002 SSL_CTX_set_dh_auto(ctx, 1);
3003 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3004 err && *err ? *err : "");
3005#else
3006 memprintf(err, "%s, DH ciphers won't be available.\n",
3007 err && *err ? *err : "");
3008#endif
3009 ret |= ERR_WARN;
3010 goto end;
3011 }
William Lallemandfa892222019-07-23 16:06:08 +02003012 }
3013 else {
3014 /* Clear openssl global errors stack */
3015 ERR_clear_error();
3016
Willy Tarreau6d27a922020-11-05 19:38:05 +01003017 if (global_ssl.default_dh_param && global_ssl.default_dh_param <= 1024) {
William Lallemandfa892222019-07-23 16:06:08 +02003018 /* we are limited to DH parameter of 1024 bits anyway */
3019 if (local_dh_1024 == NULL)
3020 local_dh_1024 = ssl_get_dh_1024();
3021
Emeric Brun7a883362019-10-17 13:27:40 +02003022 if (local_dh_1024 == NULL) {
3023 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3024 err && *err ? *err : "", path);
3025 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02003026 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02003027 }
William Lallemandfa892222019-07-23 16:06:08 +02003028
Emeric Bruna9363eb2019-10-17 14:53:03 +02003029 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
3030 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3031 err && *err ? *err : "", path);
3032#if defined(SSL_CTX_set_dh_auto)
3033 SSL_CTX_set_dh_auto(ctx, 1);
3034 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3035 err && *err ? *err : "");
3036#else
3037 memprintf(err, "%s, DH ciphers won't be available.\n",
3038 err && *err ? *err : "");
3039#endif
3040 ret |= ERR_WARN;
3041 goto end;
3042 }
William Lallemandfa892222019-07-23 16:06:08 +02003043 }
3044 else {
3045 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
3046 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003047 }
3048
William Lallemandf9568fc2019-10-16 18:27:58 +02003049end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003050 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003051 return ret;
3052}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003053#endif
William Lallemandfa892222019-07-23 16:06:08 +02003054
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003055
3056/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003057 * Returns a bitfield containing the flags:
3058 * ERR_FATAL in any fatal error case
3059 * ERR_ALERT if the reason of the error is available in err
3060 * ERR_WARN if a warning is available into err
3061 * The value 0 means there is no error nor warning and
3062 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003063 */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003064static int ssl_sock_load_cert_chain(const char *path, const struct cert_key_and_chain *ckch,
3065 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003066{
Emeric Bruna96b5822019-10-17 13:25:14 +02003067 int errcode = 0;
3068
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003069 if (find_chain == NULL) {
3070 errcode |= ERR_FATAL;
3071 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003072 }
3073
3074 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3075 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3076 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003077 errcode |= ERR_ALERT | ERR_FATAL;
3078 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003079 }
3080
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003081 if (ckch->chain) {
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003082 *find_chain = ckch->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003083 } else {
3084 /* Find Certificate Chain in global */
3085 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003086 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003087 if (issuer)
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003088 *find_chain = issuer->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003089 }
William Lallemand85888572020-02-27 14:48:35 +01003090
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003091 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003092 /* always put a null chain stack in the SSL_CTX so it does not
3093 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003094 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003095 }
3096
William Lallemandf187ce62020-06-02 18:27:20 +02003097 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003098#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003099 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand935d8292020-08-12 20:02:10 +02003100 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3101 err && *err ? *err : "", path);
3102 errcode |= ERR_ALERT | ERR_FATAL;
3103 goto end;
3104 }
William Lallemandf187ce62020-06-02 18:27:20 +02003105#else
3106 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003107 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02003108 STACK_OF(X509) *chain;
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003109 chain = X509_chain_up_ref(*find_chain);
William Lallemandf187ce62020-06-02 18:27:20 +02003110 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003111 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003112 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3113 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003114 X509_free(ca);
3115 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003116 errcode |= ERR_ALERT | ERR_FATAL;
3117 goto end;
3118 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003119 }
William Lallemandf187ce62020-06-02 18:27:20 +02003120#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003121
William Lallemand9a1d8392020-08-10 17:28:23 +02003122#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003123 /* remove the Root CA from the SSL_CTX if the option is activated */
3124 if (global_ssl.skip_self_issued_ca) {
3125 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3126 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3127 err && *err ? *err : "", path);
3128 errcode |= ERR_ALERT | ERR_FATAL;
3129 goto end;
3130 }
3131 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003132#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003133
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003134end:
3135 return errcode;
3136}
3137
3138
3139/* Loads the info in ckch into ctx
3140 * Returns a bitfield containing the flags:
3141 * ERR_FATAL in any fatal error case
3142 * ERR_ALERT if the reason of the error is available in err
3143 * ERR_WARN if a warning is available into err
3144 * The value 0 means there is no error nor warning and
3145 * the operation succeed.
3146 */
3147static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3148{
3149 int errcode = 0;
3150 STACK_OF(X509) *find_chain = NULL;
3151
3152 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3153 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3154 err && *err ? *err : "", path);
3155 errcode |= ERR_ALERT | ERR_FATAL;
3156 return errcode;
3157 }
3158
3159 /* Load certificate chain */
3160 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3161 if (errcode & ERR_CODE)
3162 goto end;
3163
William Lallemandfa892222019-07-23 16:06:08 +02003164#ifndef OPENSSL_NO_DH
3165 /* store a NULL pointer to indicate we have not yet loaded
3166 a custom DH param file */
3167 if (ssl_dh_ptr_index >= 0) {
3168 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3169 }
3170
Emeric Brun7a883362019-10-17 13:27:40 +02003171 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3172 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003173 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3174 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003175 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003176 }
3177#endif
3178
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003179#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003180 if (sctl_ex_index >= 0 && ckch->sctl) {
3181 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3182 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003183 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003184 errcode |= ERR_ALERT | ERR_FATAL;
3185 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003186 }
3187 }
3188#endif
3189
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003190#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003191 /* Load OCSP Info into context */
3192 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003193 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003194 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",
3195 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003196 errcode |= ERR_ALERT | ERR_FATAL;
3197 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003198 }
3199 }
William Lallemand246c0242019-10-11 08:59:13 +02003200#endif
3201
Emeric Bruna96b5822019-10-17 13:25:14 +02003202 end:
3203 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003204}
3205
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003206
3207/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3208 * Returns a bitfield containing the flags:
3209 * ERR_FATAL in any fatal error case
3210 * ERR_ALERT if the reason of the error is available in err
3211 * ERR_WARN if a warning is available into err
3212 * The value 0 means there is no error nor warning and
3213 * the operation succeed.
3214 */
3215static int ssl_sock_put_srv_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch,
3216 SSL_CTX *ctx, char **err)
3217{
3218 int errcode = 0;
3219 STACK_OF(X509) *find_chain = NULL;
3220
3221 /* Load the private key */
3222 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3223 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3224 err && *err ? *err : "", path);
3225 errcode |= ERR_ALERT | ERR_FATAL;
3226 }
3227
3228 /* Load certificate chain */
3229 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3230 if (errcode & ERR_CODE)
3231 goto end;
3232
3233 if (SSL_CTX_check_private_key(ctx) <= 0) {
3234 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3235 err && *err ? *err : "", path);
3236 errcode |= ERR_ALERT | ERR_FATAL;
3237 }
3238
3239end:
3240 return errcode;
3241}
3242
3243
William Lallemand614ca0d2019-10-07 13:52:11 +02003244/*
3245 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003246 *
3247 * Returns a bitfield containing the flags:
3248 * ERR_FATAL in any fatal error case
3249 * ERR_ALERT if the reason of the error is available in err
3250 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003251 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003252int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003253 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003254{
William Lallemandc9402072019-05-15 15:33:54 +02003255 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003256 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003257 int order = 0;
3258 X509_NAME *xname;
3259 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003260 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003261 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003262#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3263 STACK_OF(GENERAL_NAME) *names;
3264#endif
William Lallemand36b84632019-07-18 19:28:17 +02003265 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003266 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003267 int errcode = 0;
3268
3269 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003270
William Lallemande3af8fb2019-10-08 11:36:53 +02003271 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003272 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003273
William Lallemande3af8fb2019-10-08 11:36:53 +02003274 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003275
William Lallemandc9402072019-05-15 15:33:54 +02003276 ctx = SSL_CTX_new(SSLv23_server_method());
3277 if (!ctx) {
3278 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3279 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003280 errcode |= ERR_ALERT | ERR_FATAL;
3281 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003282 }
3283
Emeric Bruna96b5822019-10-17 13:25:14 +02003284 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3285 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003286 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003287
3288 ckch_inst = ckch_inst_new();
3289 if (!ckch_inst) {
3290 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3291 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003292 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003293 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003294 }
3295
William Lallemand36b84632019-07-18 19:28:17 +02003296 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003297 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003298 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003299 switch(EVP_PKEY_base_id(pkey)) {
3300 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003301 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003302 break;
3303 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003304 kinfo.sig = TLSEXT_signature_ecdsa;
3305 break;
3306 case EVP_PKEY_DSA:
3307 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003308 break;
3309 }
3310 EVP_PKEY_free(pkey);
3311 }
3312
Emeric Brun50bcecc2013-04-22 13:05:23 +02003313 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003314 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003315 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 +02003316 if (order < 0) {
3317 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003318 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003319 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003320 }
3321 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003322 }
3323 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003324#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003325 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003326 if (names) {
3327 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3328 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3329 if (name->type == GEN_DNS) {
3330 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003331 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003332 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003333 if (order < 0) {
3334 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003335 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003336 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003337 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003338 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003339 }
3340 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003341 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003342 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003343#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003344 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003345 i = -1;
3346 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3347 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003348 ASN1_STRING *value;
3349
3350 value = X509_NAME_ENTRY_get_data(entry);
3351 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003352 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003353 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003354 if (order < 0) {
3355 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003356 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003357 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003358 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003359 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003360 }
3361 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003362 /* we must not free the SSL_CTX anymore below, since it's already in
3363 * the tree, so it will be discovered and cleaned in time.
3364 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003365
Emeric Brunfc0421f2012-09-07 17:30:07 +02003366#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003367 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003368 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3369 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003370 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003371 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003372 }
3373#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003374 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003375 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003376 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003377 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003378 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003379 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003380 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003381
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003382 /* Always keep a reference to the newly constructed SSL_CTX in the
3383 * instance. This way if the instance has no SNIs, the SSL_CTX will
3384 * still be linked. */
3385 SSL_CTX_up_ref(ctx);
3386 ckch_inst->ctx = ctx;
3387
William Lallemand9117de92019-10-04 00:29:42 +02003388 /* everything succeed, the ckch instance can be used */
3389 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003390 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003391 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003392
William Lallemand02e19a52020-04-08 16:11:26 +02003393 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3394
Emeric Brun054563d2019-10-17 13:16:58 +02003395 *ckchi = ckch_inst;
3396 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003397
3398error:
3399 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003400 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003401 if (ckch_inst->is_default)
3402 SSL_CTX_free(ctx);
3403
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003404 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003405 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003406 }
William Lallemandd9199372019-10-04 15:37:05 +02003407 SSL_CTX_free(ctx);
3408
Emeric Brun054563d2019-10-17 13:16:58 +02003409 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003410}
3411
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003412
3413/*
3414 * This function allocate a ckch_inst that will be used on the backend side
3415 * (server line)
3416 *
3417 * Returns a bitfield containing the flags:
3418 * ERR_FATAL in any fatal error case
3419 * ERR_ALERT if the reason of the error is available in err
3420 * ERR_WARN if a warning is available into err
3421 */
3422int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003423 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003424{
3425 SSL_CTX *ctx;
3426 struct cert_key_and_chain *ckch;
3427 struct ckch_inst *ckch_inst = NULL;
3428 int errcode = 0;
3429
3430 *ckchi = NULL;
3431
3432 if (!ckchs || !ckchs->ckch)
3433 return ERR_FATAL;
3434
3435 ckch = ckchs->ckch;
3436
3437 ctx = SSL_CTX_new(SSLv23_client_method());
3438 if (!ctx) {
3439 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3440 err && *err ? *err : "", path);
3441 errcode |= ERR_ALERT | ERR_FATAL;
3442 goto error;
3443 }
3444
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003445 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, ckch, ctx, err);
3446 if (errcode & ERR_CODE)
3447 goto error;
3448
3449 ckch_inst = ckch_inst_new();
3450 if (!ckch_inst) {
3451 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3452 err && *err ? *err : "", path);
3453 errcode |= ERR_ALERT | ERR_FATAL;
3454 goto error;
3455 }
3456
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003457 /* everything succeed, the ckch instance can be used */
3458 ckch_inst->bind_conf = NULL;
3459 ckch_inst->ssl_conf = NULL;
3460 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003461 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003462 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003463
3464 *ckchi = ckch_inst;
3465 return errcode;
3466
3467error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003468 SSL_CTX_free(ctx);
3469
3470 return errcode;
3471}
3472
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003473/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003474static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3475 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003476 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003477{
Emeric Brun054563d2019-10-17 13:16:58 +02003478 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003479
3480 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003481 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 +02003482
Emeric Brun054563d2019-10-17 13:16:58 +02003483 if (errcode & ERR_CODE)
3484 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003485
William Lallemand24bde432020-03-09 16:48:43 +01003486 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003487
3488 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003489 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003490 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003491}
3492
William Lallemanddb26e2b2021-01-26 12:01:46 +01003493/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3494 * fill the SSL_CTX of the server.
3495 *
3496 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003497static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003498 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003499{
3500 int errcode = 0;
3501
3502 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003503 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003504
3505 if (errcode & ERR_CODE)
3506 return errcode;
3507
William Lallemanddb26e2b2021-01-26 12:01:46 +01003508 (*ckch_inst)->server = server;
3509 /* Keep the reference to the SSL_CTX in the server. */
3510 SSL_CTX_up_ref((*ckch_inst)->ctx);
3511 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003512 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003513 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003514 return errcode;
3515}
3516
William Lallemand6be66ec2020-03-06 22:26:32 +01003517
William Lallemand4c68bba2020-03-30 18:45:10 +02003518
3519
3520/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3521 * done once. Zero is returned if the operation fails. No error is returned
3522 * if the random is said as not implemented, because we expect that openssl
3523 * will use another method once needed.
3524 */
3525static int ssl_initialize_random()
3526{
3527 unsigned char random;
3528 static int random_initialized = 0;
3529
3530 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3531 random_initialized = 1;
3532
3533 return random_initialized;
3534}
3535
William Lallemand2954c472020-03-06 21:54:13 +01003536/* Load a crt-list file, this is done in 2 parts:
3537 * - store the content of the file in a crtlist structure with crtlist_entry structures
3538 * - generate the instances by iterating on entries in the crtlist struct
3539 *
3540 * Nothing is locked there, this function is used in the configuration parser.
3541 *
3542 * Returns a set of ERR_* flags possibly with an error in <err>.
3543 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003544int 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 +01003545{
3546 struct crtlist *crtlist = NULL;
3547 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003548 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003549 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003550 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003551 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003552
William Lallemand79d31ec2020-03-25 15:10:49 +01003553 bind_conf_node = malloc(sizeof(*bind_conf_node));
3554 if (!bind_conf_node) {
3555 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3556 cfgerr |= ERR_FATAL | ERR_ALERT;
3557 goto error;
3558 }
3559 bind_conf_node->next = NULL;
3560 bind_conf_node->bind_conf = bind_conf;
3561
William Lallemand41ca9302020-04-08 13:15:18 +02003562 /* strip trailing slashes, including first one */
3563 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3564 *end = 0;
3565
William Lallemand2954c472020-03-06 21:54:13 +01003566 /* look for an existing crtlist or create one */
3567 eb = ebst_lookup(&crtlists_tree, file);
3568 if (eb) {
3569 crtlist = ebmb_entry(eb, struct crtlist, node);
3570 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003571 /* load a crt-list OR a directory */
3572 if (dir)
3573 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3574 else
3575 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3576
William Lallemand2954c472020-03-06 21:54:13 +01003577 if (!(cfgerr & ERR_CODE))
3578 ebst_insert(&crtlists_tree, &crtlist->node);
3579 }
3580
3581 if (cfgerr & ERR_CODE) {
3582 cfgerr |= ERR_FATAL | ERR_ALERT;
3583 goto error;
3584 }
3585
3586 /* generates ckch instance from the crtlist_entry */
3587 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3588 struct ckch_store *store;
3589 struct ckch_inst *ckch_inst = NULL;
3590
3591 store = entry->node.key;
3592 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3593 if (cfgerr & ERR_CODE) {
3594 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3595 goto error;
3596 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003597 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003598 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003599 }
William Lallemand2954c472020-03-06 21:54:13 +01003600
William Lallemand79d31ec2020-03-25 15:10:49 +01003601 /* add the bind_conf to the list */
3602 bind_conf_node->next = crtlist->bind_conf;
3603 crtlist->bind_conf = bind_conf_node;
3604
William Lallemand2954c472020-03-06 21:54:13 +01003605 return cfgerr;
3606error:
3607 {
William Lallemand49398312020-03-30 17:01:33 +02003608 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003609 struct ckch_inst *inst, *s_inst;
3610
William Lallemand49398312020-03-30 17:01:33 +02003611 lastentry = entry; /* which entry we tried to generate last */
3612 if (lastentry) {
3613 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3614 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3615 break;
3616
3617 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003618
William Lallemand49398312020-03-30 17:01:33 +02003619 /* this was not generated for this bind_conf, skip */
3620 if (inst->bind_conf != bind_conf)
3621 continue;
3622
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003623 /* free the sni_ctx and instance */
3624 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003625 }
William Lallemand2954c472020-03-06 21:54:13 +01003626 }
William Lallemand2954c472020-03-06 21:54:13 +01003627 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003628 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003629 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003630 return cfgerr;
3631}
3632
William Lallemand06b22a82020-03-16 14:45:55 +01003633/* Returns a set of ERR_* flags possibly with an error in <err>. */
3634int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3635{
3636 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003637 int cfgerr = 0;
3638 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003639 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003640 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003641
3642 if ((ckchs = ckchs_lookup(path))) {
3643 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003644 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3645 found++;
3646 } else if (stat(path, &buf) == 0) {
3647 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003648 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003649 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003650 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003651 cfgerr |= ERR_ALERT | ERR_FATAL;
3652 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003653 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003654 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003655 }
3656 } else {
3657 /* stat failed, could be a bundle */
3658 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003659 char fp[MAXPATHLEN+1] = {0};
3660 int n = 0;
3661
3662 /* Load all possible certs and keys in separate ckch_store */
3663 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3664 struct stat buf;
3665 int ret;
3666
3667 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3668 if (ret > sizeof(fp))
3669 continue;
3670
3671 if ((ckchs = ckchs_lookup(fp))) {
3672 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003673 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003674 } else {
3675 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003676 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003677 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003678 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003679 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003680 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3681 }
3682 }
3683 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003684#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3685 if (found) {
3686 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3687 err && *err ? *err : "", path);
3688 cfgerr |= ERR_ALERT | ERR_FATAL;
3689 }
3690#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003691 }
3692 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003693 if (!found) {
3694 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3695 err && *err ? *err : "", path, strerror(errno));
3696 cfgerr |= ERR_ALERT | ERR_FATAL;
3697 }
William Lallemand06b22a82020-03-16 14:45:55 +01003698
3699 return cfgerr;
3700}
3701
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003702
3703/* Create a full ssl context and ckch instance that will be used for a specific
3704 * backend server (server configuration line).
3705 * Returns a set of ERR_* flags possibly with an error in <err>.
3706 */
3707int ssl_sock_load_srv_cert(char *path, struct server *server, char **err)
3708{
3709 struct stat buf;
3710 int cfgerr = 0;
3711 struct ckch_store *ckchs;
3712 int found = 0; /* did we found a file to load ? */
3713
3714 if ((ckchs = ckchs_lookup(path))) {
3715 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01003716 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003717 found++;
3718 } else if (stat(path, &buf) == 0) {
3719 /* We do not manage directories on backend side. */
3720 if (S_ISDIR(buf.st_mode) == 0) {
3721 ++found;
3722 ckchs = ckchs_load_cert_file(path, err);
3723 if (!ckchs)
3724 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003725 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003726 }
3727 }
3728 if (!found) {
3729 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3730 err && *err ? *err : "", path, strerror(errno));
3731 cfgerr |= ERR_ALERT | ERR_FATAL;
3732 }
3733
3734 return cfgerr;
3735}
3736
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003737/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003738static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003739ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003740{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003741 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003742 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003743 SSL_OP_ALL | /* all known workarounds for bugs */
3744 SSL_OP_NO_SSLv2 |
3745 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003746 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003747 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003748 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003749 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003750 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003751 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003752 SSL_MODE_ENABLE_PARTIAL_WRITE |
3753 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003754 SSL_MODE_RELEASE_BUFFERS |
3755 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003756 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003757 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003758 int flags = MC_SSL_O_ALL;
3759 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003760 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003761
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003762 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003763 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003764
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003765 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003766 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3767 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3768 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003769 else
3770 flags = conf_ssl_methods->flags;
3771
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003772 min = conf_ssl_methods->min;
3773 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003774
3775 /* default minimum is TLSV12, */
3776 if (!min) {
3777 if (!max || (max >= default_min_ver)) {
3778 min = default_min_ver;
3779 } else {
3780 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). "
3781 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3782 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3783 min = max;
3784 }
3785 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003786 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003787 if (min)
3788 flags |= (methodVersions[min].flag - 1);
3789 if (max)
3790 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003791 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003792 min = max = CONF_TLSV_NONE;
3793 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003794 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003795 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003796 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003797 if (min) {
3798 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003799 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3800 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3801 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3802 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003803 hole = 0;
3804 }
3805 max = i;
3806 }
3807 else {
3808 min = max = i;
3809 }
3810 }
3811 else {
3812 if (min)
3813 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003814 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003815 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003816 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3817 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003818 cfgerr += 1;
3819 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003820 /* save real min/max in bind_conf */
3821 conf_ssl_methods->min = min;
3822 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003823
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003824#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003825 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003826 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003827 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003828 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003829 else
William Lallemandd0712f32020-06-11 17:34:00 +02003830 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
3831 /* clear every version flags in case SSL_CTX_new()
3832 * returns an SSL_CTX with disabled versions */
3833 SSL_CTX_clear_options(ctx, methodVersions[i].option);
3834
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003835 if (flags & methodVersions[i].flag)
3836 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02003837
3838 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003839#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003840 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003841 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3842 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003843#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003844
3845 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3846 options |= SSL_OP_NO_TICKET;
3847 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3848 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003849
3850#ifdef SSL_OP_NO_RENEGOTIATION
3851 options |= SSL_OP_NO_RENEGOTIATION;
3852#endif
3853
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003854 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003855
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05003856#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003857 if (global_ssl.async)
3858 mode |= SSL_MODE_ASYNC;
3859#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003860 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003861 if (global_ssl.life_time)
3862 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003863
3864#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3865#ifdef OPENSSL_IS_BORINGSSL
3866 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3867 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003868#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003869 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003870 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003871 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3872 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003873#else
3874 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003875#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003876 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003877#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003878 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003879}
3880
William Lallemand4f45bb92017-10-30 20:08:51 +01003881
3882static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3883{
3884 if (first == block) {
3885 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3886 if (first->len > 0)
3887 sh_ssl_sess_tree_delete(sh_ssl_sess);
3888 }
3889}
3890
3891/* return first block from sh_ssl_sess */
3892static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3893{
3894 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3895
3896}
3897
3898/* store a session into the cache
3899 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3900 * data: asn1 encoded session
3901 * data_len: asn1 encoded session length
3902 * Returns 1 id session was stored (else 0)
3903 */
3904static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3905{
3906 struct shared_block *first;
3907 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3908
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003909 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003910 if (!first) {
3911 /* Could not retrieve enough free blocks to store that session */
3912 return 0;
3913 }
3914
3915 /* STORE the key in the first elem */
3916 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3917 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3918 first->len = sizeof(struct sh_ssl_sess_hdr);
3919
3920 /* it returns the already existing node
3921 or current node if none, never returns null */
3922 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3923 if (oldsh_ssl_sess != sh_ssl_sess) {
3924 /* NOTE: Row couldn't be in use because we lock read & write function */
3925 /* release the reserved row */
3926 shctx_row_dec_hot(ssl_shctx, first);
3927 /* replace the previous session already in the tree */
3928 sh_ssl_sess = oldsh_ssl_sess;
3929 /* ignore the previous session data, only use the header */
3930 first = sh_ssl_sess_first_block(sh_ssl_sess);
3931 shctx_row_inc_hot(ssl_shctx, first);
3932 first->len = sizeof(struct sh_ssl_sess_hdr);
3933 }
3934
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003935 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01003936 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003937 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01003938 }
3939
3940 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003941
3942 return 1;
3943}
William Lallemanded0b5ad2017-10-30 19:36:36 +01003944
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003945/* SSL callback used when a new session is created while connecting to a server */
3946static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
3947{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02003948 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003949 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003950
Willy Tarreau07d94e42018-09-20 10:57:52 +02003951 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003952
William Lallemand3ce6eed2021-02-08 10:43:44 +01003953 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
3954 * one cache per thread, it only prevents to flush it from the CLI in
3955 * another thread */
3956
Olivier Houcharde6060c52017-11-16 17:42:52 +01003957 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
3958 int len;
3959 unsigned char *ptr;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003960
Olivier Houcharde6060c52017-11-16 17:42:52 +01003961 len = i2d_SSL_SESSION(sess, NULL);
William Lallemand3ce6eed2021-02-08 10:43:44 +01003962 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003963 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
3964 ptr = s->ssl_ctx.reused_sess[tid].ptr;
3965 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01003966 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
3967 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01003968 s->ssl_ctx.reused_sess[tid].allocated_size = len;
3969 }
3970 if (s->ssl_ctx.reused_sess[tid].ptr) {
3971 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
3972 &ptr);
3973 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01003974 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003975 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01003976 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003977 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01003978 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003979 }
3980
3981 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003982}
3983
Olivier Houcharde6060c52017-11-16 17:42:52 +01003984
William Lallemanded0b5ad2017-10-30 19:36:36 +01003985/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01003986int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003987{
3988 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
3989 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
3990 unsigned char *p;
3991 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02003992 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003993 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003994
3995 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003996 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02003997 * note: SSL_SESSION_set1_id is using
3998 * a memcpy so we need to use a different pointer
3999 * than sid_data or sid_ctx_data to avoid valgrind
4000 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004001 */
4002
4003 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004004
4005 /* copy value in an other buffer */
4006 memcpy(encid, sid_data, sid_length);
4007
4008 /* pad with 0 */
4009 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4010 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4011
4012 /* force length to zero to avoid ASN1 encoding */
4013 SSL_SESSION_set1_id(sess, encid, 0);
4014
4015 /* force length to zero to avoid ASN1 encoding */
4016 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004017
4018 /* check if buffer is large enough for the ASN1 encoded session */
4019 data_len = i2d_SSL_SESSION(sess, NULL);
4020 if (data_len > SHSESS_MAX_DATA_LEN)
4021 goto err;
4022
4023 p = encsess;
4024
4025 /* process ASN1 session encoding before the lock */
4026 i2d_SSL_SESSION(sess, &p);
4027
William Lallemanded0b5ad2017-10-30 19:36:36 +01004028
William Lallemanda3c77cf2017-10-30 23:44:40 +01004029 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004030 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004031 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004032 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004033err:
4034 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004035 SSL_SESSION_set1_id(sess, encid, sid_length);
4036 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004037
4038 return 0; /* do not increment session reference count */
4039}
4040
4041/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004042SSL_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 +01004043{
William Lallemand4f45bb92017-10-30 20:08:51 +01004044 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004045 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4046 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004047 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004048 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004049
4050 global.shctx_lookups++;
4051
4052 /* allow the session to be freed automatically by openssl */
4053 *do_copy = 0;
4054
4055 /* tree key is zeros padded sessionid */
4056 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4057 memcpy(tmpkey, key, key_len);
4058 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4059 key = tmpkey;
4060 }
4061
4062 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004063 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004064
4065 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004066 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4067 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004068 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004069 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004070 global.shctx_misses++;
4071 return NULL;
4072 }
4073
William Lallemand4f45bb92017-10-30 20:08:51 +01004074 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4075 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004076
William Lallemand4f45bb92017-10-30 20:08:51 +01004077 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 +01004078
William Lallemanda3c77cf2017-10-30 23:44:40 +01004079 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004080
4081 /* decode ASN1 session */
4082 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004083 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004084 /* Reset session id and session id contenxt */
4085 if (sess) {
4086 SSL_SESSION_set1_id(sess, key, key_len);
4087 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4088 }
4089
4090 return sess;
4091}
4092
William Lallemand4f45bb92017-10-30 20:08:51 +01004093
William Lallemanded0b5ad2017-10-30 19:36:36 +01004094/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004095void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004096{
William Lallemand4f45bb92017-10-30 20:08:51 +01004097 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004098 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4099 unsigned int sid_length;
4100 const unsigned char *sid_data;
4101 (void)ctx;
4102
4103 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4104 /* tree key is zeros padded sessionid */
4105 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4106 memcpy(tmpkey, sid_data, sid_length);
4107 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4108 sid_data = tmpkey;
4109 }
4110
William Lallemanda3c77cf2017-10-30 23:44:40 +01004111 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004112
4113 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004114 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4115 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004116 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004117 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004118 }
4119
4120 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004121 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004122}
4123
4124/* Set session cache mode to server and disable openssl internal cache.
4125 * Set shared cache callbacks on an ssl context.
4126 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004127void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004128{
4129 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4130
4131 if (!ssl_shctx) {
4132 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4133 return;
4134 }
4135
4136 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4137 SSL_SESS_CACHE_NO_INTERNAL |
4138 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4139
4140 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004141 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4142 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4143 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004144}
William Lallemand7d42ef52020-07-06 11:41:30 +02004145
4146/*
4147 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4148 *
4149 * The format is:
4150 * * <Label> <space> <ClientRandom> <space> <Secret>
4151 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4152 */
4153
William Lallemand722180a2021-06-09 16:46:12 +02004154#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004155void SSL_CTX_keylog(const SSL *ssl, const char *line)
4156{
4157 struct ssl_keylog *keylog;
4158 char *lastarg = NULL;
4159 char *dst = NULL;
4160
4161 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4162 if (!keylog)
4163 return;
4164
4165 lastarg = strrchr(line, ' ');
4166 if (lastarg == NULL || ++lastarg == NULL)
4167 return;
4168
4169 dst = pool_alloc(pool_head_ssl_keylog_str);
4170 if (!dst)
4171 return;
4172
4173 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4174 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4175
4176 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4177 if (keylog->client_random)
4178 goto error;
4179 keylog->client_random = dst;
4180
4181 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4182 if (keylog->client_early_traffic_secret)
4183 goto error;
4184 keylog->client_early_traffic_secret = dst;
4185
4186 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4187 if(keylog->client_handshake_traffic_secret)
4188 goto error;
4189 keylog->client_handshake_traffic_secret = dst;
4190
4191 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4192 if (keylog->server_handshake_traffic_secret)
4193 goto error;
4194 keylog->server_handshake_traffic_secret = dst;
4195
4196 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4197 if (keylog->client_traffic_secret_0)
4198 goto error;
4199 keylog->client_traffic_secret_0 = dst;
4200
4201 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4202 if (keylog->server_traffic_secret_0)
4203 goto error;
4204 keylog->server_traffic_secret_0 = dst;
4205
4206 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4207 if (keylog->early_exporter_secret)
4208 goto error;
4209 keylog->early_exporter_secret = dst;
4210
4211 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4212 if (keylog->exporter_secret)
4213 goto error;
4214 keylog->exporter_secret = dst;
4215 } else {
4216 goto error;
4217 }
4218
4219 return;
4220
4221error:
4222 pool_free(pool_head_ssl_keylog_str, dst);
4223
4224 return;
4225}
4226#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004227
William Lallemand8b453912019-11-21 15:48:10 +01004228/*
4229 * This function applies the SSL configuration on a SSL_CTX
4230 * It returns an error code and fills the <err> buffer
4231 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004232static 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 +01004233{
4234 struct proxy *curproxy = bind_conf->frontend;
4235 int cfgerr = 0;
4236 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004237 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004238 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004239#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004240 const char *conf_ciphersuites;
4241#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004242 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004243
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004244 if (ssl_conf) {
4245 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4246 int i, min, max;
4247 int flags = MC_SSL_O_ALL;
4248
4249 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004250 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4251 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004252 if (min)
4253 flags |= (methodVersions[min].flag - 1);
4254 if (max)
4255 flags |= ~((methodVersions[max].flag << 1) - 1);
4256 min = max = CONF_TLSV_NONE;
4257 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4258 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4259 if (min)
4260 max = i;
4261 else
4262 min = max = i;
4263 }
4264 /* save real min/max */
4265 conf_ssl_methods->min = min;
4266 conf_ssl_methods->max = max;
4267 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004268 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4269 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004270 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004271 }
4272 }
4273
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004274 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004275 case SSL_SOCK_VERIFY_NONE:
4276 verify = SSL_VERIFY_NONE;
4277 break;
4278 case SSL_SOCK_VERIFY_OPTIONAL:
4279 verify = SSL_VERIFY_PEER;
4280 break;
4281 case SSL_SOCK_VERIFY_REQUIRED:
4282 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4283 break;
4284 }
4285 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4286 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004287 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 +01004288 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 +01004289 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 +01004290 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004291 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004292 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004293 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004294 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004295 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004296 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004297 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4298 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4299 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4300 cfgerr |= ERR_ALERT | ERR_FATAL;
4301 }
4302 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004303 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004304 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 +02004305 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004306 }
Emeric Brun850efd52014-01-29 12:24:34 +01004307 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004308 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4309 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004310 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004311 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004312#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004313 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004314 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4315
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004316 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004317 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4318 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004319 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004320 }
Emeric Brun561e5742012-10-02 15:20:55 +02004321 else {
4322 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4323 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004324 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004325#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004326 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004327 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004328#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004329 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004330 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004331 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4332 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004333 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004334 }
4335 }
4336#endif
4337
William Lallemand4f45bb92017-10-30 20:08:51 +01004338 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004339 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4340 if (conf_ciphers &&
4341 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004342 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4343 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004344 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004345 }
4346
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004347#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004348 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4349 if (conf_ciphersuites &&
4350 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004351 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4352 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004353 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004354 }
4355#endif
4356
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004357#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004358 /* If tune.ssl.default-dh-param has not been set,
4359 neither has ssl-default-dh-file and no static DH
4360 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004361 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004362 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004363 (ssl_dh_ptr_index == -1 ||
4364 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004365 /* default to dh-param 2048 */
4366 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004367 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004368
Willy Tarreauef934602016-12-22 23:12:01 +01004369 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004370 if (local_dh_1024 == NULL) {
4371 local_dh_1024 = ssl_get_dh_1024();
4372 }
Willy Tarreauef934602016-12-22 23:12:01 +01004373 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004374 if (local_dh_2048 == NULL) {
4375 local_dh_2048 = ssl_get_dh_2048();
4376 }
Willy Tarreauef934602016-12-22 23:12:01 +01004377 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004378 if (local_dh_4096 == NULL) {
4379 local_dh_4096 = ssl_get_dh_4096();
4380 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004381 }
4382 }
4383 }
4384#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004385
Emeric Brunfc0421f2012-09-07 17:30:07 +02004386 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004387#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004388 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004389#endif
William Lallemand722180a2021-06-09 16:46:12 +02004390#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004391 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
4392#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004393
Bernard Spil13c53f82018-02-15 13:34:58 +01004394#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004395 ssl_conf_cur = NULL;
4396 if (ssl_conf && ssl_conf->npn_str)
4397 ssl_conf_cur = ssl_conf;
4398 else if (bind_conf->ssl_conf.npn_str)
4399 ssl_conf_cur = &bind_conf->ssl_conf;
4400 if (ssl_conf_cur)
4401 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004402#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004403#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004404 ssl_conf_cur = NULL;
4405 if (ssl_conf && ssl_conf->alpn_str)
4406 ssl_conf_cur = ssl_conf;
4407 else if (bind_conf->ssl_conf.alpn_str)
4408 ssl_conf_cur = &bind_conf->ssl_conf;
4409 if (ssl_conf_cur)
4410 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004411#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004412#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004413 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4414 if (conf_curves) {
4415 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004416 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4417 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004418 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004419 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004420 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004421 }
4422#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004423#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004424 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004425 int i;
4426 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004427#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004428 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004429 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4430 NULL);
4431
4432 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004433 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004434 return cfgerr;
4435 }
4436#else
4437 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4438 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4439 ECDHE_DEFAULT_CURVE);
4440#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004441
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004442 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004443 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004444 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4445 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004446 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004447 }
4448 else {
4449 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4450 EC_KEY_free(ecdh);
4451 }
4452 }
4453#endif
4454
Emeric Brunfc0421f2012-09-07 17:30:07 +02004455 return cfgerr;
4456}
4457
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004458
4459/*
4460 * Prepare the SSL_CTX based on the bind line configuration.
4461 * Since the CA file loading is made depending on the verify option of the bind
4462 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4463 * If we want to create a link between the CA file entry and the corresponding
4464 * ckch instance (for CA file hot update), it needs to be done after
4465 * ssl_sock_prepare_ctx.
4466 * Returns 0 in case of success.
4467 */
4468int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4469 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4470{
4471 int errcode = 0;
4472
4473 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4474 if (!errcode && ckch_inst)
4475 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4476
4477 return errcode;
4478}
4479
Evan Broderbe554312013-06-27 00:05:25 -07004480static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4481{
4482 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4483 size_t prefixlen, suffixlen;
4484
4485 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004486 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004487 return 1;
4488
Evan Broderbe554312013-06-27 00:05:25 -07004489 /* The rest of this logic is based on RFC 6125, section 6.4.3
4490 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4491
Emeric Bruna848dae2013-10-08 11:27:28 +02004492 pattern_wildcard = NULL;
4493 pattern_left_label_end = pattern;
4494 while (*pattern_left_label_end != '.') {
4495 switch (*pattern_left_label_end) {
4496 case 0:
4497 /* End of label not found */
4498 return 0;
4499 case '*':
4500 /* If there is more than one wildcards */
4501 if (pattern_wildcard)
4502 return 0;
4503 pattern_wildcard = pattern_left_label_end;
4504 break;
4505 }
4506 pattern_left_label_end++;
4507 }
4508
4509 /* If it's not trivial and there is no wildcard, it can't
4510 * match */
4511 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004512 return 0;
4513
4514 /* Make sure all labels match except the leftmost */
4515 hostname_left_label_end = strchr(hostname, '.');
4516 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004517 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004518 return 0;
4519
4520 /* Make sure the leftmost label of the hostname is long enough
4521 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004522 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004523 return 0;
4524
4525 /* Finally compare the string on either side of the
4526 * wildcard */
4527 prefixlen = pattern_wildcard - pattern;
4528 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004529 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4530 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004531 return 0;
4532
4533 return 1;
4534}
4535
4536static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4537{
4538 SSL *ssl;
4539 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004540 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004541 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004542 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004543
4544 int depth;
4545 X509 *cert;
4546 STACK_OF(GENERAL_NAME) *alt_names;
4547 int i;
4548 X509_NAME *cert_subject;
4549 char *str;
4550
4551 if (ok == 0)
4552 return ok;
4553
4554 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004555 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004556 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004557
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004558 /* We're checking if the provided hostnames match the desired one. The
4559 * desired hostname comes from the SNI we presented if any, or if not
4560 * provided then it may have been explicitly stated using a "verifyhost"
4561 * directive. If neither is set, we don't care about the name so the
4562 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004563 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004564 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004565 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004566 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004567 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004568 if (!servername)
4569 return ok;
4570 }
Evan Broderbe554312013-06-27 00:05:25 -07004571
4572 /* We only need to verify the CN on the actual server cert,
4573 * not the indirect CAs */
4574 depth = X509_STORE_CTX_get_error_depth(ctx);
4575 if (depth != 0)
4576 return ok;
4577
4578 /* At this point, the cert is *not* OK unless we can find a
4579 * hostname match */
4580 ok = 0;
4581
4582 cert = X509_STORE_CTX_get_current_cert(ctx);
4583 /* It seems like this might happen if verify peer isn't set */
4584 if (!cert)
4585 return ok;
4586
4587 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4588 if (alt_names) {
4589 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4590 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4591 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004592#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004593 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4594#else
Evan Broderbe554312013-06-27 00:05:25 -07004595 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004596#endif
Evan Broderbe554312013-06-27 00:05:25 -07004597 ok = ssl_sock_srv_hostcheck(str, servername);
4598 OPENSSL_free(str);
4599 }
4600 }
4601 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004602 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004603 }
4604
4605 cert_subject = X509_get_subject_name(cert);
4606 i = -1;
4607 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4608 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004609 ASN1_STRING *value;
4610 value = X509_NAME_ENTRY_get_data(entry);
4611 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004612 ok = ssl_sock_srv_hostcheck(str, servername);
4613 OPENSSL_free(str);
4614 }
4615 }
4616
Willy Tarreau71d058c2017-07-26 20:09:56 +02004617 /* report the mismatch and indicate if SNI was used or not */
4618 if (!ok && !conn->err_code)
4619 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004620 return ok;
4621}
4622
Emeric Brun94324a42012-10-11 14:00:19 +02004623/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004624int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004625{
4626 int cfgerr = 0;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004627 SSL_CTX *ctx = srv->ssl_ctx.ctx;
Emeric Brun94324a42012-10-11 14:00:19 +02004628
Thierry Fournier383085f2013-01-24 14:15:43 +01004629 /* Make sure openssl opens /dev/urandom before the chroot */
4630 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004631 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004632 cfgerr++;
4633 }
4634
Willy Tarreaufce03112015-01-15 21:32:40 +01004635 /* Automatic memory computations need to know we use SSL there */
4636 global.ssl_used_backend = 1;
4637
4638 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004639 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004640 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004641 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02004642 cfgerr++;
4643 return cfgerr;
4644 }
4645 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004646 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004647 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004648
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004649 /* The context will be uninitialized if there wasn't any "cert" option
4650 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004651 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004652 ctx = SSL_CTX_new(SSLv23_client_method());
4653 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004654 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004655 cfgerr++;
4656 return cfgerr;
4657 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004658
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004659 srv->ssl_ctx.ctx = ctx;
4660 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004661
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004662 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 +01004663
4664 return cfgerr;
4665}
4666
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004667/* Initialize an SSL context that will be used on the backend side.
4668 * Returns an error count.
4669 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004670static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004671{
4672 struct proxy *curproxy = srv->proxy;
4673 int cfgerr = 0;
4674 long options =
4675 SSL_OP_ALL | /* all known workarounds for bugs */
4676 SSL_OP_NO_SSLv2 |
4677 SSL_OP_NO_COMPRESSION;
4678 long mode =
4679 SSL_MODE_ENABLE_PARTIAL_WRITE |
4680 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4681 SSL_MODE_RELEASE_BUFFERS |
4682 SSL_MODE_SMALL_BUFFERS;
4683 int verify = SSL_VERIFY_NONE;
4684 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4685 int i, min, max, hole;
4686 int flags = MC_SSL_O_ALL;
4687
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004688 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004689 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
4690 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004691 else
4692 flags = conf_ssl_methods->flags;
4693
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004694 /* Real min and max should be determinate with configuration and openssl's capabilities */
4695 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004696 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004697 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004698 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004699
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004700 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004701 min = max = CONF_TLSV_NONE;
4702 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004703 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004704 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004705 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004706 if (min) {
4707 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02004708 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01004709 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4710 proxy_type_str(curproxy), curproxy->id, srv->id,
4711 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004712 hole = 0;
4713 }
4714 max = i;
4715 }
4716 else {
4717 min = max = i;
4718 }
4719 }
4720 else {
4721 if (min)
4722 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004723 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004724 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02004725 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004726 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004727 cfgerr += 1;
4728 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004729
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004730#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004731 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004732 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004733 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004734 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004735 else
4736 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4737 if (flags & methodVersions[i].flag)
4738 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004739#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004740 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004741 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4742 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004743#endif
4744
4745 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4746 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004747 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004748
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004749#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004750 if (global_ssl.async)
4751 mode |= SSL_MODE_ASYNC;
4752#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004753 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004754
Emeric Brun850efd52014-01-29 12:24:34 +01004755 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4756 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004757 switch (srv->ssl_ctx.verify) {
4758 case SSL_SOCK_VERIFY_NONE:
4759 verify = SSL_VERIFY_NONE;
4760 break;
4761 case SSL_SOCK_VERIFY_REQUIRED:
4762 verify = SSL_VERIFY_PEER;
4763 break;
4764 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004765 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004766 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004767 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004768 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004769 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004770 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004771 ha_alert("unable to set CA file '%s'.\n",
4772 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004773 cfgerr++;
4774 }
4775 }
Emeric Brun850efd52014-01-29 12:24:34 +01004776 else {
4777 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004778 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 +01004779 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004780 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01004781 cfgerr++;
4782 }
Emeric Brunef42d922012-10-11 16:11:36 +02004783#ifdef X509_V_FLAG_CRL_CHECK
4784 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004785 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02004786
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004787 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004788 ha_alert("unable to configure CRL file '%s'.\n",
4789 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004790 cfgerr++;
4791 }
4792 else {
4793 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4794 }
4795 }
4796#endif
4797 }
4798
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004799 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
4800 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004801 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004802 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004803 ha_alert("unable to set SSL cipher list to '%s'.\n",
4804 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004805 cfgerr++;
4806 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004807
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004808#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004809 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004810 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004811 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
4812 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004813 cfgerr++;
4814 }
4815#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004816#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4817 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004818 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01004819#endif
4820#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4821 if (srv->ssl_ctx.alpn_str)
4822 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4823#endif
4824
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004825
4826 return cfgerr;
4827}
4828
4829/*
4830 * Prepare the frontend's SSL_CTX based on the server line configuration.
4831 * Since the CA file loading is made depending on the verify option of the
4832 * server line, the link between the SSL_CTX and the CA file tree entry is
4833 * made here.
4834 * If we want to create a link between the CA file entry and the corresponding
4835 * ckch instance (for CA file hot update), it needs to be done after
4836 * ssl_sock_prepare_srv_ssl_ctx.
4837 * Returns an error count.
4838 */
4839int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
4840 struct ckch_inst *ckch_inst)
4841{
4842 int cfgerr = 0;
4843
4844 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
4845 if (!cfgerr && ckch_inst)
4846 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02004847
4848 return cfgerr;
4849}
4850
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004851
Frédéric Lécailleec216522020-11-23 14:33:30 +01004852/*
4853 * Create an initial CTX used to start the SSL connections.
4854 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
4855 * Returns 0 if succeeded, or something >0 if not.
4856 */
4857#ifdef USE_QUIC
4858static int ssl_initial_ctx(struct bind_conf *bind_conf)
4859{
4860 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
4861 return ssl_quic_initial_ctx(bind_conf);
4862 else
4863 return ssl_sock_initial_ctx(bind_conf);
4864}
4865#else
4866static int ssl_initial_ctx(struct bind_conf *bind_conf)
4867{
4868 return ssl_sock_initial_ctx(bind_conf);
4869}
4870#endif
4871
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004872/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004873 * be NULL, in which case nothing is done. Returns the number of errors
4874 * encountered.
4875 */
Willy Tarreau03209342016-12-22 17:08:28 +01004876int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004877{
4878 struct ebmb_node *node;
4879 struct sni_ctx *sni;
4880 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004881 int errcode = 0;
4882 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004883
Willy Tarreaufce03112015-01-15 21:32:40 +01004884 /* Automatic memory computations need to know we use SSL there */
4885 global.ssl_used_frontend = 1;
4886
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004887 /* Make sure openssl opens /dev/urandom before the chroot */
4888 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004889 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004890 err++;
4891 }
4892 /* Create initial_ctx used to start the ssl connection before do switchctx */
4893 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01004894 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004895 /* It should not be necessary to call this function, but it's
4896 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01004897 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004898 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
4899 }
4900 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02004901 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 +01004902 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004903
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004904 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004905 while (node) {
4906 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004907 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004908 /* only initialize the CTX on its first occurrence and
4909 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004910 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
4911 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004912 node = ebmb_next(node);
4913 }
4914
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004915 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004916 while (node) {
4917 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004918 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004919 /* only initialize the CTX on its first occurrence and
4920 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004921 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004922 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004923 node = ebmb_next(node);
4924 }
William Lallemand8b453912019-11-21 15:48:10 +01004925
4926 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004927 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004928 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004929 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004930 err++;
4931 }
4932
4933 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004934 return err;
4935}
4936
Willy Tarreau55d37912016-12-21 23:38:39 +01004937/* Prepares all the contexts for a bind_conf and allocates the shared SSL
4938 * context if needed. Returns < 0 on error, 0 on success. The warnings and
4939 * alerts are directly emitted since the rest of the stack does it below.
4940 */
4941int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
4942{
4943 struct proxy *px = bind_conf->frontend;
4944 int alloc_ctx;
4945 int err;
4946
4947 if (!bind_conf->is_ssl) {
4948 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004949 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
4950 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01004951 }
4952 return 0;
4953 }
4954 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004955 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004956 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
4957 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004958 }
4959 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004960 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
4961 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004962 return -1;
4963 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004964 }
William Lallemandc61c0b32017-12-04 18:46:39 +01004965 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004966 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02004967 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01004968 sizeof(*sh_ssl_sess_tree),
4969 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02004970 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004971 if (alloc_ctx == SHCTX_E_INIT_LOCK)
4972 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");
4973 else
4974 ha_alert("Unable to allocate SSL session cache.\n");
4975 return -1;
4976 }
4977 /* free block callback */
4978 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
4979 /* init the root tree within the extra space */
4980 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
4981 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01004982 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004983 err = 0;
4984 /* initialize all certificate contexts */
4985 err += ssl_sock_prepare_all_ctx(bind_conf);
4986
4987 /* initialize CA variables if the certificates generation is enabled */
4988 err += ssl_sock_load_ca(bind_conf);
4989
4990 return -err;
4991}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004992
4993/* release ssl context allocated for servers. */
4994void ssl_sock_free_srv_ctx(struct server *srv)
4995{
Olivier Houchardc7566002018-11-20 23:33:50 +01004996#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4997 if (srv->ssl_ctx.alpn_str)
Willy Tarreaue709e822021-02-26 21:06:32 +01004998 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01004999#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005000#ifdef OPENSSL_NPN_NEGOTIATED
Olivier Houchardc7566002018-11-20 23:33:50 +01005001 if (srv->ssl_ctx.npn_str)
Willy Tarreaue709e822021-02-26 21:06:32 +01005002 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005003#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005004 if (srv->ssl_ctx.reused_sess) {
5005 int i;
5006
5007 for (i = 0; i < global.nbthread; i++)
Willy Tarreaue709e822021-02-26 21:06:32 +01005008 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
5009 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005010 }
5011
Willy Tarreaue709e822021-02-26 21:06:32 +01005012 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005013 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005014 srv->ssl_ctx.ctx = NULL;
5015 }
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005016}
5017
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005018/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005019 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5020 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005021void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005022{
5023 struct ebmb_node *node, *back;
5024 struct sni_ctx *sni;
5025
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005026 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005027 while (node) {
5028 sni = ebmb_entry(node, struct sni_ctx, name);
5029 back = ebmb_next(node);
5030 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005031 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005032 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005033 free(sni);
5034 node = back;
5035 }
5036
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005037 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005038 while (node) {
5039 sni = ebmb_entry(node, struct sni_ctx, name);
5040 back = ebmb_next(node);
5041 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005042 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005043 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005044 free(sni);
5045 node = back;
5046 }
William Lallemandb2408692020-06-24 09:54:29 +02005047
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005048 SSL_CTX_free(bind_conf->initial_ctx);
5049 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005050 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005051 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005052 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005053 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005054}
William Lallemandb2408692020-06-24 09:54:29 +02005055
5056
5057void ssl_sock_deinit()
5058{
5059 crtlist_deinit(); /* must be free'd before the ckchs */
5060 ckch_deinit();
5061}
5062REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005063
Willy Tarreau795cdab2016-12-22 17:30:54 +01005064/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5065void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5066{
5067 ssl_sock_free_ca(bind_conf);
5068 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005069 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005070 free(bind_conf->ca_sign_file);
5071 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005072 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005073 free(bind_conf->keys_ref->filename);
5074 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005075 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005076 free(bind_conf->keys_ref);
5077 }
5078 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005079 bind_conf->ca_sign_pass = NULL;
5080 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005081}
5082
Christopher Faulet31af49d2015-06-09 17:29:50 +02005083/* Load CA cert file and private key used to generate certificates */
5084int
Willy Tarreau03209342016-12-22 17:08:28 +01005085ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005086{
Willy Tarreau03209342016-12-22 17:08:28 +01005087 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03005088 struct cert_key_and_chain *ckch = NULL;
5089 int ret = 0;
5090 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005091
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02005092 if (!bind_conf->generate_certs)
Shimi Gersner5846c492020-08-23 13:58:12 +03005093 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005094
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005095#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005096 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005097 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005098 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005099 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005100 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005101#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005102
Christopher Faulet31af49d2015-06-09 17:29:50 +02005103 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005104 ha_alert("Proxy '%s': cannot enable certificate generation, "
5105 "no CA certificate File configured at [%s:%d].\n",
5106 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005107 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005108 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005109
Shimi Gersner5846c492020-08-23 13:58:12 +03005110 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02005111 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03005112 if (!ckch) {
5113 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5114 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5115 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005116 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005117
5118 /* Try to parse file */
5119 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
5120 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5121 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005122 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005123 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005124 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005125
5126 /* Fail if missing cert or pkey */
5127 if ((!ckch->cert) || (!ckch->key)) {
5128 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5129 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5130 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005131 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005132
Shimi Gersner5846c492020-08-23 13:58:12 +03005133 /* Final assignment to bind */
5134 bind_conf->ca_sign_ckch = ckch;
5135 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005136
Shimi Gersner5846c492020-08-23 13:58:12 +03005137 failed:
5138 if (ckch) {
5139 ssl_sock_free_cert_key_and_chain_contents(ckch);
5140 free(ckch);
5141 }
5142
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005143 bind_conf->generate_certs = 0;
Shimi Gersner5846c492020-08-23 13:58:12 +03005144 ret++;
5145 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005146}
5147
5148/* Release CA cert and private key used to generate certificated */
5149void
5150ssl_sock_free_ca(struct bind_conf *bind_conf)
5151{
Shimi Gersner5846c492020-08-23 13:58:12 +03005152 if (bind_conf->ca_sign_ckch) {
5153 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005154 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005155 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005156}
5157
Emeric Brun46591952012-05-18 15:47:34 +02005158/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005159 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5160 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5161 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5162 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005163 * 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 +01005164 * as parameters to this function.
5165 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5166 * CO_ER_SSL_NO_MEM.
5167 */
5168int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5169 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5170{
5171 int retry = 1;
5172
5173 retry:
5174 /* Alloc a new SSL session. */
5175 *ssl = SSL_new(ssl_ctx);
5176 if (!*ssl) {
5177 if (!retry--)
5178 goto err;
5179
5180 pool_gc(NULL);
5181 goto retry;
5182 }
5183
5184 *bio = BIO_new(bio_meth);
5185 if (!*bio) {
5186 SSL_free(*ssl);
5187 *ssl = NULL;
5188 if (!retry--)
5189 goto err;
5190
5191 pool_gc(NULL);
5192 goto retry;
5193 }
5194
5195 BIO_set_data(*bio, ctx);
5196 SSL_set_bio(*ssl, *bio, *bio);
5197
5198 /* set connection pointer. */
5199 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5200 SSL_free(*ssl);
5201 *ssl = NULL;
5202 if (!retry--)
5203 goto err;
5204
5205 pool_gc(NULL);
5206 goto retry;
5207 }
5208
5209 return 0;
5210
5211 err:
5212 conn->err_code = CO_ER_SSL_NO_MEM;
5213 return -1;
5214}
5215
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005216/* This function is called when all the XPRT have been initialized. We can
5217 * now attempt to start the SSL handshake.
5218 */
5219static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5220{
5221 struct ssl_sock_ctx *ctx = xprt_ctx;
5222
5223 if (ctx->xprt->start) {
5224 int ret;
5225
5226 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5227 if (ret < 0)
5228 return ret;
5229 }
5230 tasklet_wakeup(ctx->wait_event.tasklet);
5231
5232 return 0;
5233}
5234
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005235/*
Emeric Brun46591952012-05-18 15:47:34 +02005236 * This function is called if SSL * context is not yet allocated. The function
5237 * is designed to be called before any other data-layer operation and sets the
5238 * handshake flag on the connection. It is safe to call it multiple times.
5239 * It returns 0 on success and -1 in error case.
5240 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005241static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005242{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005243 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005244 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005245 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005246 return 0;
5247
Olivier Houchard66ab4982019-02-26 18:37:15 +01005248 ctx = pool_alloc(ssl_sock_ctx_pool);
5249 if (!ctx) {
5250 conn->err_code = CO_ER_SSL_NO_MEM;
5251 return -1;
5252 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005253 ctx->wait_event.tasklet = tasklet_new();
5254 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005255 conn->err_code = CO_ER_SSL_NO_MEM;
5256 pool_free(ssl_sock_ctx_pool, ctx);
5257 return -1;
5258 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005259 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5260 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005261 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005262 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005263 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005264 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005265 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005266 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005267 ctx->xprt_st = 0;
5268 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005269
5270 /* Only work with sockets for now, this should be adapted when we'll
5271 * add QUIC support.
5272 */
5273 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005274 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005275 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5276 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005277 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005278
Willy Tarreau20879a02012-12-03 16:32:10 +01005279 if (global.maxsslconn && sslconns >= global.maxsslconn) {
5280 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005281 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005282 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005283
Emeric Brun46591952012-05-18 15:47:34 +02005284 /* If it is in client mode initiate SSL session
5285 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005286 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005287 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5288 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005289 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005290
Olivier Houchard66ab4982019-02-26 18:37:15 +01005291 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005292 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005293 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5294 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5295 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 +01005296 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005297 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005298 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005299 } else if (sess) {
5300 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005301 }
5302 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005303 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005304
Emeric Brun46591952012-05-18 15:47:34 +02005305 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005306 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005307
Willy Tarreau4781b152021-04-06 13:53:36 +02005308 _HA_ATOMIC_INC(&sslconns);
5309 _HA_ATOMIC_INC(&totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005310 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005311 return 0;
5312 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005313 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005314 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005315
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005316 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5317 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005318 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005319
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005320#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005321 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005322 b_alloc(&ctx->early_buf);
5323 SSL_set_max_early_data(ctx->ssl,
5324 /* Only allow early data if we managed to allocate
5325 * a buffer.
5326 */
5327 (!b_is_null(&ctx->early_buf)) ?
5328 global.tune.bufsize - global.tune.maxrewrite : 0);
5329 }
5330#endif
5331
Olivier Houchard66ab4982019-02-26 18:37:15 +01005332 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005333
Emeric Brun46591952012-05-18 15:47:34 +02005334 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005335 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005336#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005337 if (bc->ssl_conf.early_data)
5338 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005339#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005340
Willy Tarreau4781b152021-04-06 13:53:36 +02005341 _HA_ATOMIC_INC(&sslconns);
5342 _HA_ATOMIC_INC(&totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005343 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005344 return 0;
5345 }
5346 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005347 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005348err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005349 if (ctx && ctx->wait_event.tasklet)
5350 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005351 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005352 return -1;
5353}
5354
5355
5356/* This is the callback which is used when an SSL handshake is pending. It
5357 * updates the FD status if it wants some polling before being called again.
5358 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5359 * otherwise it returns non-zero and removes itself from the connection's
5360 * flags (the bit is provided in <flag> by the caller).
5361 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005362static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005363{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005364 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005365 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005366 struct ssl_counters *counters = NULL;
5367 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005368 struct listener *li;
5369 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005370 socklen_t lskerr;
5371 int skerr;
5372
Emeric Brun46591952012-05-18 15:47:34 +02005373
Willy Tarreau3c728722014-01-23 13:50:42 +01005374 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005375 return 0;
5376
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005377 /* get counters */
5378 switch (obj_type(conn->target)) {
5379 case OBJ_TYPE_LISTENER:
5380 li = objt_listener(conn->target);
5381 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5382 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5383 &ssl_stats_module);
5384 break;
5385
5386 case OBJ_TYPE_SERVER:
5387 srv = objt_server(conn->target);
5388 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5389 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5390 &ssl_stats_module);
5391 break;
5392
5393 default:
5394 break;
5395 }
5396
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005397 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005398 goto out_error;
5399
Willy Tarreau06300382021-02-02 15:42:25 +01005400 /* don't start calculating a handshake on a dead connection */
5401 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5402 goto out_error;
5403
5404 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5405 * status from the lower layers, so let's check the FD directly. Ideally
5406 * the xprt layers should provide some status indicating their knowledge
5407 * of shutdowns or error.
5408 */
5409 skerr = 0;
5410 lskerr = sizeof(skerr);
5411 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5412 skerr != 0)
5413 goto out_error;
5414
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005415#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005416 /*
5417 * Check if we have early data. If we do, we have to read them
5418 * before SSL_do_handshake() is called, And there's no way to
5419 * detect early data, except to try to read them
5420 */
5421 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005422 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005423
Olivier Houchard54907bb2019-12-19 15:02:39 +01005424 while (1) {
5425 ret = SSL_read_early_data(ctx->ssl,
5426 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5427 &read_data);
5428 if (ret == SSL_READ_EARLY_DATA_ERROR)
5429 goto check_error;
5430 if (read_data > 0) {
5431 conn->flags |= CO_FL_EARLY_DATA;
5432 b_add(&ctx->early_buf, read_data);
5433 }
5434 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5435 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5436 if (!b_data(&ctx->early_buf))
5437 b_free(&ctx->early_buf);
5438 break;
5439 }
5440 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005441 }
5442#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005443 /* If we use SSL_do_handshake to process a reneg initiated by
5444 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5445 * Usually SSL_write and SSL_read are used and process implicitly
5446 * the reneg handshake.
5447 * Here we use SSL_peek as a workaround for reneg.
5448 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005449 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005450 char c;
5451
Olivier Houchard66ab4982019-02-26 18:37:15 +01005452 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005453 if (ret <= 0) {
5454 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005455 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005456
Emeric Brun674b7432012-11-08 19:21:55 +01005457 if (ret == SSL_ERROR_WANT_WRITE) {
5458 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005459 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005460 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005461 return 0;
5462 }
5463 else if (ret == SSL_ERROR_WANT_READ) {
5464 /* handshake may have been completed but we have
5465 * no more data to read.
5466 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005467 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005468 ret = 1;
5469 goto reneg_ok;
5470 }
5471 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005472 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005473 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005474 return 0;
5475 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005476#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005477 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005478 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005479 return 0;
5480 }
5481#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005482 else if (ret == SSL_ERROR_SYSCALL) {
5483 /* if errno is null, then connection was successfully established */
5484 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5485 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005486 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005487#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5488 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005489 conn->err_code = CO_ER_SSL_HANDSHAKE;
5490#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005491 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005492#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005493 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005494 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005495 empty_handshake = state == TLS_ST_BEFORE;
5496#else
Lukas Tribus49799162019-07-08 14:29:15 +02005497 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5498 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005499#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005500 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005501 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005502 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005503 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5504 else
5505 conn->err_code = CO_ER_SSL_EMPTY;
5506 }
5507 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005508 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005509 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5510 else
5511 conn->err_code = CO_ER_SSL_ABORT;
5512 }
5513 }
5514 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005515 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005516 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005517 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005518 conn->err_code = CO_ER_SSL_HANDSHAKE;
5519 }
Lukas Tribus49799162019-07-08 14:29:15 +02005520#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005521 }
Emeric Brun674b7432012-11-08 19:21:55 +01005522 goto out_error;
5523 }
5524 else {
5525 /* Fail on all other handshake errors */
5526 /* Note: OpenSSL may leave unread bytes in the socket's
5527 * buffer, causing an RST to be emitted upon close() on
5528 * TCP sockets. We first try to drain possibly pending
5529 * data to avoid this as much as possible.
5530 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005531 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005532 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005533 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005534 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005535 goto out_error;
5536 }
5537 }
5538 /* read some data: consider handshake completed */
5539 goto reneg_ok;
5540 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005541 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005542check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005543 if (ret != 1) {
5544 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005545 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005546
5547 if (ret == SSL_ERROR_WANT_WRITE) {
5548 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005549 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005550 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005551 return 0;
5552 }
5553 else if (ret == SSL_ERROR_WANT_READ) {
5554 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005555 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005556 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5557 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005558 return 0;
5559 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005560#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005561 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005562 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005563 return 0;
5564 }
5565#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005566 else if (ret == SSL_ERROR_SYSCALL) {
5567 /* if errno is null, then connection was successfully established */
5568 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5569 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005570 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005571#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5572 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005573 conn->err_code = CO_ER_SSL_HANDSHAKE;
5574#else
5575 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005576#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005577 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005578 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005579 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005580#else
Lukas Tribus49799162019-07-08 14:29:15 +02005581 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5582 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005583#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005584 if (empty_handshake) {
5585 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005586 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005587 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5588 else
5589 conn->err_code = CO_ER_SSL_EMPTY;
5590 }
5591 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005592 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005593 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5594 else
5595 conn->err_code = CO_ER_SSL_ABORT;
5596 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005597 }
5598 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005599 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005600 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5601 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005602 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005603 }
Lukas Tribus49799162019-07-08 14:29:15 +02005604#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005605 }
Willy Tarreau89230192012-09-28 20:22:13 +02005606 goto out_error;
5607 }
Emeric Brun46591952012-05-18 15:47:34 +02005608 else {
5609 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005610 /* Note: OpenSSL may leave unread bytes in the socket's
5611 * buffer, causing an RST to be emitted upon close() on
5612 * TCP sockets. We first try to drain possibly pending
5613 * data to avoid this as much as possible.
5614 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005615 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005616 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005617 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005618 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005619 goto out_error;
5620 }
5621 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005622#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005623 else {
5624 /*
5625 * If the server refused the early data, we have to send a
5626 * 425 to the client, as we no longer have the data to sent
5627 * them again.
5628 */
5629 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005630 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005631 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5632 goto out_error;
5633 }
5634 }
5635 }
5636#endif
5637
Emeric Brun46591952012-05-18 15:47:34 +02005638
Emeric Brun674b7432012-11-08 19:21:55 +01005639reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005640
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005641#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005642 /* ASYNC engine API doesn't support moving read/write
5643 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005644 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005645 */
5646 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005647 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005648#endif
Emeric Brun46591952012-05-18 15:47:34 +02005649 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005650 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005651 if (objt_server(conn->target)) {
5652 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5653 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5654 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005655 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005656 else {
5657 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5658 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5659 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5660 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005661
Willy Tarreau42995282020-11-06 13:19:18 +01005662 if (counters) {
5663 ++counters->sess;
5664 ++counters_px->sess;
5665 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005666 }
Willy Tarreau42995282020-11-06 13:19:18 +01005667 else if (counters) {
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005668 ++counters->reused_sess;
5669 ++counters_px->reused_sess;
Emeric Brun46591952012-05-18 15:47:34 +02005670 }
5671
5672 /* The connection is now established at both layers, it's time to leave */
5673 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5674 return 1;
5675
5676 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005677 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005678 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005679 ERR_clear_error();
5680
Emeric Brun9fa89732012-10-04 17:09:56 +02005681 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01005682 if (objt_server(conn->target)) {
5683 struct server *s = __objt_server(conn->target);
5684 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
5685 * one cache per thread, it only prevents to flush it from the CLI in
5686 * another thread */
5687
5688 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005689 if (s->ssl_ctx.reused_sess[tid].ptr)
5690 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005691 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02005692 }
5693
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005694 if (counters) {
5695 ++counters->failed_handshake;
5696 ++counters_px->failed_handshake;
5697 }
5698
Emeric Brun46591952012-05-18 15:47:34 +02005699 /* Fail on all other handshake errors */
5700 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005701 if (!conn->err_code)
5702 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005703 return 0;
5704}
5705
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005706/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5707 * event subscriber <es> is not allowed to change from a previous call as long
5708 * as at least one event is still subscribed. The <event_type> must only be a
5709 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5710 * unless the transport layer was already released.
5711 */
5712static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005713{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005714 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005715
Olivier Houchard0ff28652019-06-24 18:57:39 +02005716 if (!ctx)
5717 return -1;
5718
Willy Tarreau113d52b2020-01-10 09:20:26 +01005719 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005720 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005721
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005722 ctx->subs = es;
5723 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005724
5725 /* we may have to subscribe to lower layers for new events */
5726 event_type &= ~ctx->wait_event.events;
5727 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5728 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005729 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005730}
5731
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005732/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5733 * The <es> pointer is not allowed to differ from the one passed to the
5734 * subscribe() call. It always returns zero.
5735 */
5736static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005737{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005738 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005739
Willy Tarreau113d52b2020-01-10 09:20:26 +01005740 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005741 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005742
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005743 es->events &= ~event_type;
5744 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005745 ctx->subs = NULL;
5746
5747 /* If we subscribed, and we're not doing the handshake,
5748 * then we subscribed because the upper layer asked for it,
5749 * as the upper layer is no longer interested, we can
5750 * unsubscribe too.
5751 */
5752 event_type &= ctx->wait_event.events;
5753 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5754 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005755
5756 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005757}
5758
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005759/* The connection has been taken over, so destroy the old tasklet and create
5760 * a new one. The original thread ID must be passed into orig_tid
5761 * It should be called with the takeover lock for the old thread held.
5762 * Returns 0 on success, and -1 on failure
5763 */
5764static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
5765{
5766 struct ssl_sock_ctx *ctx = xprt_ctx;
5767 struct tasklet *tl = tasklet_new();
5768
5769 if (!tl)
5770 return -1;
5771
5772 ctx->wait_event.tasklet->context = NULL;
5773 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
5774 ctx->wait_event.tasklet = tl;
5775 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5776 ctx->wait_event.tasklet->context = ctx;
5777 return 0;
5778}
5779
Willy Tarreau41491682021-03-02 17:29:56 +01005780/* notify the next xprt that the connection is about to become idle and that it
5781 * may be stolen at any time after the function returns and that any tasklet in
5782 * the chain must be careful before dereferencing its context.
5783 */
5784static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
5785{
5786 struct ssl_sock_ctx *ctx = xprt_ctx;
5787
5788 if (!ctx || !ctx->wait_event.tasklet)
5789 return;
5790
5791 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5792 if (ctx->xprt)
5793 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
5794}
5795
5796/* notify the next xprt that the connection is not idle anymore and that it may
5797 * not be stolen before the next xprt_set_idle().
5798 */
5799static void ssl_set_used(struct connection *conn, void *xprt_ctx)
5800{
5801 struct ssl_sock_ctx *ctx = xprt_ctx;
5802
5803 if (!ctx || !ctx->wait_event.tasklet)
5804 return;
5805
5806 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5807 if (ctx->xprt)
5808 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
5809}
5810
Olivier Houchard2e055482019-05-27 19:50:12 +02005811/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5812 * Returns 0 on success, and non-zero on failure.
5813 */
5814static 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)
5815{
5816 struct ssl_sock_ctx *ctx = xprt_ctx;
5817
5818 if (oldxprt_ops != NULL)
5819 *oldxprt_ops = ctx->xprt;
5820 if (oldxprt_ctx != NULL)
5821 *oldxprt_ctx = ctx->xprt_ctx;
5822 ctx->xprt = toadd_ops;
5823 ctx->xprt_ctx = toadd_ctx;
5824 return 0;
5825}
5826
Olivier Houchard5149b592019-05-23 17:47:36 +02005827/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5828 * return 0, otherwise just call the remove_xprt method from the underlying
5829 * XPRT.
5830 */
5831static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5832{
5833 struct ssl_sock_ctx *ctx = xprt_ctx;
5834
5835 if (ctx->xprt_ctx == toremove_ctx) {
5836 ctx->xprt_ctx = newctx;
5837 ctx->xprt = newops;
5838 return 0;
5839 }
5840 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5841}
5842
Willy Tarreau144f84a2021-03-02 16:09:26 +01005843struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02005844{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005845 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005846 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005847 struct connection *conn;
5848 int conn_in_list;
5849 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005850
Willy Tarreau41491682021-03-02 17:29:56 +01005851 if (state & TASK_F_USR1) {
5852 /* the tasklet was idling on an idle connection, it might have
5853 * been stolen, let's be careful!
5854 */
5855 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5856 if (tl->context == NULL) {
5857 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5858 tasklet_free(tl);
5859 return NULL;
5860 }
5861 conn = ctx->conn;
5862 conn_in_list = conn->flags & CO_FL_LIST_MASK;
5863 if (conn_in_list)
5864 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005865 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01005866 } else {
5867 conn = ctx->conn;
5868 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005869 }
Willy Tarreau41491682021-03-02 17:29:56 +01005870
Olivier Houchardea8dd942019-05-20 14:02:16 +02005871 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01005872 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005873 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005874 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5875 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01005876 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005877 }
5878 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005879 /* If we had an error, or the handshake is done and I/O is available,
5880 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005881 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005882 * we can't be sure conn_fd_handler() will be called again.
5883 */
5884 if ((ctx->conn->flags & CO_FL_ERROR) ||
5885 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005886 int woke = 0;
5887
5888 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005889 if (ctx->subs) {
5890 tasklet_wakeup(ctx->subs->tasklet);
5891 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005892 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005893 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005894 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005895
Olivier Houchardea8dd942019-05-20 14:02:16 +02005896 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005897 * upper layers know. If we have no mux, create it,
5898 * and once we have a mux, call its wake method if we didn't
5899 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005900 */
5901 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005902 if (!ctx->conn->mux)
5903 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005904 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005905 ret = ctx->conn->mux->wake(ctx->conn);
5906 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005907 }
5908 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05005909#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01005910 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005911 else if (b_data(&ctx->early_buf) && ctx->subs &&
5912 ctx->subs->events & SUB_RETRY_RECV) {
5913 tasklet_wakeup(ctx->subs->tasklet);
5914 ctx->subs->events &= ~SUB_RETRY_RECV;
5915 if (!ctx->subs->events)
5916 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005917 }
5918#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005919leave:
5920 if (!ret && conn_in_list) {
5921 struct server *srv = objt_server(conn->target);
5922
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005923 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005924 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau430bf4a2021-03-04 09:45:32 +01005925 ebmb_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005926 else
Willy Tarreau430bf4a2021-03-04 09:45:32 +01005927 ebmb_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005928 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005929 }
Willy Tarreau74163142021-03-13 11:30:19 +01005930 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005931}
5932
Emeric Brun46591952012-05-18 15:47:34 +02005933/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01005934 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02005935 * buffer wraps, in which case a second call may be performed. The connection's
5936 * flags are updated with whatever special event is detected (error, read0,
5937 * empty). The caller is responsible for taking care of those events and
5938 * avoiding the call if inappropriate. The function does not call the
5939 * connection's polling update function, so the caller is responsible for this.
5940 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005941static 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 +02005942{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005943 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02005944 ssize_t ret;
5945 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02005946
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005947 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005948 goto out_error;
5949
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05005950#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01005951 if (b_data(&ctx->early_buf)) {
5952 try = b_contig_space(buf);
5953 if (try > b_data(&ctx->early_buf))
5954 try = b_data(&ctx->early_buf);
5955 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
5956 b_add(buf, try);
5957 b_del(&ctx->early_buf, try);
5958 if (b_data(&ctx->early_buf) == 0)
5959 b_free(&ctx->early_buf);
5960 return try;
5961 }
5962#endif
5963
Willy Tarreau911db9b2020-01-23 16:27:54 +01005964 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005965 /* a handshake was requested */
5966 return 0;
5967
Emeric Brun46591952012-05-18 15:47:34 +02005968 /* read the largest possible block. For this, we perform only one call
5969 * to recv() unless the buffer wraps and we exactly fill the first hunk,
5970 * in which case we accept to do it once again. A new attempt is made on
5971 * EINTR too.
5972 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01005973 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005974
Willy Tarreau591d4452018-06-15 17:21:00 +02005975 try = b_contig_space(buf);
5976 if (!try)
5977 break;
5978
Willy Tarreauabf08d92014-01-14 11:31:27 +01005979 if (try > count)
5980 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02005981
Olivier Houchard66ab4982019-02-26 18:37:15 +01005982 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005983
Emeric Brune1f38db2012-09-03 20:36:47 +02005984 if (conn->flags & CO_FL_ERROR) {
5985 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005986 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005987 }
Emeric Brun46591952012-05-18 15:47:34 +02005988 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02005989 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005990 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005991 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005992 }
Emeric Brun46591952012-05-18 15:47:34 +02005993 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005994 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005995 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005996 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02005997 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005998 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005999#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006000 /* Async mode can be re-enabled, because we're leaving data state.*/
6001 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006002 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006003#endif
Emeric Brun46591952012-05-18 15:47:34 +02006004 break;
6005 }
6006 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006007 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006008 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6009 SUB_RETRY_RECV,
6010 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006011 /* handshake is running, and it may need to re-enable read */
6012 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006013#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006014 /* Async mode can be re-enabled, because we're leaving data state.*/
6015 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006016 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006017#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006018 break;
6019 }
Emeric Brun46591952012-05-18 15:47:34 +02006020 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006021 } else if (ret == SSL_ERROR_ZERO_RETURN)
6022 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006023 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6024 * stack before shutting down the connection for
6025 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006026 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
6027 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006028 /* otherwise it's a real error */
6029 goto out_error;
6030 }
6031 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006032 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006033 return done;
6034
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006035 clear_ssl_error:
6036 /* Clear openssl global errors stack */
6037 ssl_sock_dump_errors(conn);
6038 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006039 read0:
6040 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006041 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006042
Emeric Brun46591952012-05-18 15:47:34 +02006043 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006044 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006045 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006046 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006047 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006048 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006049}
6050
6051
Willy Tarreau787db9a2018-06-14 18:31:46 +02006052/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6053 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6054 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006055 * Only one call to send() is performed, unless the buffer wraps, in which case
6056 * a second call may be performed. The connection's flags are updated with
6057 * whatever special event is detected (error, empty). The caller is responsible
6058 * for taking care of those events and avoiding the call if inappropriate. The
6059 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006060 * is responsible for this. The buffer's output is not adjusted, it's up to the
6061 * caller to take care of this. It's up to the caller to update the buffer's
6062 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006063 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006064static 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 +02006065{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006066 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006067 ssize_t ret;
6068 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006069
6070 done = 0;
6071
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006072 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006073 goto out_error;
6074
Willy Tarreau911db9b2020-01-23 16:27:54 +01006075 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006076 /* a handshake was requested */
6077 return 0;
6078
6079 /* send the largest possible block. For this we perform only one call
6080 * to send() unless the buffer wraps and we exactly fill the first hunk,
6081 * in which case we accept to do it once again.
6082 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006083 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006084#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006085 size_t written_data;
6086#endif
6087
Willy Tarreau787db9a2018-06-14 18:31:46 +02006088 try = b_contig_data(buf, done);
6089 if (try > count)
6090 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006091
Willy Tarreau7bed9452014-02-02 02:00:24 +01006092 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006093 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006094 global_ssl.max_record && try > global_ssl.max_record) {
6095 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006096 }
6097 else {
6098 /* we need to keep the information about the fact that
6099 * we're not limiting the upcoming send(), because if it
6100 * fails, we'll have to retry with at least as many data.
6101 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006102 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006103 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006104
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006105#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006106 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006107 unsigned int max_early;
6108
Olivier Houchard522eea72017-11-03 16:27:47 +01006109 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006110 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006111 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006112 if (SSL_get0_session(ctx->ssl))
6113 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006114 else
6115 max_early = 0;
6116 }
6117
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006118 if (try + ctx->sent_early_data > max_early) {
6119 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006120 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006121 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006122 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006123 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006124 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006125 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006126 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006127 if (ret == 1) {
6128 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006129 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006130 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006131 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006132 /* Initiate the handshake, now */
6133 tasklet_wakeup(ctx->wait_event.tasklet);
6134 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006135
Olivier Houchardc2aae742017-09-22 18:26:28 +02006136 }
6137
6138 } else
6139#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006140 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006141
Emeric Brune1f38db2012-09-03 20:36:47 +02006142 if (conn->flags & CO_FL_ERROR) {
6143 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006144 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006145 }
Emeric Brun46591952012-05-18 15:47:34 +02006146 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006147 /* A send succeeded, so we can consider ourself connected */
6148 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006149 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006150 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006151 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006152 }
6153 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006154 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006155
Emeric Brun46591952012-05-18 15:47:34 +02006156 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006157 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006158 /* handshake is running, and it may need to re-enable write */
6159 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006160 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006161#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006162 /* Async mode can be re-enabled, because we're leaving data state.*/
6163 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006164 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006165#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006166 break;
6167 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006168
Emeric Brun46591952012-05-18 15:47:34 +02006169 break;
6170 }
6171 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006172 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006173 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006174 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6175 SUB_RETRY_RECV,
6176 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006177#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006178 /* Async mode can be re-enabled, because we're leaving data state.*/
6179 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006180 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006181#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006182 break;
6183 }
Emeric Brun46591952012-05-18 15:47:34 +02006184 goto out_error;
6185 }
6186 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006187 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006188 return done;
6189
6190 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006191 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006192 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006193 ERR_clear_error();
6194
Emeric Brun46591952012-05-18 15:47:34 +02006195 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006196 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006197}
6198
Willy Tarreau832e2422021-05-13 10:11:03 +02006199void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006200
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006201 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006202
Olivier Houchardea8dd942019-05-20 14:02:16 +02006203
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006204 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006205 if (ctx->wait_event.events != 0)
6206 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6207 ctx->wait_event.events,
6208 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006209 if (ctx->subs) {
6210 ctx->subs->events = 0;
6211 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006212 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006213
Olivier Houchard692c1d02019-05-23 18:41:47 +02006214 if (ctx->xprt->close)
6215 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006216#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006217 if (global_ssl.async) {
6218 OSSL_ASYNC_FD all_fd[32], afd;
6219 size_t num_all_fds = 0;
6220 int i;
6221
Olivier Houchard66ab4982019-02-26 18:37:15 +01006222 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006223 if (num_all_fds > 32) {
6224 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6225 return;
6226 }
6227
Olivier Houchard66ab4982019-02-26 18:37:15 +01006228 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006229
6230 /* If an async job is pending, we must try to
6231 to catch the end using polling before calling
6232 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006233 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006234 for (i=0 ; i < num_all_fds ; i++) {
6235 /* switch on an handler designed to
6236 * handle the SSL_free
6237 */
6238 afd = all_fd[i];
6239 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006240 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006241 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006242 /* To ensure that the fd cache won't be used
6243 * and we'll catch a real RD event.
6244 */
6245 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006246 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006247 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006248 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006249 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006250 return;
6251 }
Emeric Brun3854e012017-05-17 20:42:48 +02006252 /* Else we can remove the fds from the fdtab
6253 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006254 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006255 * because the fd is owned by the engine.
6256 * the engine is responsible to close
6257 */
6258 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +02006259 fd_stop_both(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006260 }
6261#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006262 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006263 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006264 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006265 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006266 _HA_ATOMIC_DEC(&sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006267 }
Emeric Brun46591952012-05-18 15:47:34 +02006268}
6269
6270/* This function tries to perform a clean shutdown on an SSL connection, and in
6271 * any case, flags the connection as reusable if no handshake was in progress.
6272 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006273static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006274{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006275 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006276
Willy Tarreau911db9b2020-01-23 16:27:54 +01006277 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006278 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006279 if (!clean)
6280 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006281 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006282 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006283 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006284 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006285 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006286 ERR_clear_error();
6287 }
Emeric Brun46591952012-05-18 15:47:34 +02006288}
6289
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006290
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006291/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006292int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6293{
6294 struct ssl_sock_ctx *ctx;
6295 X509 *crt;
6296
6297 if (!ssl_sock_is_ssl(conn))
6298 return 0;
6299
6300 ctx = conn->xprt_ctx;
6301
6302 crt = SSL_get_certificate(ctx->ssl);
6303 if (!crt)
6304 return 0;
6305
6306 return cert_get_pkey_algo(crt, out);
6307}
6308
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006309/* used for ppv2 cert signature (can be used for logging) */
6310const char *ssl_sock_get_cert_sig(struct connection *conn)
6311{
Christopher Faulet82004142019-09-10 10:12:03 +02006312 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006313
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006314 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6315 X509 *crt;
6316
6317 if (!ssl_sock_is_ssl(conn))
6318 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006319 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006320 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006321 if (!crt)
6322 return NULL;
6323 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6324 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6325}
6326
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006327/* used for ppv2 authority */
6328const char *ssl_sock_get_sni(struct connection *conn)
6329{
6330#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006331 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006332
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006333 if (!ssl_sock_is_ssl(conn))
6334 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006335 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006336 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006337#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006338 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006339#endif
6340}
6341
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006342/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006343const char *ssl_sock_get_cipher_name(struct connection *conn)
6344{
Christopher Faulet82004142019-09-10 10:12:03 +02006345 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006346
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006347 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006348 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006349 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006350 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006351}
6352
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006353/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006354const char *ssl_sock_get_proto_version(struct connection *conn)
6355{
Christopher Faulet82004142019-09-10 10:12:03 +02006356 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006357
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006358 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006359 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006360 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006361 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006362}
6363
Olivier Houchardab28a322018-12-21 19:45:40 +01006364void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6365{
6366#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02006367 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006368
Olivier Houcharde488ea82019-06-28 14:10:33 +02006369 if (!ssl_sock_is_ssl(conn))
6370 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006371 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006372 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006373#endif
6374}
6375
Willy Tarreau119a4082016-12-22 21:58:38 +01006376/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6377 * to disable SNI.
6378 */
Willy Tarreau63076412015-07-10 11:33:32 +02006379void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6380{
6381#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006382 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006383
Willy Tarreau119a4082016-12-22 21:58:38 +01006384 char *prev_name;
6385
Willy Tarreau63076412015-07-10 11:33:32 +02006386 if (!ssl_sock_is_ssl(conn))
6387 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006388 ctx = conn->xprt_ctx;
Willy Tarreau63076412015-07-10 11:33:32 +02006389
Willy Tarreau119a4082016-12-22 21:58:38 +01006390 /* if the SNI changes, we must destroy the reusable context so that a
6391 * new connection will present a new SNI. As an optimization we could
6392 * later imagine having a small cache of ssl_ctx to hold a few SNI per
6393 * server.
6394 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006395 prev_name = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau119a4082016-12-22 21:58:38 +01006396 if ((!prev_name && hostname) ||
6397 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006398 SSL_set_session(ctx->ssl, NULL);
Willy Tarreau119a4082016-12-22 21:58:38 +01006399
Olivier Houchard66ab4982019-02-26 18:37:15 +01006400 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006401#endif
6402}
6403
Emeric Brun0abf8362014-06-24 18:26:41 +02006404/* Extract peer certificate's common name into the chunk dest
6405 * Returns
6406 * the len of the extracted common name
6407 * or 0 if no CN found in DN
6408 * or -1 on error case (i.e. no peer certificate)
6409 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006410int ssl_sock_get_remote_common_name(struct connection *conn,
6411 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006412{
Christopher Faulet82004142019-09-10 10:12:03 +02006413 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04006414 X509 *crt = NULL;
6415 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006416 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006417 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006418 .area = (char *)&find_cn,
6419 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006420 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006421 int result = -1;
David Safb76832014-05-08 23:42:08 -04006422
6423 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02006424 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02006425 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006426
6427 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006428 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006429 if (!crt)
6430 goto out;
6431
6432 name = X509_get_subject_name(crt);
6433 if (!name)
6434 goto out;
David Safb76832014-05-08 23:42:08 -04006435
Emeric Brun0abf8362014-06-24 18:26:41 +02006436 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6437out:
David Safb76832014-05-08 23:42:08 -04006438 if (crt)
6439 X509_free(crt);
6440
6441 return result;
6442}
6443
Dave McCowan328fb582014-07-30 10:39:13 -04006444/* returns 1 if client passed a certificate for this session, 0 if not */
6445int ssl_sock_get_cert_used_sess(struct connection *conn)
6446{
Christopher Faulet82004142019-09-10 10:12:03 +02006447 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006448 X509 *crt = NULL;
6449
6450 if (!ssl_sock_is_ssl(conn))
6451 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006452 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006453
6454 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006455 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006456 if (!crt)
6457 return 0;
6458
6459 X509_free(crt);
6460 return 1;
6461}
6462
6463/* returns 1 if client passed a certificate for this connection, 0 if not */
6464int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006465{
Christopher Faulet82004142019-09-10 10:12:03 +02006466 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006467
David Safb76832014-05-08 23:42:08 -04006468 if (!ssl_sock_is_ssl(conn))
6469 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006470 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006471 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006472}
6473
6474/* returns result from SSL verify */
6475unsigned int ssl_sock_get_verify_result(struct connection *conn)
6476{
Christopher Faulet82004142019-09-10 10:12:03 +02006477 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006478
David Safb76832014-05-08 23:42:08 -04006479 if (!ssl_sock_is_ssl(conn))
6480 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006481 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006482 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006483}
6484
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006485/* Returns the application layer protocol name in <str> and <len> when known.
6486 * Zero is returned if the protocol name was not found, otherwise non-zero is
6487 * returned. The string is allocated in the SSL context and doesn't have to be
6488 * freed by the caller. NPN is also checked if available since older versions
6489 * of openssl (1.0.1) which are more common in field only support this one.
6490 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006491static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006492{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006493#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6494 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006495 struct ssl_sock_ctx *ctx = xprt_ctx;
6496 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006497 return 0;
6498
6499 *str = NULL;
6500
6501#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006502 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006503 if (*str)
6504 return 1;
6505#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006506#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006507 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006508 if (*str)
6509 return 1;
6510#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006511#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006512 return 0;
6513}
6514
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006515/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006516int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006517{
6518 X509 *ca;
6519 X509_NAME *name = NULL;
6520 ASN1_OCTET_STRING *skid = NULL;
6521 STACK_OF(X509) *chain = NULL;
6522 struct issuer_chain *issuer;
6523 struct eb64_node *node;
6524 char *path;
6525 u64 key;
6526 int ret = 0;
6527
6528 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6529 if (chain == NULL) {
6530 chain = sk_X509_new_null();
6531 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6532 name = X509_get_subject_name(ca);
6533 }
6534 if (!sk_X509_push(chain, ca)) {
6535 X509_free(ca);
6536 goto end;
6537 }
6538 }
6539 if (!chain) {
6540 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6541 goto end;
6542 }
6543 if (!skid) {
6544 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6545 goto end;
6546 }
6547 if (!name) {
6548 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6549 goto end;
6550 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006551 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006552 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006553 issuer = container_of(node, typeof(*issuer), node);
6554 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6555 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6556 goto end;
6557 }
6558 }
6559 issuer = calloc(1, sizeof *issuer);
6560 path = strdup(fp);
6561 if (!issuer || !path) {
6562 free(issuer);
6563 free(path);
6564 goto end;
6565 }
6566 issuer->node.key = key;
6567 issuer->path = path;
6568 issuer->chain = chain;
6569 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006570 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006571 ret = 1;
6572 end:
6573 if (skid)
6574 ASN1_OCTET_STRING_free(skid);
6575 if (chain)
6576 sk_X509_pop_free(chain, X509_free);
6577 return ret;
6578}
6579
William Lallemandda8584c2020-05-14 10:14:37 +02006580 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006581{
6582 AUTHORITY_KEYID *akid;
6583 struct issuer_chain *issuer = NULL;
6584
6585 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006586 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006587 struct eb64_node *node;
6588 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006589 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006590 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6591 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6592 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6593 issuer = ti;
6594 break;
6595 }
6596 }
6597 AUTHORITY_KEYID_free(akid);
6598 }
6599 return issuer;
6600}
6601
William Lallemanddad31052020-05-14 17:47:32 +02006602void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006603{
6604 struct eb64_node *node, *back;
6605 struct issuer_chain *issuer;
6606
William Lallemande0f3fd52020-02-25 14:53:06 +01006607 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006608 while (node) {
6609 issuer = container_of(node, typeof(*issuer), node);
6610 back = eb64_next(node);
6611 eb64_delete(node);
6612 free(issuer->path);
6613 sk_X509_pop_free(issuer->chain, X509_free);
6614 free(issuer);
6615 node = back;
6616 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006617}
6618
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006619#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006620static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006621 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006622
Emeric Brun3854e012017-05-17 20:42:48 +02006623 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006624 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006625 err_code = ERR_ABORT;
6626 }
6627 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006628}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006629#endif
6630
Willy Tarreaude5675a2021-01-20 14:41:29 +01006631/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006632 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006633 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006634static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006635{
6636 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006637 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006638
6639 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006640 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006641
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006642 if (sctx->conn != conn) {
6643 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6644 ret = 1;
6645 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01006646 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6647
6648 if (sctx->xprt) {
6649 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6650 if (sctx->xprt_ctx)
6651 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6652 }
6653
6654 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006655
6656 /* as soon as a shutdown is reported the lower layer unregisters its
6657 * subscriber, so the situations below are transient and rare enough to
6658 * be reported as suspicious. In any case they shouldn't last.
6659 */
6660 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
6661 ret = 1;
6662 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
6663 ret = 1;
6664
Willy Tarreaude5675a2021-01-20 14:41:29 +01006665 chunk_appendf(&trash, " .subs=%p", sctx->subs);
6666 if (sctx->subs) {
6667 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006668 if (sctx->subs->tasklet->calls >= 1000000)
6669 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006670 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
6671 sctx->subs->tasklet->calls,
6672 sctx->subs->tasklet->context);
6673 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
6674 chunk_appendf(&trash, ")");
6675 }
6676 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
6677 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006678 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006679}
6680
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006681#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02006682/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006683 * each reference. The variable <ref> must point to the current node's list
6684 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02006685 */
William Lallemand32af2032016-10-29 18:09:35 +02006686static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006687struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02006688{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006689 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006690 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02006691
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006692 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006693 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006694 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02006695
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006696 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02006697}
6698
6699static inline
6700struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6701{
6702 int id;
6703 char *error;
6704
6705 /* If the reference starts by a '#', this is numeric id. */
6706 if (reference[0] == '#') {
6707 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6708 id = strtol(reference + 1, &error, 10);
6709 if (*error != '\0')
6710 return NULL;
6711
6712 /* Perform the unique id lookup. */
6713 return tlskeys_ref_lookupid(id);
6714 }
6715
6716 /* Perform the string lookup. */
6717 return tlskeys_ref_lookup(reference);
6718}
6719#endif
6720
6721
6722#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6723
6724static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6725
6726static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6727 return cli_io_handler_tlskeys_files(appctx);
6728}
6729
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006730/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6731 * (next index to be dumped), and cli.p0 (next key reference).
6732 */
William Lallemand32af2032016-10-29 18:09:35 +02006733static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6734
6735 struct stream_interface *si = appctx->owner;
6736
6737 switch (appctx->st2) {
6738 case STAT_ST_INIT:
6739 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006740 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006741 * later and restart at the state "STAT_ST_INIT".
6742 */
6743 chunk_reset(&trash);
6744
6745 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6746 chunk_appendf(&trash, "# id secret\n");
6747 else
6748 chunk_appendf(&trash, "# id (file)\n");
6749
Willy Tarreau06d80a92017-10-19 14:32:15 +02006750 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006751 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006752 return 0;
6753 }
6754
William Lallemand32af2032016-10-29 18:09:35 +02006755 /* Now, we start the browsing of the references lists.
6756 * Note that the following call to LIST_ELEM return bad pointer. The only
6757 * available field of this pointer is <list>. It is used with the function
6758 * tlskeys_list_get_next() for retruning the first available entry
6759 */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006760 if (appctx->ctx.cli.p0 == NULL)
6761 appctx->ctx.cli.p0 = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006762
6763 appctx->st2 = STAT_ST_LIST;
6764 /* fall through */
6765
6766 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006767 while (appctx->ctx.cli.p0) {
6768 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006769
6770 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006771 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006772 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006773
6774 if (appctx->ctx.cli.i1 == 0)
6775 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6776
William Lallemand32af2032016-10-29 18:09:35 +02006777 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006778 int head;
6779
6780 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6781 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006782 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006783 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006784
6785 chunk_reset(t2);
6786 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006787 if (ref->key_size_bits == 128) {
6788 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6789 sizeof(struct tls_sess_key_128),
6790 t2->area, t2->size);
6791 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6792 t2->area);
6793 }
6794 else if (ref->key_size_bits == 256) {
6795 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6796 sizeof(struct tls_sess_key_256),
6797 t2->area, t2->size);
6798 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6799 t2->area);
6800 }
6801 else {
6802 /* This case should never happen */
6803 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6804 }
William Lallemand32af2032016-10-29 18:09:35 +02006805
Willy Tarreau06d80a92017-10-19 14:32:15 +02006806 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006807 /* let's try again later from this stream. We add ourselves into
6808 * this stream's users so that it can remove us upon termination.
6809 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006810 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006811 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006812 return 0;
6813 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006814 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006815 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006816 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006817 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006818 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006819 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006820 /* let's try again later from this stream. We add ourselves into
6821 * this stream's users so that it can remove us upon termination.
6822 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006823 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006824 return 0;
6825 }
6826
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006827 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006828 break;
6829
6830 /* get next list entry and check the end of the list */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006831 appctx->ctx.cli.p0 = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006832 }
6833
6834 appctx->st2 = STAT_ST_FIN;
6835 /* fall through */
6836
6837 default:
6838 appctx->st2 = STAT_ST_FIN;
6839 return 1;
6840 }
6841 return 0;
6842}
6843
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006844/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006845static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006846{
William Lallemand32af2032016-10-29 18:09:35 +02006847 /* no parameter, shows only file list */
6848 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006849 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006850 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006851 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006852 }
6853
6854 if (args[2][0] == '*') {
6855 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006856 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006857 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006858 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006859 if (!appctx->ctx.cli.p0)
6860 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006861 }
William Lallemand32af2032016-10-29 18:09:35 +02006862 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006863 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006864}
6865
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006866static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006867{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006868 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006869 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006870
William Lallemand32af2032016-10-29 18:09:35 +02006871 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006872 if (!*args[3] || !*args[4])
6873 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 +02006874
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006875 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006876 if (!ref)
6877 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006878
Willy Tarreau1c913e42018-08-22 05:26:57 +02006879 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006880 if (ret < 0)
6881 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006882
Willy Tarreau1c913e42018-08-22 05:26:57 +02006883 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006884 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6885 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006886
Willy Tarreau9d008692019-08-09 11:21:01 +02006887 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006888}
William Lallemandd4f946c2019-12-05 10:26:40 +01006889#endif
William Lallemand419e6342020-04-08 12:05:39 +02006890
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006891static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006892{
6893#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6894 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006895 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006896
6897 if (!payload)
6898 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006899
6900 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006901 if (!*payload)
6902 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006903
6904 /* remove \r and \n from the payload */
6905 for (i = 0, j = 0; payload[i]; i++) {
6906 if (payload[i] == '\r' || payload[i] == '\n')
6907 continue;
6908 payload[j++] = payload[i];
6909 }
6910 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006911
Willy Tarreau1c913e42018-08-22 05:26:57 +02006912 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006913 if (ret < 0)
6914 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006915
Willy Tarreau1c913e42018-08-22 05:26:57 +02006916 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02006917 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02006918 if (err)
6919 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
6920 else
6921 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006922 }
Willy Tarreau9d008692019-08-09 11:21:01 +02006923
6924 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006925#else
Willy Tarreau9d008692019-08-09 11:21:01 +02006926 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 +02006927#endif
6928
Elliot Otchet71f82972020-01-15 08:12:14 -05006929}
6930
William Lallemand32af2032016-10-29 18:09:35 +02006931/* register cli keywords */
6932static struct cli_kw_list cli_kws = {{ },{
6933#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Willy Tarreaub205bfd2021-05-07 11:38:37 +02006934 { { "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 },
6935 { { "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 +02006936#endif
Willy Tarreaub205bfd2021-05-07 11:38:37 +02006937 { { "set", "ssl", "ocsp-response", NULL }, "set ssl ocsp-response <resp|payload> : update a certificate's OCSP Response from a base64-encode DER", cli_parse_set_ocspresponse, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02006938 { { NULL }, NULL, NULL, NULL }
6939}};
6940
Willy Tarreau0108d902018-11-25 19:14:37 +01006941INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02006942
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02006943/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02006944struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02006945 .snd_buf = ssl_sock_from_buf,
6946 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01006947 .subscribe = ssl_subscribe,
6948 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02006949 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02006950 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02006951 .rcv_pipe = NULL,
6952 .snd_pipe = NULL,
6953 .shutr = NULL,
6954 .shutw = ssl_sock_shutw,
6955 .close = ssl_sock_close,
6956 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01006957 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01006958 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01006959 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01006960 .prepare_srv = ssl_sock_prepare_srv_ctx,
6961 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006962 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006963 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01006964 .set_idle = ssl_set_idle,
6965 .set_used = ssl_set_used,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01006966 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01006967 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02006968};
6969
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006970enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
6971 struct session *sess, struct stream *s, int flags)
6972{
6973 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006974 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006975
6976 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006977 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006978
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006979 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006980 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006981 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006982 s->req.flags |= CF_READ_NULL;
6983 return ACT_RET_YIELD;
6984 }
6985 }
6986 return (ACT_RET_CONT);
6987}
6988
6989static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
6990{
6991 rule->action_ptr = ssl_action_wait_for_hs;
6992
6993 return ACT_RET_PRS_OK;
6994}
6995
6996static struct action_kw_list http_req_actions = {ILH, {
6997 { "wait-for-handshake", ssl_parse_wait_for_hs },
6998 { /* END */ }
6999}};
7000
Willy Tarreau0108d902018-11-25 19:14:37 +01007001INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7002
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007003#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007004
7005static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7006{
7007 if (ptr) {
7008 chunk_destroy(ptr);
7009 free(ptr);
7010 }
7011}
7012
7013#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007014
7015#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7016static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7017{
7018 struct ocsp_cbk_arg *ocsp_arg;
7019
7020 if (ptr) {
7021 ocsp_arg = ptr;
7022
7023 if (ocsp_arg->is_single) {
7024 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
7025 ocsp_arg->s_ocsp = NULL;
7026 } else {
7027 int i;
7028
7029 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
7030 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
7031 ocsp_arg->m_ocsp[i] = NULL;
7032 }
7033 }
7034 free(ocsp_arg);
7035 }
7036}
7037#endif
7038
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007039static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7040{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007041 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007042}
William Lallemand7d42ef52020-07-06 11:41:30 +02007043
William Lallemand722180a2021-06-09 16:46:12 +02007044#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007045static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7046{
7047 struct ssl_keylog *keylog;
7048
7049 if (!ptr)
7050 return;
7051
7052 keylog = ptr;
7053
7054 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7055 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7056 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7057 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7058 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7059 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7060 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7061 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7062
7063 pool_free(pool_head_ssl_keylog, ptr);
7064}
7065#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007066
Emeric Brun46591952012-05-18 15:47:34 +02007067__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02007068static void __ssl_sock_init(void)
7069{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007070#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007071 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007072 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007073#endif
Emeric Brun46591952012-05-18 15:47:34 +02007074
Willy Tarreauef934602016-12-22 23:12:01 +01007075 if (global_ssl.listen_default_ciphers)
7076 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7077 if (global_ssl.connect_default_ciphers)
7078 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007079#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007080 if (global_ssl.listen_default_ciphersuites)
7081 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7082 if (global_ssl.connect_default_ciphersuites)
7083 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7084#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007085
Willy Tarreau13e14102016-12-22 20:25:26 +01007086 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007087#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007088 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007089#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007090#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007091 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007092 n = sk_SSL_COMP_num(cm);
7093 while (n--) {
7094 (void) sk_SSL_COMP_pop(cm);
7095 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007096#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007097
Willy Tarreau5db847a2019-05-09 14:13:35 +02007098#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007099 ssl_locking_init();
7100#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007101#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007102 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7103#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007104
7105#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7106 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7107#endif
7108
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007109 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007110 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 +02007111#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007112 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7113#endif
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007114#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007115 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007116 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007117#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007118#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7119 hap_register_post_check(tlskeys_finalize_config);
7120#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007121
7122 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7123 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7124
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007125 hap_register_post_deinit(ssl_free_global_issuers);
7126
Willy Tarreau80713382018-11-26 10:19:54 +01007127#ifndef OPENSSL_NO_DH
7128 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7129 hap_register_post_deinit(ssl_free_dh);
7130#endif
7131#ifndef OPENSSL_NO_ENGINE
7132 hap_register_post_deinit(ssl_free_engines);
7133#endif
7134 /* Load SSL string for the verbose & debug mode. */
7135 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02007136 ha_meth = BIO_meth_new(0x666, "ha methods");
7137 BIO_meth_set_write(ha_meth, ha_ssl_write);
7138 BIO_meth_set_read(ha_meth, ha_ssl_read);
7139 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7140 BIO_meth_set_create(ha_meth, ha_ssl_new);
7141 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7142 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7143 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007144
7145 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007146
Dragan Dosen9ac98092020-05-11 15:51:45 +02007147 /* Try to register dedicated SSL/TLS protocol message callbacks for
7148 * heartbleed attack (CVE-2014-0160) and clienthello.
7149 */
7150 hap_register_post_check(ssl_sock_register_msg_callbacks);
7151
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007152 /* Try to free all callbacks that were registered by using
7153 * ssl_sock_register_msg_callback().
7154 */
7155 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007156}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007157
Willy Tarreau80713382018-11-26 10:19:54 +01007158/* Compute and register the version string */
7159static void ssl_register_build_options()
7160{
7161 char *ptr = NULL;
7162 int i;
7163
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007164 memprintf(&ptr, "Built with OpenSSL version : "
7165#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007166 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007167#else /* OPENSSL_IS_BORINGSSL */
7168 OPENSSL_VERSION_TEXT
7169 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007170 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007171 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007172#endif
7173 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007174#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007175 "no (library version too old)"
7176#elif defined(OPENSSL_NO_TLSEXT)
7177 "no (disabled via OPENSSL_NO_TLSEXT)"
7178#else
7179 "yes"
7180#endif
7181 "", ptr);
7182
7183 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7184#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7185 "yes"
7186#else
7187#ifdef OPENSSL_NO_TLSEXT
7188 "no (because of OPENSSL_NO_TLSEXT)"
7189#else
7190 "no (version might be too old, 0.9.8f min needed)"
7191#endif
7192#endif
7193 "", ptr);
7194
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007195 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7196 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7197 if (methodVersions[i].option)
7198 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007199
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007200 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007201}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007202
Willy Tarreau80713382018-11-26 10:19:54 +01007203INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007204
Emeric Brun46591952012-05-18 15:47:34 +02007205
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007206#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007207void ssl_free_engines(void) {
7208 struct ssl_engine_list *wl, *wlb;
7209 /* free up engine list */
7210 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7211 ENGINE_finish(wl->e);
7212 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007213 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007214 free(wl);
7215 }
7216}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007217#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007218
Remi Gacogned3a23c32015-05-28 16:39:47 +02007219#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007220void ssl_free_dh(void) {
7221 if (local_dh_1024) {
7222 DH_free(local_dh_1024);
7223 local_dh_1024 = NULL;
7224 }
7225 if (local_dh_2048) {
7226 DH_free(local_dh_2048);
7227 local_dh_2048 = NULL;
7228 }
7229 if (local_dh_4096) {
7230 DH_free(local_dh_4096);
7231 local_dh_4096 = NULL;
7232 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007233 if (global_dh) {
7234 DH_free(global_dh);
7235 global_dh = NULL;
7236 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007237}
7238#endif
7239
7240__attribute__((destructor))
7241static void __ssl_sock_deinit(void)
7242{
7243#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007244 if (ssl_ctx_lru_tree) {
7245 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007246 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007247 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007248#endif
7249
Willy Tarreau5db847a2019-05-09 14:13:35 +02007250#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007251 ERR_remove_state(0);
7252 ERR_free_strings();
7253
7254 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007255#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007256
Willy Tarreau5db847a2019-05-09 14:13:35 +02007257#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007258 CRYPTO_cleanup_all_ex_data();
7259#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007260 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007261}
7262
William Dauchyf6370442020-11-14 19:25:33 +01007263/* Activate ssl on server <s>.
7264 * do nothing if there is no change to apply
7265 *
7266 * Must be called with the server lock held.
7267 */
7268void ssl_sock_set_srv(struct server *s, signed char use_ssl)
7269{
7270 if (s->use_ssl == use_ssl)
7271 return;
7272
7273 s->use_ssl = use_ssl;
7274 if (s->use_ssl == 1)
7275 s->xprt = &ssl_sock;
7276 else
7277 s->xprt = s->check.xprt = s->agent.xprt = xprt_get(XPRT_RAW);
7278}
7279
Emeric Brun46591952012-05-18 15:47:34 +02007280/*
7281 * Local variables:
7282 * c-indent-level: 8
7283 * c-basic-offset: 8
7284 * End:
7285 */