blob: 0fc3388df3c9a7a6935ae597e964eb95a930d07f [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,
Ilya Shipitsin04a5a442020-11-03 14:15:38 +0500130#ifdef HAVE_OPENSSL_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{
322 X509_STORE *store;
323 store = ssl_store_get0_locations_file(path);
324 if (store_ctx && store) {
325 int i;
326 X509_OBJECT *obj;
327 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
328 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
329 obj = sk_X509_OBJECT_value(objs, i);
330 switch (X509_OBJECT_get_type(obj)) {
331 case X509_LU_X509:
332 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
333 break;
334 case X509_LU_CRL:
335 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
336 break;
337 default:
338 break;
339 }
340 }
341 return 1;
342 }
343 return 0;
344}
345
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500346/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200347static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
348{
349 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
350 return ssl_set_cert_crl_file(store_ctx, path);
351}
352
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200353/*
354 Extract CA_list from CA_file already in tree.
355 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
356 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
357*/
358static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
359{
360 struct ebmb_node *eb;
361 struct cafile_entry *ca_e;
362
363 eb = ebst_lookup(&cafile_tree, path);
364 if (!eb)
365 return NULL;
366 ca_e = ebmb_entry(eb, struct cafile_entry, node);
367
368 if (ca_e->ca_list == NULL) {
369 int i;
370 unsigned long key;
371 struct eb_root ca_name_tree = EB_ROOT;
372 struct eb64_node *node, *back;
373 struct {
374 struct eb64_node node;
375 X509_NAME *xname;
376 } *ca_name;
377 STACK_OF(X509_OBJECT) *objs;
378 STACK_OF(X509_NAME) *skn;
379 X509 *x;
380 X509_NAME *xn;
381
382 skn = sk_X509_NAME_new_null();
383 /* take x509 from cafile_tree */
384 objs = X509_STORE_get0_objects(ca_e->ca_store);
385 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
386 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
387 if (!x)
388 continue;
389 xn = X509_get_subject_name(x);
390 if (!xn)
391 continue;
392 /* Check for duplicates. */
393 key = X509_NAME_hash(xn);
394 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
395 node && ca_name == NULL;
396 node = eb64_next(node)) {
397 ca_name = container_of(node, typeof(*ca_name), node);
398 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
399 ca_name = NULL;
400 }
401 /* find a duplicate */
402 if (ca_name)
403 continue;
404 ca_name = calloc(1, sizeof *ca_name);
405 xn = X509_NAME_dup(xn);
406 if (!ca_name ||
407 !xn ||
408 !sk_X509_NAME_push(skn, xn)) {
409 free(ca_name);
410 X509_NAME_free(xn);
411 sk_X509_NAME_pop_free(skn, X509_NAME_free);
412 sk_X509_NAME_free(skn);
413 skn = NULL;
414 break;
415 }
416 ca_name->node.key = key;
417 ca_name->xname = xn;
418 eb64_insert(&ca_name_tree, &ca_name->node);
419 }
420 ca_e->ca_list = skn;
421 /* remove temporary ca_name tree */
422 node = eb64_first(&ca_name_tree);
423 while (node) {
424 ca_name = container_of(node, typeof(*ca_name), node);
425 back = eb64_next(node);
426 eb64_delete(node);
427 free(ca_name);
428 node = back;
429 }
430 }
431 return ca_e->ca_list;
432}
433
Willy Tarreauff882702021-04-10 17:23:00 +0200434struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200435int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100436int ssl_app_data_index = -1;
Willy Tarreauef934602016-12-22 23:12:01 +0100437
Ilya Shipitsin04a5a442020-11-03 14:15:38 +0500438#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200439int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200440struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
441struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200442#endif
443
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200444#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
445struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
446#endif
447
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200448#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200449unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000450struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
451struct ssl_engine_list {
452 struct list list;
453 ENGINE *e;
454};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200455#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000456
Remi Gacogne8de54152014-07-15 11:36:40 +0200457#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200458static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200459static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200460static DH *local_dh_1024 = NULL;
461static DH *local_dh_2048 = NULL;
462static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100463static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200464#endif /* OPENSSL_NO_DH */
465
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100466#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200467/* X509V3 Extensions that will be added on generated certificates */
468#define X509V3_EXT_SIZE 5
469static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
470 "basicConstraints",
471 "nsComment",
472 "subjectKeyIdentifier",
473 "authorityKeyIdentifier",
474 "keyUsage",
475};
476static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
477 "CA:FALSE",
478 "\"OpenSSL Generated Certificate\"",
479 "hash",
480 "keyid,issuer:always",
481 "nonRepudiation,digitalSignature,keyEncipherment"
482};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200483/* LRU cache to store generated certificate */
484static struct lru64_head *ssl_ctx_lru_tree = NULL;
485static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200486static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100487__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200488
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200489#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
490
yanbzhube2774d2015-12-10 15:07:30 -0500491/* The order here matters for picking a default context,
492 * keep the most common keytype at the bottom of the list
493 */
494const char *SSL_SOCK_KEYTYPE_NAMES[] = {
495 "dsa",
496 "ecdsa",
497 "rsa"
498};
yanbzhube2774d2015-12-10 15:07:30 -0500499
William Lallemandc3cd35f2017-11-28 11:04:43 +0100500static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100501static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
502
Dragan Dosen9ac98092020-05-11 15:51:45 +0200503/* Dedicated callback functions for heartbeat and clienthello.
504 */
505#ifdef TLS1_RT_HEARTBEAT
506static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
507 int content_type, const void *buf, size_t len,
508 SSL *ssl);
509#endif
510static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
511 int content_type, const void *buf, size_t len,
512 SSL *ssl);
513
Ilya Shipitsin04a5a442020-11-03 14:15:38 +0500514#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200515static void ssl_init_keylog(struct connection *conn, int write_p, int version,
516 int content_type, const void *buf, size_t len,
517 SSL *ssl);
518#endif
519
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200520/* List head of all registered SSL/TLS protocol message callbacks. */
521struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
522
523/* Registers the function <func> in order to be called on SSL/TLS protocol
524 * message processing. It will return 0 if the function <func> is not set
525 * or if it fails to allocate memory.
526 */
527int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
528{
529 struct ssl_sock_msg_callback *cbk;
530
531 if (!func)
532 return 0;
533
534 cbk = calloc(1, sizeof(*cbk));
535 if (!cbk) {
536 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
537 return 0;
538 }
539
540 cbk->func = func;
541
Willy Tarreau2b718102021-04-21 07:32:39 +0200542 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200543
544 return 1;
545}
546
Dragan Dosen9ac98092020-05-11 15:51:45 +0200547/* Used to register dedicated SSL/TLS protocol message callbacks.
548 */
549static int ssl_sock_register_msg_callbacks(void)
550{
551#ifdef TLS1_RT_HEARTBEAT
552 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
553 return ERR_ABORT;
554#endif
555 if (global_ssl.capture_cipherlist > 0) {
556 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
557 return ERR_ABORT;
558 }
Ilya Shipitsin04a5a442020-11-03 14:15:38 +0500559#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200560 if (global_ssl.keylog > 0) {
561 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
562 return ERR_ABORT;
563 }
564#endif
565
Christopher Fauletfc633b62020-11-06 15:24:23 +0100566 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200567}
568
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200569/* Used to free all SSL/TLS protocol message callbacks that were
570 * registered by using ssl_sock_register_msg_callback().
571 */
572static void ssl_sock_unregister_msg_callbacks(void)
573{
574 struct ssl_sock_msg_callback *cbk, *cbkback;
575
576 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200577 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200578 free(cbk);
579 }
580}
581
Dragan Doseneb607fe2020-05-11 17:17:06 +0200582SSL *ssl_sock_get_ssl_object(struct connection *conn)
583{
584 if (!ssl_sock_is_ssl(conn))
585 return NULL;
586
587 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
588}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100589/*
590 * This function gives the detail of the SSL error. It is used only
591 * if the debug mode and the verbose mode are activated. It dump all
592 * the SSL error until the stack was empty.
593 */
594static forceinline void ssl_sock_dump_errors(struct connection *conn)
595{
596 unsigned long ret;
597
598 if (unlikely(global.mode & MODE_DEBUG)) {
599 while(1) {
600 ret = ERR_get_error();
601 if (ret == 0)
602 return;
Willy Tarreau566cebc2021-03-02 19:32:39 +0100603 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
604 conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100605 ERR_func_error_string(ret), ERR_reason_error_string(ret));
606 }
607 }
608}
609
yanbzhube2774d2015-12-10 15:07:30 -0500610
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200611#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200612int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000613{
614 int err_code = ERR_ABORT;
615 ENGINE *engine;
616 struct ssl_engine_list *el;
617
618 /* grab the structural reference to the engine */
619 engine = ENGINE_by_id(engine_id);
620 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100621 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000622 goto fail_get;
623 }
624
625 if (!ENGINE_init(engine)) {
626 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100627 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000628 goto fail_init;
629 }
630
631 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100632 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000633 goto fail_set_method;
634 }
635
636 el = calloc(1, sizeof(*el));
637 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200638 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100639 nb_engines++;
640 if (global_ssl.async)
641 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000642 return 0;
643
644fail_set_method:
645 /* release the functional reference from ENGINE_init() */
646 ENGINE_finish(engine);
647
648fail_init:
649 /* release the structural reference from ENGINE_by_id() */
650 ENGINE_free(engine);
651
652fail_get:
653 return err_code;
654}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200655#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000656
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500657#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200658/*
659 * openssl async fd handler
660 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200661void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000662{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200663 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000664
Emeric Brun3854e012017-05-17 20:42:48 +0200665 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000666 * to poll this fd until it is requested
667 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000668 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000669 fd_cant_recv(fd);
670
671 /* crypto engine is available, let's notify the associated
672 * connection that it can pursue its processing.
673 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200674 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000675}
676
Emeric Brun3854e012017-05-17 20:42:48 +0200677/*
678 * openssl async delayed SSL_free handler
679 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200680void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000681{
682 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200683 OSSL_ASYNC_FD all_fd[32];
684 size_t num_all_fds = 0;
685 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000686
Emeric Brun3854e012017-05-17 20:42:48 +0200687 /* We suppose that the async job for a same SSL *
688 * are serialized. So if we are awake it is
689 * because the running job has just finished
690 * and we can remove all async fds safely
691 */
692 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
693 if (num_all_fds > 32) {
694 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
695 return;
696 }
697
698 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
699 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200700 fd_stop_both(all_fd[i]);
Emeric Brun3854e012017-05-17 20:42:48 +0200701
702 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000703 SSL_free(ssl);
Willy Tarreau4781b152021-04-06 13:53:36 +0200704 _HA_ATOMIC_DEC(&sslconns);
705 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000706}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000707/*
Emeric Brun3854e012017-05-17 20:42:48 +0200708 * function used to manage a returned SSL_ERROR_WANT_ASYNC
709 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000710 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200711static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000712{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100713 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200714 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200715 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000716 size_t num_add_fds = 0;
717 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200718 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000719
720 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
721 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200722 if (num_add_fds > 32 || num_del_fds > 32) {
723 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 +0000724 return;
725 }
726
Emeric Brun3854e012017-05-17 20:42:48 +0200727 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000728
Emeric Brun3854e012017-05-17 20:42:48 +0200729 /* We remove unused fds from the fdtab */
730 for (i=0 ; i < num_del_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200731 fd_stop_both(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000732
Emeric Brun3854e012017-05-17 20:42:48 +0200733 /* We add new fds to the fdtab */
734 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200735 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000736 }
737
Emeric Brun3854e012017-05-17 20:42:48 +0200738 num_add_fds = 0;
739 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
740 if (num_add_fds > 32) {
741 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
742 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000743 }
Emeric Brun3854e012017-05-17 20:42:48 +0200744
745 /* We activate the polling for all known async fds */
746 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000747 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200748 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000749 /* To ensure that the fd cache won't be used
750 * We'll prefer to catch a real RD event
751 * because handling an EAGAIN on this fd will
752 * result in a context switch and also
753 * some engines uses a fd in blocking mode.
754 */
755 fd_cant_recv(add_fd[i]);
756 }
Emeric Brun3854e012017-05-17 20:42:48 +0200757
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000758}
759#endif
760
William Lallemand104a7a62019-10-14 14:14:59 +0200761#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200762/*
763 * This function returns the number of seconds elapsed
764 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
765 * date presented un ASN1_GENERALIZEDTIME.
766 *
767 * In parsing error case, it returns -1.
768 */
769static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
770{
771 long epoch;
772 char *p, *end;
773 const unsigned short month_offset[12] = {
774 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
775 };
776 int year, month;
777
778 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
779
780 p = (char *)d->data;
781 end = p + d->length;
782
783 if (end - p < 4) return -1;
784 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
785 p += 4;
786 if (end - p < 2) return -1;
787 month = 10 * (p[0] - '0') + p[1] - '0';
788 if (month < 1 || month > 12) return -1;
789 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
790 We consider leap years and the current month (<marsh or not) */
791 epoch = ( ((year - 1970) * 365)
792 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
793 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
794 + month_offset[month-1]
795 ) * 24 * 60 * 60;
796 p += 2;
797 if (end - p < 2) return -1;
798 /* Add the number of seconds of completed days of current month */
799 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
800 p += 2;
801 if (end - p < 2) return -1;
802 /* Add the completed hours of the current day */
803 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
804 p += 2;
805 if (end - p < 2) return -1;
806 /* Add the completed minutes of the current hour */
807 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
808 p += 2;
809 if (p == end) return -1;
810 /* Test if there is available seconds */
811 if (p[0] < '0' || p[0] > '9')
812 goto nosec;
813 if (end - p < 2) return -1;
814 /* Add the seconds of the current minute */
815 epoch += 10 * (p[0] - '0') + p[1] - '0';
816 p += 2;
817 if (p == end) return -1;
818 /* Ignore seconds float part if present */
819 if (p[0] == '.') {
820 do {
821 if (++p == end) return -1;
822 } while (p[0] >= '0' && p[0] <= '9');
823 }
824
825nosec:
826 if (p[0] == 'Z') {
827 if (end - p != 1) return -1;
828 return epoch;
829 }
830 else if (p[0] == '+') {
831 if (end - p != 5) return -1;
832 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700833 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 +0200834 }
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
841 return -1;
842}
843
William Lallemand104a7a62019-10-14 14:14:59 +0200844/*
845 * struct alignment works here such that the key.key is the same as key_data
846 * Do not change the placement of key_data
847 */
848struct certificate_ocsp {
849 struct ebmb_node key;
850 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
851 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200852 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200853 long expire;
854};
855
856struct ocsp_cbk_arg {
857 int is_single;
858 int single_kt;
859 union {
860 struct certificate_ocsp *s_ocsp;
861 /*
862 * m_ocsp will have multiple entries dependent on key type
863 * Entry 0 - DSA
864 * Entry 1 - ECDSA
865 * Entry 2 - RSA
866 */
867 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
868 };
869};
870
Emeric Brun1d3865b2014-06-20 15:37:32 +0200871static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200872
873/* This function starts to check if the OCSP response (in DER format) contained
874 * in chunk 'ocsp_response' is valid (else exits on error).
875 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
876 * contained in the OCSP Response and exits on error if no match.
877 * If it's a valid OCSP Response:
878 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
879 * pointed by 'ocsp'.
880 * If 'ocsp' is NULL, the function looks up into the OCSP response's
881 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
882 * from the response) and exits on error if not found. Finally, If an OCSP response is
883 * already present in the container, it will be overwritten.
884 *
885 * Note: OCSP response containing more than one OCSP Single response is not
886 * considered valid.
887 *
888 * Returns 0 on success, 1 in error case.
889 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200890static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
891 struct certificate_ocsp *ocsp,
892 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200893{
894 OCSP_RESPONSE *resp;
895 OCSP_BASICRESP *bs = NULL;
896 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200897 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200898 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200899 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200900 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200901 int reason;
902 int ret = 1;
903
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200904 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
905 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200906 if (!resp) {
907 memprintf(err, "Unable to parse OCSP response");
908 goto out;
909 }
910
911 rc = OCSP_response_status(resp);
912 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
913 memprintf(err, "OCSP response status not successful");
914 goto out;
915 }
916
917 bs = OCSP_response_get1_basic(resp);
918 if (!bs) {
919 memprintf(err, "Failed to get basic response from OCSP Response");
920 goto out;
921 }
922
923 count_sr = OCSP_resp_count(bs);
924 if (count_sr > 1) {
925 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
926 goto out;
927 }
928
929 sr = OCSP_resp_get0(bs, 0);
930 if (!sr) {
931 memprintf(err, "Failed to get OCSP single response");
932 goto out;
933 }
934
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200935 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
936
Emeric Brun4147b2e2014-06-16 18:36:30 +0200937 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200938 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200939 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200940 goto out;
941 }
942
Emeric Brun13a6b482014-06-20 15:44:34 +0200943 if (!nextupd) {
944 memprintf(err, "OCSP single response: missing nextupdate");
945 goto out;
946 }
947
Emeric Brunc8b27b62014-06-19 14:16:17 +0200948 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200949 if (!rc) {
950 memprintf(err, "OCSP single response: no longer valid.");
951 goto out;
952 }
953
954 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200955 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +0200956 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
957 goto out;
958 }
959 }
960
961 if (!ocsp) {
962 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
963 unsigned char *p;
964
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200965 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200966 if (!rc) {
967 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
968 goto out;
969 }
970
971 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
972 memprintf(err, "OCSP single response: Certificate ID too long");
973 goto out;
974 }
975
976 p = key;
977 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200978 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200979 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
980 if (!ocsp) {
981 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
982 goto out;
983 }
984 }
985
986 /* According to comments on "chunk_dup", the
987 previous chunk buffer will be freed */
988 if (!chunk_dup(&ocsp->response, ocsp_response)) {
989 memprintf(err, "OCSP response: Memory allocation error");
990 goto out;
991 }
992
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200993 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
994
Emeric Brun4147b2e2014-06-16 18:36:30 +0200995 ret = 0;
996out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +0100997 ERR_clear_error();
998
Emeric Brun4147b2e2014-06-16 18:36:30 +0200999 if (bs)
1000 OCSP_BASICRESP_free(bs);
1001
1002 if (resp)
1003 OCSP_RESPONSE_free(resp);
1004
1005 return ret;
1006}
1007/*
1008 * External function use to update the OCSP response in the OCSP response's
1009 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1010 * to update in DER format.
1011 *
1012 * Returns 0 on success, 1 in error case.
1013 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001014int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001015{
1016 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1017}
1018
William Lallemand4a660132019-10-14 14:51:41 +02001019#endif
1020
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001021#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1022static 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)
1023{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001024 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001025 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001026 struct connection *conn;
1027 int head;
1028 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001029 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001030
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001031 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001032 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001033 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1034
1035 keys = ref->tlskeys;
1036 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001037
1038 if (enc) {
1039 memcpy(key_name, keys[head].name, 16);
1040
1041 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001042 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001043
Emeric Brun9e754772019-01-10 17:51:55 +01001044 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001045
Emeric Brun9e754772019-01-10 17:51:55 +01001046 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1047 goto end;
1048
Willy Tarreau9356dac2019-05-10 09:22:53 +02001049 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001050 ret = 1;
1051 }
1052 else if (ref->key_size_bits == 256 ) {
1053
1054 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1055 goto end;
1056
Willy Tarreau9356dac2019-05-10 09:22:53 +02001057 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001058 ret = 1;
1059 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001060 } else {
1061 for (i = 0; i < TLS_TICKETS_NO; i++) {
1062 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1063 goto found;
1064 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001065 ret = 0;
1066 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001067
Christopher Faulet16f45c82018-02-16 11:23:49 +01001068 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001069 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001070 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 +01001071 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1072 goto end;
1073 /* 2 for key renewal, 1 if current key is still valid */
1074 ret = i ? 2 : 1;
1075 }
1076 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001077 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 +01001078 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1079 goto end;
1080 /* 2 for key renewal, 1 if current key is still valid */
1081 ret = i ? 2 : 1;
1082 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001083 }
Emeric Brun9e754772019-01-10 17:51:55 +01001084
Christopher Faulet16f45c82018-02-16 11:23:49 +01001085 end:
1086 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1087 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001088}
1089
1090struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1091{
1092 struct tls_keys_ref *ref;
1093
1094 list_for_each_entry(ref, &tlskeys_reference, list)
1095 if (ref->filename && strcmp(filename, ref->filename) == 0)
1096 return ref;
1097 return NULL;
1098}
1099
1100struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1101{
1102 struct tls_keys_ref *ref;
1103
1104 list_for_each_entry(ref, &tlskeys_reference, list)
1105 if (ref->unique_id == unique_id)
1106 return ref;
1107 return NULL;
1108}
1109
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001110/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001111 * match existing ones, this function returns -1
1112 * else it returns 0 on success.
1113 */
1114int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001115 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001116{
Emeric Brun9e754772019-01-10 17:51:55 +01001117 if (ref->key_size_bits == 128) {
1118 if (tlskey->data != sizeof(struct tls_sess_key_128))
1119 return -1;
1120 }
1121 else if (ref->key_size_bits == 256) {
1122 if (tlskey->data != sizeof(struct tls_sess_key_256))
1123 return -1;
1124 }
1125 else
1126 return -1;
1127
Christopher Faulet16f45c82018-02-16 11:23:49 +01001128 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001129 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1130 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001131 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1132 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001133
1134 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001135}
1136
Willy Tarreau83061a82018-07-13 11:56:34 +02001137int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001138{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001139 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1140
1141 if(!ref) {
1142 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1143 return 1;
1144 }
Emeric Brun9e754772019-01-10 17:51:55 +01001145 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1146 memprintf(err, "Invalid key size");
1147 return 1;
1148 }
1149
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001150 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001151}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001152
1153/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001154 * automatic ids. It's called just after the basic checks. It returns
1155 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001156 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001157static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001158{
1159 int i = 0;
1160 struct tls_keys_ref *ref, *ref2, *ref3;
1161 struct list tkr = LIST_HEAD_INIT(tkr);
1162
1163 list_for_each_entry(ref, &tlskeys_reference, list) {
1164 if (ref->unique_id == -1) {
1165 /* Look for the first free id. */
1166 while (1) {
1167 list_for_each_entry(ref2, &tlskeys_reference, list) {
1168 if (ref2->unique_id == i) {
1169 i++;
1170 break;
1171 }
1172 }
1173 if (&ref2->list == &tlskeys_reference)
1174 break;
1175 }
1176
1177 /* Uses the unique id and increment it for the next entry. */
1178 ref->unique_id = i;
1179 i++;
1180 }
1181 }
1182
1183 /* This sort the reference list by id. */
1184 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001185 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001186 list_for_each_entry(ref3, &tkr, list) {
1187 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001188 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001189 break;
1190 }
1191 }
1192 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001193 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001194 }
1195
1196 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001197 LIST_INSERT(&tkr, &tlskeys_reference);
1198 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001199 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001200}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001201#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1202
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001203#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001204int ocsp_ex_index = -1;
1205
yanbzhube2774d2015-12-10 15:07:30 -05001206int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1207{
1208 switch (evp_keytype) {
1209 case EVP_PKEY_RSA:
1210 return 2;
1211 case EVP_PKEY_DSA:
1212 return 0;
1213 case EVP_PKEY_EC:
1214 return 1;
1215 }
1216
1217 return -1;
1218}
1219
Emeric Brun4147b2e2014-06-16 18:36:30 +02001220/*
1221 * Callback used to set OCSP status extension content in server hello.
1222 */
1223int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1224{
yanbzhube2774d2015-12-10 15:07:30 -05001225 struct certificate_ocsp *ocsp;
1226 struct ocsp_cbk_arg *ocsp_arg;
1227 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001228 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001229 EVP_PKEY *ssl_pkey;
1230 int key_type;
1231 int index;
1232
William Lallemand76b4a122020-08-04 17:41:39 +02001233 ctx = SSL_get_SSL_CTX(ssl);
1234 if (!ctx)
1235 return SSL_TLSEXT_ERR_NOACK;
1236
1237 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1238 if (!ocsp_arg)
1239 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001240
1241 ssl_pkey = SSL_get_privatekey(ssl);
1242 if (!ssl_pkey)
1243 return SSL_TLSEXT_ERR_NOACK;
1244
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001245 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001246
1247 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1248 ocsp = ocsp_arg->s_ocsp;
1249 else {
1250 /* For multiple certs per context, we have to find the correct OCSP response based on
1251 * the certificate type
1252 */
1253 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1254
1255 if (index < 0)
1256 return SSL_TLSEXT_ERR_NOACK;
1257
1258 ocsp = ocsp_arg->m_ocsp[index];
1259
1260 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001261
1262 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001263 !ocsp->response.area ||
1264 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001265 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001266 return SSL_TLSEXT_ERR_NOACK;
1267
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001268 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001269 if (!ssl_buf)
1270 return SSL_TLSEXT_ERR_NOACK;
1271
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001272 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1273 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001274
1275 return SSL_TLSEXT_ERR_OK;
1276}
1277
William Lallemand4a660132019-10-14 14:51:41 +02001278#endif
1279
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001280#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001281
1282
1283/*
1284 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1285 * used anymore. Also removes it from the tree if free'd.
1286 */
1287static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1288{
1289 if (!ocsp)
1290 return;
1291
1292 ocsp->refcount--;
1293 if (ocsp->refcount <= 0) {
1294 ebmb_delete(&ocsp->key);
1295 chunk_destroy(&ocsp->response);
1296 free(ocsp);
1297 }
1298}
1299
1300
Emeric Brun4147b2e2014-06-16 18:36:30 +02001301/*
1302 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001303 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1304 * status extension, the issuer's certificate is mandatory. It should be
1305 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001306 *
William Lallemand246c0242019-10-11 08:59:13 +02001307 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1308 * OCSP response. If file is empty or content is not a valid OCSP response,
1309 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1310 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001311 *
1312 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001313 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001314 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001315static 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 +02001316{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001317 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001318 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001319 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001320 struct certificate_ocsp *ocsp = NULL, *iocsp;
1321 char *warn = NULL;
1322 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001323 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001324
Emeric Brun4147b2e2014-06-16 18:36:30 +02001325
William Lallemand246c0242019-10-11 08:59:13 +02001326 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001327 if (!x)
1328 goto out;
1329
William Lallemand246c0242019-10-11 08:59:13 +02001330 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001331 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1332 if (chain) {
1333 /* check if one of the certificate of the chain is the issuer */
1334 for (i = 0; i < sk_X509_num(chain); i++) {
1335 X509 *ti = sk_X509_value(chain, i);
1336 if (X509_check_issued(ti, x) == X509_V_OK) {
1337 issuer = ti;
1338 break;
1339 }
1340 }
1341 }
William Lallemand246c0242019-10-11 08:59:13 +02001342 if (!issuer)
1343 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001344
1345 cid = OCSP_cert_to_id(0, x, issuer);
1346 if (!cid)
1347 goto out;
1348
1349 i = i2d_OCSP_CERTID(cid, NULL);
1350 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1351 goto out;
1352
Vincent Bernat02779b62016-04-03 13:48:43 +02001353 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001354 if (!ocsp)
1355 goto out;
1356
1357 p = ocsp->key_data;
1358 i2d_OCSP_CERTID(cid, &p);
1359
1360 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1361 if (iocsp == ocsp)
1362 ocsp = NULL;
1363
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001364#ifndef SSL_CTX_get_tlsext_status_cb
1365# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1366 *cb = (void (*) (void))ctx->tlsext_status_cb;
1367#endif
1368 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1369
1370 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001371 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001372 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001373
William Lallemanda560c062020-07-31 11:43:20 +02001374 cb_arg = calloc(1, sizeof(*cb_arg));
1375 if (!cb_arg)
1376 goto out;
1377
yanbzhube2774d2015-12-10 15:07:30 -05001378 cb_arg->is_single = 1;
1379 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001380 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001381
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001382 pkey = X509_get_pubkey(x);
1383 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1384 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001385
1386 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001387 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 */
1388
yanbzhube2774d2015-12-10 15:07:30 -05001389 } else {
1390 /*
1391 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1392 * Update that cb_arg with the new cert's staple
1393 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001394 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001395 struct certificate_ocsp *tmp_ocsp;
1396 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001397 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001398 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001399
William Lallemand76b4a122020-08-04 17:41:39 +02001400 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001401
1402 /*
1403 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1404 * the order of operations below matter, take care when changing it
1405 */
1406 tmp_ocsp = cb_arg->s_ocsp;
1407 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1408 cb_arg->s_ocsp = NULL;
1409 cb_arg->m_ocsp[index] = tmp_ocsp;
1410 cb_arg->is_single = 0;
1411 cb_arg->single_kt = 0;
1412
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001413 pkey = X509_get_pubkey(x);
1414 key_type = EVP_PKEY_base_id(pkey);
1415 EVP_PKEY_free(pkey);
1416
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001417 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001418 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001419 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001420 iocsp->refcount++;
1421 }
yanbzhube2774d2015-12-10 15:07:30 -05001422 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001423
1424 ret = 0;
1425
1426 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001427 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001428 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001429 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001430 }
1431
1432out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001433 if (cid)
1434 OCSP_CERTID_free(cid);
1435
1436 if (ocsp)
1437 free(ocsp);
1438
1439 if (warn)
1440 free(warn);
1441
Emeric Brun4147b2e2014-06-16 18:36:30 +02001442 return ret;
1443}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001444#endif
1445
1446#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001447static 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 +02001448{
William Lallemand4a660132019-10-14 14:51:41 +02001449 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 +02001450}
1451#endif
1452
William Lallemand4a660132019-10-14 14:51:41 +02001453
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001454#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001455
1456#define CT_EXTENSION_TYPE 18
1457
William Lallemand03c331c2020-05-13 10:10:01 +02001458int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001459
1460int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1461{
Willy Tarreau83061a82018-07-13 11:56:34 +02001462 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001463
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001464 *out = (unsigned char *) sctl->area;
1465 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001466
1467 return 1;
1468}
1469
1470int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1471{
1472 return 1;
1473}
1474
William Lallemanda17f4112019-10-10 15:16:44 +02001475static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001476{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001477 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001478
William Lallemanda17f4112019-10-10 15:16:44 +02001479 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 +01001480 goto out;
1481
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001482 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1483
1484 ret = 0;
1485
1486out:
1487 return ret;
1488}
1489
1490#endif
1491
Emeric Brune1f38db2012-09-03 20:36:47 +02001492void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1493{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001494 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001495 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001496 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001497 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001498
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001499#ifndef SSL_OP_NO_RENEGOTIATION
1500 /* Please note that BoringSSL defines this macro to zero so don't
1501 * change this to #if and do not assign a default value to this macro!
1502 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001503 if (where & SSL_CB_HANDSHAKE_START) {
1504 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001505 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 +02001506 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001507 conn->err_code = CO_ER_SSL_RENEG;
1508 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001509 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001510#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001511
1512 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001513 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001514 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001515 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001516 consider that the buffering was activated,
1517 so we rise the output buffer size from 4k
1518 to 16k */
1519 write_bio = SSL_get_wbio(ssl);
1520 if (write_bio != SSL_get_rbio(ssl)) {
1521 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001522 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001523 }
1524 }
1525 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001526}
1527
Emeric Brune64aef12012-09-21 13:15:06 +02001528/* Callback is called for each certificate of the chain during a verify
1529 ok is set to 1 if preverify detect no error on current certificate.
1530 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001531int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001532{
1533 SSL *ssl;
1534 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001535 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001536 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001537
1538 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001539 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001540
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001541 ctx = conn->xprt_ctx;
1542
1543 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001544
Emeric Brun81c00f02012-09-21 14:31:21 +02001545 if (ok) /* no errors */
1546 return ok;
1547
1548 depth = X509_STORE_CTX_get_error_depth(x_store);
1549 err = X509_STORE_CTX_get_error(x_store);
1550
1551 /* check if CA error needs to be ignored */
1552 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001553 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1554 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1555 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001556 }
1557
Willy Tarreau731248f2020-02-04 14:02:02 +01001558 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001559 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001560 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001561 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001562 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001563
Willy Tarreau20879a02012-12-03 16:32:10 +01001564 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001565 return 0;
1566 }
1567
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001568 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1569 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001570
Emeric Brun81c00f02012-09-21 14:31:21 +02001571 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001572 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001573 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001574 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001575 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001576 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001577
Willy Tarreau20879a02012-12-03 16:32:10 +01001578 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001579 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001580}
1581
Dragan Dosen9ac98092020-05-11 15:51:45 +02001582#ifdef TLS1_RT_HEARTBEAT
1583static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1584 int content_type, const void *buf, size_t len,
1585 SSL *ssl)
1586{
1587 /* test heartbeat received (write_p is set to 0
1588 for a received record) */
1589 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1590 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1591 const unsigned char *p = buf;
1592 unsigned int payload;
1593
1594 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1595
1596 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1597 if (*p != TLS1_HB_REQUEST)
1598 return;
1599
1600 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1601 goto kill_it;
1602
1603 payload = (p[1] * 256) + p[2];
1604 if (3 + payload + 16 <= len)
1605 return; /* OK no problem */
1606 kill_it:
1607 /* We have a clear heartbleed attack (CVE-2014-0160), the
1608 * advertised payload is larger than the advertised packet
1609 * length, so we have garbage in the buffer between the
1610 * payload and the end of the buffer (p+len). We can't know
1611 * if the SSL stack is patched, and we don't know if we can
1612 * safely wipe out the area between p+3+len and payload.
1613 * So instead, we prevent the response from being sent by
1614 * setting the max_send_fragment to 0 and we report an SSL
1615 * error, which will kill this connection. It will be reported
1616 * above as SSL_ERROR_SSL while an other handshake failure with
1617 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1618 */
1619 ssl->max_send_fragment = 0;
1620 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1621 }
1622}
1623#endif
1624
1625static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1626 int content_type, const void *buf, size_t len,
1627 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001628{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001629 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001630 unsigned char *msg;
1631 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001632 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001633
1634 /* This function is called for "from client" and "to server"
1635 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001636 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001637 */
1638
1639 /* "write_p" is set to 0 is the bytes are received messages,
1640 * otherwise it is set to 1.
1641 */
1642 if (write_p != 0)
1643 return;
1644
1645 /* content_type contains the type of message received or sent
1646 * according with the SSL/TLS protocol spec. This message is
1647 * encoded with one byte. The value 256 (two bytes) is used
1648 * for designing the SSL/TLS record layer. According with the
1649 * rfc6101, the expected message (other than 256) are:
1650 * - change_cipher_spec(20)
1651 * - alert(21)
1652 * - handshake(22)
1653 * - application_data(23)
1654 * - (255)
1655 * We are interessed by the handshake and specially the client
1656 * hello.
1657 */
1658 if (content_type != 22)
1659 return;
1660
1661 /* The message length is at least 4 bytes, containing the
1662 * message type and the message length.
1663 */
1664 if (len < 4)
1665 return;
1666
1667 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001668 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001669 * - hello_request(0)
1670 * - client_hello(1)
1671 * - server_hello(2)
1672 * - certificate(11)
1673 * - server_key_exchange (12)
1674 * - certificate_request(13)
1675 * - server_hello_done(14)
1676 * We are interested by the client hello.
1677 */
1678 msg = (unsigned char *)buf;
1679 if (msg[0] != 1)
1680 return;
1681
1682 /* Next three bytes are the length of the message. The total length
1683 * must be this decoded length + 4. If the length given as argument
1684 * is not the same, we abort the protocol dissector.
1685 */
1686 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1687 if (len < rec_len + 4)
1688 return;
1689 msg += 4;
1690 end = msg + rec_len;
1691 if (end < msg)
1692 return;
1693
1694 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1695 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001696 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1697 */
1698 msg += 1 + 1 + 4 + 28;
1699 if (msg > end)
1700 return;
1701
1702 /* Next, is session id:
1703 * if present, we have to jump by length + 1 for the size information
1704 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001705 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001706 if (msg[0] > 0)
1707 msg += msg[0];
1708 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001709 if (msg > end)
1710 return;
1711
1712 /* Next two bytes are the ciphersuite length. */
1713 if (msg + 2 > end)
1714 return;
1715 rec_len = (msg[0] << 8) + msg[1];
1716 msg += 2;
1717 if (msg + rec_len > end || msg + rec_len < msg)
1718 return;
1719
Willy Tarreaub454e902021-03-22 15:09:41 +01001720 capture = pool_alloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001721 if (!capture)
1722 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001723 /* Compute the xxh64 of the ciphersuite. */
1724 capture->xxh64 = XXH64(msg, rec_len, 0);
1725
1726 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001727 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1728 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001729 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001730
1731 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001732}
William Lallemand7d42ef52020-07-06 11:41:30 +02001733
1734
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05001735#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001736static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1737 int content_type, const void *buf, size_t len,
1738 SSL *ssl)
1739{
1740 struct ssl_keylog *keylog;
1741
1742 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1743 return;
1744
Willy Tarreauf208ac02021-03-22 21:10:12 +01001745 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001746 if (!keylog)
1747 return;
1748
William Lallemand7d42ef52020-07-06 11:41:30 +02001749 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1750 pool_free(pool_head_ssl_keylog, keylog);
1751 return;
1752 }
1753}
1754#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001755
Emeric Brun29f037d2014-04-25 19:05:36 +02001756/* Callback is called for ssl protocol analyse */
1757void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1758{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001759 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1760 struct ssl_sock_msg_callback *cbk;
1761
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001762 /* Try to call all callback functions that were registered by using
1763 * ssl_sock_register_msg_callback().
1764 */
1765 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1766 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1767 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001768}
1769
Bernard Spil13c53f82018-02-15 13:34:58 +01001770#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001771static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1772 const unsigned char *in, unsigned int inlen,
1773 void *arg)
1774{
1775 struct server *srv = arg;
1776
1777 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1778 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1779 return SSL_TLSEXT_ERR_OK;
1780 return SSL_TLSEXT_ERR_NOACK;
1781}
1782#endif
1783
1784#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001785/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001786 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001787 */
1788static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1789 unsigned int *len, void *arg)
1790{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001791 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001792
1793 *data = (const unsigned char *)conf->npn_str;
1794 *len = conf->npn_len;
1795 return SSL_TLSEXT_ERR_OK;
1796}
1797#endif
1798
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001799#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001800/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001801 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001802 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001803static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1804 unsigned char *outlen,
1805 const unsigned char *server,
1806 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001807{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001808 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001809
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001810 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1811 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1812 return SSL_TLSEXT_ERR_NOACK;
1813 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001814 return SSL_TLSEXT_ERR_OK;
1815}
1816#endif
1817
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001818#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001819#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001820
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001821/* Configure a DNS SAN extenion on a certificate. */
1822int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1823 int failure = 0;
1824 X509_EXTENSION *san_ext = NULL;
1825 CONF *conf = NULL;
1826 struct buffer *san_name = get_trash_chunk();
1827
1828 conf = NCONF_new(NULL);
1829 if (!conf) {
1830 failure = 1;
1831 goto cleanup;
1832 }
1833
1834 /* Build an extension based on the DNS entry above */
1835 chunk_appendf(san_name, "DNS:%s", servername);
1836 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1837 if (!san_ext) {
1838 failure = 1;
1839 goto cleanup;
1840 }
1841
1842 /* Add the extension */
1843 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1844 failure = 1;
1845 goto cleanup;
1846 }
1847
1848 /* Success */
1849 failure = 0;
1850
1851cleanup:
1852 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1853 if (NULL != conf) NCONF_free(conf);
1854
1855 return failure;
1856}
1857
Christopher Faulet30548802015-06-11 13:39:32 +02001858/* Create a X509 certificate with the specified servername and serial. This
1859 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001860static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001861ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001862{
Shimi Gersner5846c492020-08-23 13:58:12 +03001863 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1864 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001865 SSL_CTX *ssl_ctx = NULL;
1866 X509 *newcrt = NULL;
1867 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001868 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001869 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001870 X509_NAME *name;
1871 const EVP_MD *digest;
1872 X509V3_CTX ctx;
1873 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001874 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001875
Christopher Faulet48a83322017-07-28 16:56:09 +02001876 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001877#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001878 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1879#else
1880 tmp_ssl = SSL_new(bind_conf->default_ctx);
1881 if (tmp_ssl)
1882 pkey = SSL_get_privatekey(tmp_ssl);
1883#endif
1884 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001885 goto mkcert_error;
1886
1887 /* Create the certificate */
1888 if (!(newcrt = X509_new()))
1889 goto mkcert_error;
1890
1891 /* Set version number for the certificate (X509v3) and the serial
1892 * number */
1893 if (X509_set_version(newcrt, 2L) != 1)
1894 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001895 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001896
1897 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001898 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1899 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001900 goto mkcert_error;
1901
1902 /* set public key in the certificate */
1903 if (X509_set_pubkey(newcrt, pkey) != 1)
1904 goto mkcert_error;
1905
1906 /* Set issuer name from the CA */
1907 if (!(name = X509_get_subject_name(cacert)))
1908 goto mkcert_error;
1909 if (X509_set_issuer_name(newcrt, name) != 1)
1910 goto mkcert_error;
1911
1912 /* Set the subject name using the same, but the CN */
1913 name = X509_NAME_dup(name);
1914 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1915 (const unsigned char *)servername,
1916 -1, -1, 0) != 1) {
1917 X509_NAME_free(name);
1918 goto mkcert_error;
1919 }
1920 if (X509_set_subject_name(newcrt, name) != 1) {
1921 X509_NAME_free(name);
1922 goto mkcert_error;
1923 }
1924 X509_NAME_free(name);
1925
1926 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001927 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001928 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1929 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1930 X509_EXTENSION *ext;
1931
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001932 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001933 goto mkcert_error;
1934 if (!X509_add_ext(newcrt, ext, -1)) {
1935 X509_EXTENSION_free(ext);
1936 goto mkcert_error;
1937 }
1938 X509_EXTENSION_free(ext);
1939 }
1940
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001941 /* Add SAN extension */
1942 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
1943 goto mkcert_error;
1944 }
1945
Christopher Faulet31af49d2015-06-09 17:29:50 +02001946 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001947
1948 key_type = EVP_PKEY_base_id(capkey);
1949
1950 if (key_type == EVP_PKEY_DSA)
1951 digest = EVP_sha1();
1952 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001953 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001954 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001955 digest = EVP_sha256();
1956 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05001957#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02001958 int nid;
1959
1960 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1961 goto mkcert_error;
1962 if (!(digest = EVP_get_digestbynid(nid)))
1963 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02001964#else
1965 goto mkcert_error;
1966#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02001967 }
1968
Christopher Faulet31af49d2015-06-09 17:29:50 +02001969 if (!(X509_sign(newcrt, capkey, digest)))
1970 goto mkcert_error;
1971
1972 /* Create and set the new SSL_CTX */
1973 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
1974 goto mkcert_error;
1975 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1976 goto mkcert_error;
1977 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
1978 goto mkcert_error;
1979 if (!SSL_CTX_check_private_key(ssl_ctx))
1980 goto mkcert_error;
1981
Shimi Gersner5846c492020-08-23 13:58:12 +03001982 /* Build chaining the CA cert and the rest of the chain, keep these order */
1983#if defined(SSL_CTX_add1_chain_cert)
1984 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
1985 goto mkcert_error;
1986 }
1987
1988 if (bind_conf->ca_sign_ckch->chain) {
1989 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
1990 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
1991 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
1992 goto mkcert_error;
1993 }
1994 }
1995 }
1996#endif
1997
Christopher Faulet31af49d2015-06-09 17:29:50 +02001998 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02001999
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002000#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002001 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002002#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002003#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2004 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002005 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002006 EC_KEY *ecc;
2007 int nid;
2008
2009 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2010 goto end;
2011 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2012 goto end;
2013 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2014 EC_KEY_free(ecc);
2015 }
2016#endif
2017 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002018 return ssl_ctx;
2019
2020 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002021 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002022 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002023 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2024 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002025 return NULL;
2026}
2027
Christopher Faulet7969a332015-10-09 11:15:03 +02002028SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002029ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02002030{
Willy Tarreau07d94e42018-09-20 10:57:52 +02002031 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01002032 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002033
Olivier Houchard66ab4982019-02-26 18:37:15 +01002034 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02002035}
2036
Christopher Faulet30548802015-06-11 13:39:32 +02002037/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002038 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002039SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002040ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002041{
2042 struct lru64 *lru = NULL;
2043
2044 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002045 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002046 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002047 if (lru && lru->domain) {
2048 if (ssl)
2049 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002050 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002051 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002052 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002053 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002054 }
2055 return NULL;
2056}
2057
Emeric Brun821bb9b2017-06-15 16:37:39 +02002058/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2059 * function is not thread-safe, it should only be used to check if a certificate
2060 * exists in the lru cache (with no warranty it will not be removed by another
2061 * thread). It is kept for backward compatibility. */
2062SSL_CTX *
2063ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2064{
2065 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2066}
2067
Christopher Fauletd2cab922015-07-28 16:03:47 +02002068/* Set a certificate int the LRU cache used to store generated
2069 * certificate. Return 0 on success, otherwise -1 */
2070int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002071ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002072{
2073 struct lru64 *lru = NULL;
2074
2075 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002076 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002077 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002078 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002079 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002080 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002081 }
Christopher Faulet30548802015-06-11 13:39:32 +02002082 if (lru->domain && lru->data)
2083 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002084 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002085 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002086 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002087 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002088 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002089}
2090
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002091/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002092unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002093ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002094{
2095 return XXH32(data, len, ssl_ctx_lru_seed);
2096}
2097
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002098/* Generate a cert and immediately assign it to the SSL session so that the cert's
2099 * refcount is maintained regardless of the cert's presence in the LRU cache.
2100 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002101static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002102ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002103{
Shimi Gersner5846c492020-08-23 13:58:12 +03002104 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002105 SSL_CTX *ssl_ctx = NULL;
2106 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002107 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002108
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002109 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002110 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002111 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002112 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002113 if (lru && lru->domain)
2114 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002115 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002116 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002117 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002118 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002119 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002120 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002121 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002122 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002123 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002124 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002125 SSL_set_SSL_CTX(ssl, ssl_ctx);
2126 /* No LRU cache, this CTX will be released as soon as the session dies */
2127 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002128 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002129 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002130 return 0;
2131}
2132static int
2133ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2134{
2135 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002136 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002137
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002138 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002139 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002140 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002141 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002142 }
2143 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002144}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002145#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002146
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002147#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002148
2149static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002150{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002151#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002152 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002153 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2154#endif
2155}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002156static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2157 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002158 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2159}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002160static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002161#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002162 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002163 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2164#endif
2165}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002166static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002167#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002168 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002169 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2170#endif
2171}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002172/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002173static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2174/* Unusable in this context. */
2175static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2176static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2177static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2178static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2179static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002180#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002181
2182static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2183 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002184 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2185}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002186static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2187 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2188 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2189}
2190static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2191 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002192 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2193}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002194static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2195 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2196 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2197}
2198static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2199 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002200 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2201}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002202static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2203 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2204 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2205}
2206static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2207 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002208 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2209}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002210static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2211 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2212 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2213}
2214static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002215#if SSL_OP_NO_TLSv1_3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002216 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002217 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2218#endif
2219}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002220static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
2221#if SSL_OP_NO_TLSv1_3
2222 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2223 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002224#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002225}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002226#endif
2227static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2228static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002229
William Lallemand7fd8b452020-05-07 15:20:43 +02002230struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002231 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2232 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2233 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2234 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2235 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2236 {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 +02002237};
2238
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002239static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2240{
2241 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2242 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2243 SSL_set_SSL_CTX(ssl, ctx);
2244}
2245
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002246#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002247
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002248int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002249{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002250 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002251 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002252
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002253 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2254 return SSL_TLSEXT_ERR_OK;
2255 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002256}
2257
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002258#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002259int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002260{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002261 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002262#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002263int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002264{
2265#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002266 struct connection *conn;
2267 struct bind_conf *s;
2268 const uint8_t *extension_data;
2269 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002270 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002271
2272 char *wildp = NULL;
2273 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002274 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002275 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002276 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002277 int i;
2278
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002279 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002280 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002281
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002282#ifdef USE_QUIC
2283 if (conn->qc) {
2284 /* Look for the QUIC transport parameters. */
2285#ifdef OPENSSL_IS_BORINGSSL
2286 if (!SSL_early_callback_ctx_extension_get(ctx, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2287 &extension_data, &extension_len))
2288#else
2289 if (!SSL_client_hello_get0_ext(ssl, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2290 &extension_data, &extension_len))
2291#endif
2292 goto abort;
2293
2294 if (!quic_transport_params_store(conn->qc, 0, extension_data,
2295 extension_data + extension_len))
2296 goto abort;
2297 }
2298#endif
2299
Olivier Houchard9679ac92017-10-27 14:58:08 +02002300 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002301 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002302#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002303 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2304 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002305#else
2306 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2307#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002308 /*
2309 * The server_name extension was given too much extensibility when it
2310 * was written, so parsing the normal case is a bit complex.
2311 */
2312 size_t len;
2313 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002314 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002315 /* Extract the length of the supplied list of names. */
2316 len = (*extension_data++) << 8;
2317 len |= *extension_data++;
2318 if (len + 2 != extension_len)
2319 goto abort;
2320 /*
2321 * The list in practice only has a single element, so we only consider
2322 * the first one.
2323 */
2324 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2325 goto abort;
2326 extension_len = len - 1;
2327 /* Now we can finally pull out the byte array with the actual hostname. */
2328 if (extension_len <= 2)
2329 goto abort;
2330 len = (*extension_data++) << 8;
2331 len |= *extension_data++;
2332 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2333 || memchr(extension_data, 0, len) != NULL)
2334 goto abort;
2335 servername = extension_data;
2336 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002337 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002338#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2339 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002340 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002341 }
2342#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002343 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002344 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002345 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002346 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002347 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002348 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002349 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002350 goto abort;
2351 }
2352
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002353 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002354#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002355 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002356#else
2357 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2358#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002359 uint8_t sign;
2360 size_t len;
2361 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002362 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002363 len = (*extension_data++) << 8;
2364 len |= *extension_data++;
2365 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002366 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002367 if (len % 2 != 0)
2368 goto abort;
2369 for (; len > 0; len -= 2) {
2370 extension_data++; /* hash */
2371 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002372 switch (sign) {
2373 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002374 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002375 break;
2376 case TLSEXT_signature_ecdsa:
2377 has_ecdsa_sig = 1;
2378 break;
2379 default:
2380 continue;
2381 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002382 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002383 break;
2384 }
2385 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002386 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002387 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002388 }
2389 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002390 const SSL_CIPHER *cipher;
2391 size_t len;
2392 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002393 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002394#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002395 len = ctx->cipher_suites_len;
2396 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002397#else
2398 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2399#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002400 if (len % 2 != 0)
2401 goto abort;
2402 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002403#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002404 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002405 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002406#else
2407 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2408#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002409 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002410 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002411 break;
2412 }
2413 }
2414 }
2415
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002416 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002417 trash.area[i] = tolower(servername[i]);
2418 if (!wildp && (trash.area[i] == '.'))
2419 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002420 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002421 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002422
William Lallemand150bfa82019-09-19 17:12:49 +02002423 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002424
William Lallemand94bd3192020-08-14 14:43:35 +02002425 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2426 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002427 for (i = 0; i < 2; i++) {
2428 if (i == 0) /* lookup in full qualified names */
2429 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002430 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002431 node = ebst_lookup(&s->sni_w_ctx, wildp);
2432 else
2433 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002434
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002435 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002436
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002437 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002438 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002439 struct sni_ctx *sni, *sni_tmp;
2440 int skip = 0;
2441
2442 if (i == 1 && wildp) { /* wildcard */
2443 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2444 sni = container_of(n, struct sni_ctx, name);
2445 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002446 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002447 skip = 1;
2448 break;
2449 }
2450 }
2451 if (skip)
2452 continue;
2453 }
2454
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002455 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002456 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002457 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002458 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002459 break;
2460 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002461 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002462 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002463 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002464 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002465 if (!node_anonymous)
2466 node_anonymous = n;
2467 break;
2468 }
2469 }
2470 }
William Lallemand94bd3192020-08-14 14:43:35 +02002471 }
2472 /* Once the certificates are found, select them depending on what is
2473 * supported in the client and by key_signature priority order: EDSA >
2474 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002475 if (has_ecdsa_sig && node_ecdsa)
2476 node = node_ecdsa;
2477 else if (has_rsa_sig && node_rsa)
2478 node = node_rsa;
2479 else if (node_anonymous)
2480 node = node_anonymous;
2481 else if (node_ecdsa)
2482 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2483 else
2484 node = node_rsa; /* no rsa signature case (far far away) */
2485
William Lallemand94bd3192020-08-14 14:43:35 +02002486 if (node) {
2487 /* switch ctx */
2488 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2489 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2490 if (conf) {
2491 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2492 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2493 if (conf->early_data)
2494 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002495 }
William Lallemand94bd3192020-08-14 14:43:35 +02002496 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2497 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002498 }
William Lallemand150bfa82019-09-19 17:12:49 +02002499
William Lallemand02010472019-10-18 11:02:19 +02002500 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002501#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002502 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002503 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002504 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002505 }
2506#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002507 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002508 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002509 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002510 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002511 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002512 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02002513allow_early:
2514#ifdef OPENSSL_IS_BORINGSSL
2515 if (allow_early)
2516 SSL_set_early_data_enabled(ssl, 1);
2517#else
2518 if (!allow_early)
2519 SSL_set_max_early_data(ssl, 0);
2520#endif
2521 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002522 abort:
2523 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2524 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002525#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002526 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002527#else
2528 *al = SSL_AD_UNRECOGNIZED_NAME;
2529 return 0;
2530#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002531}
2532
2533#else /* OPENSSL_IS_BORINGSSL */
2534
Emeric Brunfc0421f2012-09-07 17:30:07 +02002535/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2536 * warning when no match is found, which implies the default (first) cert
2537 * will keep being used.
2538 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002539static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002540{
2541 const char *servername;
2542 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002543 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002544 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002545 int i;
2546 (void)al; /* shut gcc stupid warning */
2547
2548 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002549 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002550#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002551 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2552 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002553#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002554 if (s->strict_sni)
2555 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002556 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002557 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002558 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002559 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002560 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002561
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002562 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002563 if (!servername[i])
2564 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002565 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002566 if (!wildp && (trash.area[i] == '.'))
2567 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002568 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002569 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002570
William Lallemand150bfa82019-09-19 17:12:49 +02002571 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002572 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002573 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002574 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2575 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002576 if (!container_of(n, struct sni_ctx, name)->neg) {
2577 node = n;
2578 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002579 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002580 }
2581 if (!node && wildp) {
2582 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002583 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2584 /* lookup a not neg filter */
2585 if (!container_of(n, struct sni_ctx, name)->neg) {
2586 node = n;
2587 break;
2588 }
2589 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002590 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002591 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002592#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002593 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2594 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002595 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002596 return SSL_TLSEXT_ERR_OK;
2597 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002598#endif
William Lallemand21724f02019-11-04 17:56:13 +01002599 if (s->strict_sni) {
2600 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002601 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002602 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002603 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002604 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002605 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002606 }
2607
2608 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002609 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002610 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002611 return SSL_TLSEXT_ERR_OK;
2612}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002613#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002614#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2615
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002616#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002617
2618static DH * ssl_get_dh_1024(void)
2619{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002620 static unsigned char dh1024_p[]={
2621 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2622 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2623 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2624 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2625 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2626 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2627 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2628 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2629 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2630 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2631 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2632 };
2633 static unsigned char dh1024_g[]={
2634 0x02,
2635 };
2636
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002637 BIGNUM *p;
2638 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002639 DH *dh = DH_new();
2640 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002641 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2642 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002643
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002644 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002645 DH_free(dh);
2646 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002647 } else {
2648 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002649 }
2650 }
2651 return dh;
2652}
2653
2654static DH *ssl_get_dh_2048(void)
2655{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002656 static unsigned char dh2048_p[]={
2657 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2658 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2659 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2660 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2661 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2662 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2663 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2664 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2665 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2666 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2667 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2668 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2669 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2670 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2671 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2672 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2673 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2674 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2675 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2676 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2677 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2678 0xB7,0x1F,0x77,0xF3,
2679 };
2680 static unsigned char dh2048_g[]={
2681 0x02,
2682 };
2683
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002684 BIGNUM *p;
2685 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002686 DH *dh = DH_new();
2687 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002688 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2689 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002690
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002691 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002692 DH_free(dh);
2693 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002694 } else {
2695 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002696 }
2697 }
2698 return dh;
2699}
2700
2701static DH *ssl_get_dh_4096(void)
2702{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002703 static unsigned char dh4096_p[]={
2704 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2705 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2706 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2707 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2708 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2709 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2710 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2711 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2712 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2713 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2714 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2715 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2716 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2717 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2718 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2719 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2720 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2721 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2722 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2723 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2724 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2725 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2726 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2727 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2728 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2729 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2730 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2731 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2732 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2733 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2734 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2735 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2736 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2737 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2738 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2739 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2740 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2741 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2742 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2743 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2744 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2745 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2746 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002747 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002748 static unsigned char dh4096_g[]={
2749 0x02,
2750 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002751
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002752 BIGNUM *p;
2753 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002754 DH *dh = DH_new();
2755 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002756 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2757 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002758
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002759 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002760 DH_free(dh);
2761 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002762 } else {
2763 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002764 }
2765 }
2766 return dh;
2767}
2768
2769/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002770 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002771static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2772{
2773 DH *dh = NULL;
2774 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002775 int type;
2776
2777 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002778
2779 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2780 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2781 */
2782 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2783 keylen = EVP_PKEY_bits(pkey);
2784 }
2785
Willy Tarreauef934602016-12-22 23:12:01 +01002786 if (keylen > global_ssl.default_dh_param) {
2787 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002788 }
2789
Remi Gacogned3a341a2015-05-29 16:26:17 +02002790 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002791 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002792 }
2793 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002794 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002795 }
2796 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002797 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002798 }
2799
2800 return dh;
2801}
2802
Remi Gacogne47783ef2015-05-29 15:53:22 +02002803static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002804{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002805 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002806 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002807
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002808 if (in == NULL)
2809 goto end;
2810
Remi Gacogne47783ef2015-05-29 15:53:22 +02002811 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002812 goto end;
2813
Remi Gacogne47783ef2015-05-29 15:53:22 +02002814 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2815
2816end:
2817 if (in)
2818 BIO_free(in);
2819
Emeric Brune1b4ed42018-08-16 15:14:12 +02002820 ERR_clear_error();
2821
Remi Gacogne47783ef2015-05-29 15:53:22 +02002822 return dh;
2823}
2824
2825int ssl_sock_load_global_dh_param_from_file(const char *filename)
2826{
2827 global_dh = ssl_sock_get_dh_from_file(filename);
2828
2829 if (global_dh) {
2830 return 0;
2831 }
2832
2833 return -1;
2834}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002835#endif
2836
William Lallemand9117de92019-10-04 00:29:42 +02002837/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002838static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002839 struct bind_conf *s, struct ssl_bind_conf *conf,
2840 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002841{
2842 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002843 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002844
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002845 if (*name == '!') {
2846 neg = 1;
2847 name++;
2848 }
2849 if (*name == '*') {
2850 wild = 1;
2851 name++;
2852 }
2853 /* !* filter is a nop */
2854 if (neg && wild)
2855 return order;
2856 if (*name) {
2857 int j, len;
2858 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002859 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02002860 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002861 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002862 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002863 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002864
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002865 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002866 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002867 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002868 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002869 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002870 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002871 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002872 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002873 sc->order = order++;
2874 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002875 sc->wild = wild;
2876 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002877 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02002878 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002879 }
2880 return order;
2881}
2882
William Lallemand6af03992019-07-23 15:00:54 +02002883/*
William Lallemand1d29c742019-10-04 00:53:29 +02002884 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2885 * This function can't return an error.
2886 *
2887 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2888 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002889void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002890{
2891
2892 struct sni_ctx *sc0, *sc0b, *sc1;
2893 struct ebmb_node *node;
2894
2895 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2896
2897 /* ignore if sc0 was already inserted in a tree */
2898 if (sc0->name.node.leaf_p)
2899 continue;
2900
2901 /* Check for duplicates. */
2902 if (sc0->wild)
2903 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2904 else
2905 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2906
2907 for (; node; node = ebmb_next_dup(node)) {
2908 sc1 = ebmb_entry(node, struct sni_ctx, name);
2909 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2910 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2911 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02002912 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002913 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002914 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02002915 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002916 }
2917 }
2918
2919 /* if duplicate, ignore the insertion */
2920 if (!sc0)
2921 continue;
2922
2923 if (sc0->wild)
2924 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
2925 else
2926 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01002927 }
William Lallemand21724f02019-11-04 17:56:13 +01002928
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01002929 /* replace the default_ctx if required with the instance's ctx. */
2930 if (ckch_inst->is_default) {
2931 SSL_CTX_free(bind_conf->default_ctx);
2932 SSL_CTX_up_ref(ckch_inst->ctx);
2933 bind_conf->default_ctx = ckch_inst->ctx;
William Lallemand1d29c742019-10-04 00:53:29 +02002934 }
2935}
2936
2937/*
William Lallemande3af8fb2019-10-08 11:36:53 +02002938 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02002939 */
William Lallemande3af8fb2019-10-08 11:36:53 +02002940struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02002941
William Lallemand2954c472020-03-06 21:54:13 +01002942/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02002943struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02002944
Emeric Brun7a883362019-10-17 13:27:40 +02002945/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002946 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02002947 * DH parameter is loaded into the SSL_CTX and if there is no
2948 * DH parameter available in ckchs nor in global, the default
2949 * DH parameters are applied on the SSL_CTX.
2950 * Returns a bitfield containing the flags:
2951 * ERR_FATAL in any fatal error case
2952 * ERR_ALERT if a reason of the error is availabine in err
2953 * ERR_WARN if a warning is available into err
2954 * The value 0 means there is no error nor warning and
2955 * the operation succeed.
2956 */
William Lallemandfa892222019-07-23 16:06:08 +02002957#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02002958static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
2959 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02002960{
Emeric Brun7a883362019-10-17 13:27:40 +02002961 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02002962 DH *dh = NULL;
2963
William Lallemanda8c73742019-07-31 18:31:34 +02002964 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02002965 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02002966 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
2967 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
2968 err && *err ? *err : "", path);
2969#if defined(SSL_CTX_set_dh_auto)
2970 SSL_CTX_set_dh_auto(ctx, 1);
2971 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2972 err && *err ? *err : "");
2973#else
2974 memprintf(err, "%s, DH ciphers won't be available.\n",
2975 err && *err ? *err : "");
2976#endif
2977 ret |= ERR_WARN;
2978 goto end;
2979 }
William Lallemandfa892222019-07-23 16:06:08 +02002980
2981 if (ssl_dh_ptr_index >= 0) {
2982 /* store a pointer to the DH params to avoid complaining about
2983 ssl-default-dh-param not being set for this SSL_CTX */
2984 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
2985 }
2986 }
2987 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02002988 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
2989 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
2990 err && *err ? *err : "", path);
2991#if defined(SSL_CTX_set_dh_auto)
2992 SSL_CTX_set_dh_auto(ctx, 1);
2993 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2994 err && *err ? *err : "");
2995#else
2996 memprintf(err, "%s, DH ciphers won't be available.\n",
2997 err && *err ? *err : "");
2998#endif
2999 ret |= ERR_WARN;
3000 goto end;
3001 }
William Lallemandfa892222019-07-23 16:06:08 +02003002 }
3003 else {
3004 /* Clear openssl global errors stack */
3005 ERR_clear_error();
3006
Willy Tarreau6d27a922020-11-05 19:38:05 +01003007 if (global_ssl.default_dh_param && global_ssl.default_dh_param <= 1024) {
William Lallemandfa892222019-07-23 16:06:08 +02003008 /* we are limited to DH parameter of 1024 bits anyway */
3009 if (local_dh_1024 == NULL)
3010 local_dh_1024 = ssl_get_dh_1024();
3011
Emeric Brun7a883362019-10-17 13:27:40 +02003012 if (local_dh_1024 == NULL) {
3013 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3014 err && *err ? *err : "", path);
3015 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02003016 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02003017 }
William Lallemandfa892222019-07-23 16:06:08 +02003018
Emeric Bruna9363eb2019-10-17 14:53:03 +02003019 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
3020 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3021 err && *err ? *err : "", path);
3022#if defined(SSL_CTX_set_dh_auto)
3023 SSL_CTX_set_dh_auto(ctx, 1);
3024 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3025 err && *err ? *err : "");
3026#else
3027 memprintf(err, "%s, DH ciphers won't be available.\n",
3028 err && *err ? *err : "");
3029#endif
3030 ret |= ERR_WARN;
3031 goto end;
3032 }
William Lallemandfa892222019-07-23 16:06:08 +02003033 }
3034 else {
3035 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
3036 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003037 }
3038
William Lallemandf9568fc2019-10-16 18:27:58 +02003039end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003040 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003041 return ret;
3042}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003043#endif
William Lallemandfa892222019-07-23 16:06:08 +02003044
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003045
3046/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003047 * Returns a bitfield containing the flags:
3048 * ERR_FATAL in any fatal error case
3049 * ERR_ALERT if the reason of the error is available in err
3050 * ERR_WARN if a warning is available into err
3051 * The value 0 means there is no error nor warning and
3052 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003053 */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003054static int ssl_sock_load_cert_chain(const char *path, const struct cert_key_and_chain *ckch,
3055 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003056{
Emeric Bruna96b5822019-10-17 13:25:14 +02003057 int errcode = 0;
3058
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003059 if (find_chain == NULL) {
3060 errcode |= ERR_FATAL;
3061 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003062 }
3063
3064 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3065 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3066 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003067 errcode |= ERR_ALERT | ERR_FATAL;
3068 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003069 }
3070
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003071 if (ckch->chain) {
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003072 *find_chain = ckch->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003073 } else {
3074 /* Find Certificate Chain in global */
3075 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003076 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003077 if (issuer)
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003078 *find_chain = issuer->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003079 }
William Lallemand85888572020-02-27 14:48:35 +01003080
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003081 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003082 /* always put a null chain stack in the SSL_CTX so it does not
3083 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003084 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003085 }
3086
William Lallemandf187ce62020-06-02 18:27:20 +02003087 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003088#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003089 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand935d8292020-08-12 20:02:10 +02003090 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3091 err && *err ? *err : "", path);
3092 errcode |= ERR_ALERT | ERR_FATAL;
3093 goto end;
3094 }
William Lallemandf187ce62020-06-02 18:27:20 +02003095#else
3096 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003097 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02003098 STACK_OF(X509) *chain;
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003099 chain = X509_chain_up_ref(*find_chain);
William Lallemandf187ce62020-06-02 18:27:20 +02003100 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003101 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003102 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3103 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003104 X509_free(ca);
3105 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003106 errcode |= ERR_ALERT | ERR_FATAL;
3107 goto end;
3108 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003109 }
William Lallemandf187ce62020-06-02 18:27:20 +02003110#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003111
William Lallemand9a1d8392020-08-10 17:28:23 +02003112#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003113 /* remove the Root CA from the SSL_CTX if the option is activated */
3114 if (global_ssl.skip_self_issued_ca) {
3115 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3116 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3117 err && *err ? *err : "", path);
3118 errcode |= ERR_ALERT | ERR_FATAL;
3119 goto end;
3120 }
3121 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003122#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003123
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003124end:
3125 return errcode;
3126}
3127
3128
3129/* Loads the info in ckch into ctx
3130 * Returns a bitfield containing the flags:
3131 * ERR_FATAL in any fatal error case
3132 * ERR_ALERT if the reason of the error is available in err
3133 * ERR_WARN if a warning is available into err
3134 * The value 0 means there is no error nor warning and
3135 * the operation succeed.
3136 */
3137static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3138{
3139 int errcode = 0;
3140 STACK_OF(X509) *find_chain = NULL;
3141
3142 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3143 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3144 err && *err ? *err : "", path);
3145 errcode |= ERR_ALERT | ERR_FATAL;
3146 return errcode;
3147 }
3148
3149 /* Load certificate chain */
3150 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3151 if (errcode & ERR_CODE)
3152 goto end;
3153
William Lallemandfa892222019-07-23 16:06:08 +02003154#ifndef OPENSSL_NO_DH
3155 /* store a NULL pointer to indicate we have not yet loaded
3156 a custom DH param file */
3157 if (ssl_dh_ptr_index >= 0) {
3158 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3159 }
3160
Emeric Brun7a883362019-10-17 13:27:40 +02003161 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3162 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003163 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3164 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003165 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003166 }
3167#endif
3168
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003169#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003170 if (sctl_ex_index >= 0 && ckch->sctl) {
3171 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3172 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003173 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003174 errcode |= ERR_ALERT | ERR_FATAL;
3175 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003176 }
3177 }
3178#endif
3179
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003180#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003181 /* Load OCSP Info into context */
3182 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003183 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003184 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",
3185 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003186 errcode |= ERR_ALERT | ERR_FATAL;
3187 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003188 }
3189 }
William Lallemand246c0242019-10-11 08:59:13 +02003190#endif
3191
Emeric Bruna96b5822019-10-17 13:25:14 +02003192 end:
3193 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003194}
3195
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003196
3197/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3198 * Returns a bitfield containing the flags:
3199 * ERR_FATAL in any fatal error case
3200 * ERR_ALERT if the reason of the error is available in err
3201 * ERR_WARN if a warning is available into err
3202 * The value 0 means there is no error nor warning and
3203 * the operation succeed.
3204 */
3205static int ssl_sock_put_srv_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch,
3206 SSL_CTX *ctx, char **err)
3207{
3208 int errcode = 0;
3209 STACK_OF(X509) *find_chain = NULL;
3210
3211 /* Load the private key */
3212 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3213 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3214 err && *err ? *err : "", path);
3215 errcode |= ERR_ALERT | ERR_FATAL;
3216 }
3217
3218 /* Load certificate chain */
3219 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3220 if (errcode & ERR_CODE)
3221 goto end;
3222
3223 if (SSL_CTX_check_private_key(ctx) <= 0) {
3224 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3225 err && *err ? *err : "", path);
3226 errcode |= ERR_ALERT | ERR_FATAL;
3227 }
3228
3229end:
3230 return errcode;
3231}
3232
3233
William Lallemand614ca0d2019-10-07 13:52:11 +02003234/*
3235 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003236 *
3237 * Returns a bitfield containing the flags:
3238 * ERR_FATAL in any fatal error case
3239 * ERR_ALERT if the reason of the error is available in err
3240 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003241 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003242int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003243 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003244{
William Lallemandc9402072019-05-15 15:33:54 +02003245 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003246 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003247 int order = 0;
3248 X509_NAME *xname;
3249 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003250 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003251 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003252#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3253 STACK_OF(GENERAL_NAME) *names;
3254#endif
William Lallemand36b84632019-07-18 19:28:17 +02003255 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003256 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003257 int errcode = 0;
3258
3259 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003260
William Lallemande3af8fb2019-10-08 11:36:53 +02003261 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003262 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003263
William Lallemande3af8fb2019-10-08 11:36:53 +02003264 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003265
William Lallemandc9402072019-05-15 15:33:54 +02003266 ctx = SSL_CTX_new(SSLv23_server_method());
3267 if (!ctx) {
3268 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3269 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003270 errcode |= ERR_ALERT | ERR_FATAL;
3271 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003272 }
3273
Emeric Bruna96b5822019-10-17 13:25:14 +02003274 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3275 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003276 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003277
3278 ckch_inst = ckch_inst_new();
3279 if (!ckch_inst) {
3280 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3281 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003282 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003283 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003284 }
3285
William Lallemand36b84632019-07-18 19:28:17 +02003286 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003287 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003288 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003289 switch(EVP_PKEY_base_id(pkey)) {
3290 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003291 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003292 break;
3293 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003294 kinfo.sig = TLSEXT_signature_ecdsa;
3295 break;
3296 case EVP_PKEY_DSA:
3297 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003298 break;
3299 }
3300 EVP_PKEY_free(pkey);
3301 }
3302
Emeric Brun50bcecc2013-04-22 13:05:23 +02003303 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003304 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003305 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 +02003306 if (order < 0) {
3307 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003308 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003309 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003310 }
3311 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003312 }
3313 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003314#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003315 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003316 if (names) {
3317 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3318 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3319 if (name->type == GEN_DNS) {
3320 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003321 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003322 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003323 if (order < 0) {
3324 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003325 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003326 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003327 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003328 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003329 }
3330 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003331 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003332 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003333#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003334 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003335 i = -1;
3336 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3337 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003338 ASN1_STRING *value;
3339
3340 value = X509_NAME_ENTRY_get_data(entry);
3341 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003342 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003343 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003344 if (order < 0) {
3345 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003346 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003347 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003348 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003349 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003350 }
3351 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003352 /* we must not free the SSL_CTX anymore below, since it's already in
3353 * the tree, so it will be discovered and cleaned in time.
3354 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003355
Emeric Brunfc0421f2012-09-07 17:30:07 +02003356#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003357 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003358 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3359 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003360 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003361 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003362 }
3363#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003364 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003365 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003366 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003367 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003368 SSL_CTX_up_ref(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003369 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003370
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003371 /* Always keep a reference to the newly constructed SSL_CTX in the
3372 * instance. This way if the instance has no SNIs, the SSL_CTX will
3373 * still be linked. */
3374 SSL_CTX_up_ref(ctx);
3375 ckch_inst->ctx = ctx;
3376
William Lallemand9117de92019-10-04 00:29:42 +02003377 /* everything succeed, the ckch instance can be used */
3378 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003379 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003380 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003381
William Lallemand02e19a52020-04-08 16:11:26 +02003382 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3383
Emeric Brun054563d2019-10-17 13:16:58 +02003384 *ckchi = ckch_inst;
3385 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003386
3387error:
3388 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003389 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003390 if (ckch_inst->is_default)
3391 SSL_CTX_free(ctx);
3392
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003393 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003394 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003395 }
William Lallemandd9199372019-10-04 15:37:05 +02003396 SSL_CTX_free(ctx);
3397
Emeric Brun054563d2019-10-17 13:16:58 +02003398 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003399}
3400
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003401
3402/*
3403 * This function allocate a ckch_inst that will be used on the backend side
3404 * (server line)
3405 *
3406 * Returns a bitfield containing the flags:
3407 * ERR_FATAL in any fatal error case
3408 * ERR_ALERT if the reason of the error is available in err
3409 * ERR_WARN if a warning is available into err
3410 */
3411int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003412 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003413{
3414 SSL_CTX *ctx;
3415 struct cert_key_and_chain *ckch;
3416 struct ckch_inst *ckch_inst = NULL;
3417 int errcode = 0;
3418
3419 *ckchi = NULL;
3420
3421 if (!ckchs || !ckchs->ckch)
3422 return ERR_FATAL;
3423
3424 ckch = ckchs->ckch;
3425
3426 ctx = SSL_CTX_new(SSLv23_client_method());
3427 if (!ctx) {
3428 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3429 err && *err ? *err : "", path);
3430 errcode |= ERR_ALERT | ERR_FATAL;
3431 goto error;
3432 }
3433
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003434 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, ckch, ctx, err);
3435 if (errcode & ERR_CODE)
3436 goto error;
3437
3438 ckch_inst = ckch_inst_new();
3439 if (!ckch_inst) {
3440 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3441 err && *err ? *err : "", path);
3442 errcode |= ERR_ALERT | ERR_FATAL;
3443 goto error;
3444 }
3445
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003446 /* everything succeed, the ckch instance can be used */
3447 ckch_inst->bind_conf = NULL;
3448 ckch_inst->ssl_conf = NULL;
3449 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003450 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003451 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003452
3453 *ckchi = ckch_inst;
3454 return errcode;
3455
3456error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003457 SSL_CTX_free(ctx);
3458
3459 return errcode;
3460}
3461
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003462/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003463static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3464 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003465 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003466{
Emeric Brun054563d2019-10-17 13:16:58 +02003467 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003468
3469 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003470 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 +02003471
Emeric Brun054563d2019-10-17 13:16:58 +02003472 if (errcode & ERR_CODE)
3473 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003474
William Lallemand24bde432020-03-09 16:48:43 +01003475 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003476
3477 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003478 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003479 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003480}
3481
William Lallemanddb26e2b2021-01-26 12:01:46 +01003482/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3483 * fill the SSL_CTX of the server.
3484 *
3485 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003486static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003487 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003488{
3489 int errcode = 0;
3490
3491 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003492 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003493
3494 if (errcode & ERR_CODE)
3495 return errcode;
3496
William Lallemanddb26e2b2021-01-26 12:01:46 +01003497 (*ckch_inst)->server = server;
3498 /* Keep the reference to the SSL_CTX in the server. */
3499 SSL_CTX_up_ref((*ckch_inst)->ctx);
3500 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003501 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003502 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003503 return errcode;
3504}
3505
William Lallemand6be66ec2020-03-06 22:26:32 +01003506
William Lallemand4c68bba2020-03-30 18:45:10 +02003507
3508
3509/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3510 * done once. Zero is returned if the operation fails. No error is returned
3511 * if the random is said as not implemented, because we expect that openssl
3512 * will use another method once needed.
3513 */
3514static int ssl_initialize_random()
3515{
3516 unsigned char random;
3517 static int random_initialized = 0;
3518
3519 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3520 random_initialized = 1;
3521
3522 return random_initialized;
3523}
3524
William Lallemand2954c472020-03-06 21:54:13 +01003525/* Load a crt-list file, this is done in 2 parts:
3526 * - store the content of the file in a crtlist structure with crtlist_entry structures
3527 * - generate the instances by iterating on entries in the crtlist struct
3528 *
3529 * Nothing is locked there, this function is used in the configuration parser.
3530 *
3531 * Returns a set of ERR_* flags possibly with an error in <err>.
3532 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003533int 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 +01003534{
3535 struct crtlist *crtlist = NULL;
3536 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003537 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003538 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003539 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003540 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003541
William Lallemand79d31ec2020-03-25 15:10:49 +01003542 bind_conf_node = malloc(sizeof(*bind_conf_node));
3543 if (!bind_conf_node) {
3544 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3545 cfgerr |= ERR_FATAL | ERR_ALERT;
3546 goto error;
3547 }
3548 bind_conf_node->next = NULL;
3549 bind_conf_node->bind_conf = bind_conf;
3550
William Lallemand41ca9302020-04-08 13:15:18 +02003551 /* strip trailing slashes, including first one */
3552 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3553 *end = 0;
3554
William Lallemand2954c472020-03-06 21:54:13 +01003555 /* look for an existing crtlist or create one */
3556 eb = ebst_lookup(&crtlists_tree, file);
3557 if (eb) {
3558 crtlist = ebmb_entry(eb, struct crtlist, node);
3559 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003560 /* load a crt-list OR a directory */
3561 if (dir)
3562 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3563 else
3564 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3565
William Lallemand2954c472020-03-06 21:54:13 +01003566 if (!(cfgerr & ERR_CODE))
3567 ebst_insert(&crtlists_tree, &crtlist->node);
3568 }
3569
3570 if (cfgerr & ERR_CODE) {
3571 cfgerr |= ERR_FATAL | ERR_ALERT;
3572 goto error;
3573 }
3574
3575 /* generates ckch instance from the crtlist_entry */
3576 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3577 struct ckch_store *store;
3578 struct ckch_inst *ckch_inst = NULL;
3579
3580 store = entry->node.key;
3581 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3582 if (cfgerr & ERR_CODE) {
3583 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3584 goto error;
3585 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003586 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003587 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003588 }
William Lallemand2954c472020-03-06 21:54:13 +01003589
William Lallemand79d31ec2020-03-25 15:10:49 +01003590 /* add the bind_conf to the list */
3591 bind_conf_node->next = crtlist->bind_conf;
3592 crtlist->bind_conf = bind_conf_node;
3593
William Lallemand2954c472020-03-06 21:54:13 +01003594 return cfgerr;
3595error:
3596 {
William Lallemand49398312020-03-30 17:01:33 +02003597 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003598 struct ckch_inst *inst, *s_inst;
3599
William Lallemand49398312020-03-30 17:01:33 +02003600 lastentry = entry; /* which entry we tried to generate last */
3601 if (lastentry) {
3602 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3603 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3604 break;
3605
3606 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003607
William Lallemand49398312020-03-30 17:01:33 +02003608 /* this was not generated for this bind_conf, skip */
3609 if (inst->bind_conf != bind_conf)
3610 continue;
3611
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003612 /* free the sni_ctx and instance */
3613 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003614 }
William Lallemand2954c472020-03-06 21:54:13 +01003615 }
William Lallemand2954c472020-03-06 21:54:13 +01003616 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003617 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003618 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003619 return cfgerr;
3620}
3621
William Lallemand06b22a82020-03-16 14:45:55 +01003622/* Returns a set of ERR_* flags possibly with an error in <err>. */
3623int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3624{
3625 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003626 int cfgerr = 0;
3627 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003628 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003629 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003630
3631 if ((ckchs = ckchs_lookup(path))) {
3632 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003633 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3634 found++;
3635 } else if (stat(path, &buf) == 0) {
3636 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003637 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003638 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003639 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003640 cfgerr |= ERR_ALERT | ERR_FATAL;
3641 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003642 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003643 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003644 }
3645 } else {
3646 /* stat failed, could be a bundle */
3647 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003648 char fp[MAXPATHLEN+1] = {0};
3649 int n = 0;
3650
3651 /* Load all possible certs and keys in separate ckch_store */
3652 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3653 struct stat buf;
3654 int ret;
3655
3656 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3657 if (ret > sizeof(fp))
3658 continue;
3659
3660 if ((ckchs = ckchs_lookup(fp))) {
3661 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003662 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003663 } else {
3664 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003665 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003666 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003667 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003668 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003669 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3670 }
3671 }
3672 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003673#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3674 if (found) {
3675 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3676 err && *err ? *err : "", path);
3677 cfgerr |= ERR_ALERT | ERR_FATAL;
3678 }
3679#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003680 }
3681 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003682 if (!found) {
3683 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3684 err && *err ? *err : "", path, strerror(errno));
3685 cfgerr |= ERR_ALERT | ERR_FATAL;
3686 }
William Lallemand06b22a82020-03-16 14:45:55 +01003687
3688 return cfgerr;
3689}
3690
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003691
3692/* Create a full ssl context and ckch instance that will be used for a specific
3693 * backend server (server configuration line).
3694 * Returns a set of ERR_* flags possibly with an error in <err>.
3695 */
3696int ssl_sock_load_srv_cert(char *path, struct server *server, char **err)
3697{
3698 struct stat buf;
3699 int cfgerr = 0;
3700 struct ckch_store *ckchs;
3701 int found = 0; /* did we found a file to load ? */
3702
3703 if ((ckchs = ckchs_lookup(path))) {
3704 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01003705 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003706 found++;
3707 } else if (stat(path, &buf) == 0) {
3708 /* We do not manage directories on backend side. */
3709 if (S_ISDIR(buf.st_mode) == 0) {
3710 ++found;
3711 ckchs = ckchs_load_cert_file(path, err);
3712 if (!ckchs)
3713 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003714 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003715 }
3716 }
3717 if (!found) {
3718 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3719 err && *err ? *err : "", path, strerror(errno));
3720 cfgerr |= ERR_ALERT | ERR_FATAL;
3721 }
3722
3723 return cfgerr;
3724}
3725
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003726/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003727static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003728ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003729{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003730 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003731 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003732 SSL_OP_ALL | /* all known workarounds for bugs */
3733 SSL_OP_NO_SSLv2 |
3734 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003735 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003736 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003737 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003738 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003739 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003740 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003741 SSL_MODE_ENABLE_PARTIAL_WRITE |
3742 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003743 SSL_MODE_RELEASE_BUFFERS |
3744 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003745 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003746 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003747 int flags = MC_SSL_O_ALL;
3748 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003749 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003750
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003751 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003752 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003753
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003754 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003755 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3756 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3757 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003758 else
3759 flags = conf_ssl_methods->flags;
3760
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003761 min = conf_ssl_methods->min;
3762 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003763
3764 /* default minimum is TLSV12, */
3765 if (!min) {
3766 if (!max || (max >= default_min_ver)) {
3767 min = default_min_ver;
3768 } else {
3769 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). "
3770 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3771 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3772 min = max;
3773 }
3774 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003775 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003776 if (min)
3777 flags |= (methodVersions[min].flag - 1);
3778 if (max)
3779 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003780 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003781 min = max = CONF_TLSV_NONE;
3782 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003783 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003784 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003785 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003786 if (min) {
3787 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003788 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3789 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3790 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3791 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003792 hole = 0;
3793 }
3794 max = i;
3795 }
3796 else {
3797 min = max = i;
3798 }
3799 }
3800 else {
3801 if (min)
3802 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003803 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003804 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003805 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3806 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003807 cfgerr += 1;
3808 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003809 /* save real min/max in bind_conf */
3810 conf_ssl_methods->min = min;
3811 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003812
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003813#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003814 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003815 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003816 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003817 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003818 else
William Lallemandd0712f32020-06-11 17:34:00 +02003819 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
3820 /* clear every version flags in case SSL_CTX_new()
3821 * returns an SSL_CTX with disabled versions */
3822 SSL_CTX_clear_options(ctx, methodVersions[i].option);
3823
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003824 if (flags & methodVersions[i].flag)
3825 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02003826
3827 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003828#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003829 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003830 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3831 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003832#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003833
3834 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3835 options |= SSL_OP_NO_TICKET;
3836 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3837 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003838
3839#ifdef SSL_OP_NO_RENEGOTIATION
3840 options |= SSL_OP_NO_RENEGOTIATION;
3841#endif
3842
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003843 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003844
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05003845#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003846 if (global_ssl.async)
3847 mode |= SSL_MODE_ASYNC;
3848#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003849 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003850 if (global_ssl.life_time)
3851 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003852
3853#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3854#ifdef OPENSSL_IS_BORINGSSL
3855 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3856 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003857#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003858 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003859 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003860 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3861 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003862#else
3863 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003864#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003865 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003866#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003867 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003868}
3869
William Lallemand4f45bb92017-10-30 20:08:51 +01003870
3871static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3872{
3873 if (first == block) {
3874 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3875 if (first->len > 0)
3876 sh_ssl_sess_tree_delete(sh_ssl_sess);
3877 }
3878}
3879
3880/* return first block from sh_ssl_sess */
3881static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3882{
3883 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3884
3885}
3886
3887/* store a session into the cache
3888 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3889 * data: asn1 encoded session
3890 * data_len: asn1 encoded session length
3891 * Returns 1 id session was stored (else 0)
3892 */
3893static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3894{
3895 struct shared_block *first;
3896 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3897
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003898 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003899 if (!first) {
3900 /* Could not retrieve enough free blocks to store that session */
3901 return 0;
3902 }
3903
3904 /* STORE the key in the first elem */
3905 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3906 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3907 first->len = sizeof(struct sh_ssl_sess_hdr);
3908
3909 /* it returns the already existing node
3910 or current node if none, never returns null */
3911 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3912 if (oldsh_ssl_sess != sh_ssl_sess) {
3913 /* NOTE: Row couldn't be in use because we lock read & write function */
3914 /* release the reserved row */
3915 shctx_row_dec_hot(ssl_shctx, first);
3916 /* replace the previous session already in the tree */
3917 sh_ssl_sess = oldsh_ssl_sess;
3918 /* ignore the previous session data, only use the header */
3919 first = sh_ssl_sess_first_block(sh_ssl_sess);
3920 shctx_row_inc_hot(ssl_shctx, first);
3921 first->len = sizeof(struct sh_ssl_sess_hdr);
3922 }
3923
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003924 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01003925 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003926 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01003927 }
3928
3929 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003930
3931 return 1;
3932}
William Lallemanded0b5ad2017-10-30 19:36:36 +01003933
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003934/* SSL callback used when a new session is created while connecting to a server */
3935static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
3936{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02003937 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003938 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003939
Willy Tarreau07d94e42018-09-20 10:57:52 +02003940 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003941
William Lallemand3ce6eed2021-02-08 10:43:44 +01003942 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
3943 * one cache per thread, it only prevents to flush it from the CLI in
3944 * another thread */
3945
Olivier Houcharde6060c52017-11-16 17:42:52 +01003946 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
3947 int len;
3948 unsigned char *ptr;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003949
Olivier Houcharde6060c52017-11-16 17:42:52 +01003950 len = i2d_SSL_SESSION(sess, NULL);
William Lallemand3ce6eed2021-02-08 10:43:44 +01003951 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003952 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
3953 ptr = s->ssl_ctx.reused_sess[tid].ptr;
3954 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01003955 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
3956 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01003957 s->ssl_ctx.reused_sess[tid].allocated_size = len;
3958 }
3959 if (s->ssl_ctx.reused_sess[tid].ptr) {
3960 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
3961 &ptr);
3962 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01003963 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003964 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01003965 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003966 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01003967 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003968 }
3969
3970 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003971}
3972
Olivier Houcharde6060c52017-11-16 17:42:52 +01003973
William Lallemanded0b5ad2017-10-30 19:36:36 +01003974/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01003975int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003976{
3977 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
3978 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
3979 unsigned char *p;
3980 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02003981 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003982 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003983
3984 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003985 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02003986 * note: SSL_SESSION_set1_id is using
3987 * a memcpy so we need to use a different pointer
3988 * than sid_data or sid_ctx_data to avoid valgrind
3989 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01003990 */
3991
3992 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02003993
3994 /* copy value in an other buffer */
3995 memcpy(encid, sid_data, sid_length);
3996
3997 /* pad with 0 */
3998 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
3999 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4000
4001 /* force length to zero to avoid ASN1 encoding */
4002 SSL_SESSION_set1_id(sess, encid, 0);
4003
4004 /* force length to zero to avoid ASN1 encoding */
4005 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004006
4007 /* check if buffer is large enough for the ASN1 encoded session */
4008 data_len = i2d_SSL_SESSION(sess, NULL);
4009 if (data_len > SHSESS_MAX_DATA_LEN)
4010 goto err;
4011
4012 p = encsess;
4013
4014 /* process ASN1 session encoding before the lock */
4015 i2d_SSL_SESSION(sess, &p);
4016
William Lallemanded0b5ad2017-10-30 19:36:36 +01004017
William Lallemanda3c77cf2017-10-30 23:44:40 +01004018 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004019 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004020 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004021 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004022err:
4023 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004024 SSL_SESSION_set1_id(sess, encid, sid_length);
4025 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004026
4027 return 0; /* do not increment session reference count */
4028}
4029
4030/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004031SSL_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 +01004032{
William Lallemand4f45bb92017-10-30 20:08:51 +01004033 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004034 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4035 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004036 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004037 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004038
4039 global.shctx_lookups++;
4040
4041 /* allow the session to be freed automatically by openssl */
4042 *do_copy = 0;
4043
4044 /* tree key is zeros padded sessionid */
4045 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4046 memcpy(tmpkey, key, key_len);
4047 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4048 key = tmpkey;
4049 }
4050
4051 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004052 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004053
4054 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004055 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4056 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004057 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004058 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004059 global.shctx_misses++;
4060 return NULL;
4061 }
4062
William Lallemand4f45bb92017-10-30 20:08:51 +01004063 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4064 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004065
William Lallemand4f45bb92017-10-30 20:08:51 +01004066 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 +01004067
William Lallemanda3c77cf2017-10-30 23:44:40 +01004068 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004069
4070 /* decode ASN1 session */
4071 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004072 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004073 /* Reset session id and session id contenxt */
4074 if (sess) {
4075 SSL_SESSION_set1_id(sess, key, key_len);
4076 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4077 }
4078
4079 return sess;
4080}
4081
William Lallemand4f45bb92017-10-30 20:08:51 +01004082
William Lallemanded0b5ad2017-10-30 19:36:36 +01004083/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004084void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004085{
William Lallemand4f45bb92017-10-30 20:08:51 +01004086 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004087 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4088 unsigned int sid_length;
4089 const unsigned char *sid_data;
4090 (void)ctx;
4091
4092 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4093 /* tree key is zeros padded sessionid */
4094 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4095 memcpy(tmpkey, sid_data, sid_length);
4096 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4097 sid_data = tmpkey;
4098 }
4099
William Lallemanda3c77cf2017-10-30 23:44:40 +01004100 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004101
4102 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004103 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4104 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004105 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004106 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004107 }
4108
4109 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004110 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004111}
4112
4113/* Set session cache mode to server and disable openssl internal cache.
4114 * Set shared cache callbacks on an ssl context.
4115 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004116void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004117{
4118 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4119
4120 if (!ssl_shctx) {
4121 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4122 return;
4123 }
4124
4125 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4126 SSL_SESS_CACHE_NO_INTERNAL |
4127 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4128
4129 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004130 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4131 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4132 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004133}
William Lallemand7d42ef52020-07-06 11:41:30 +02004134
4135/*
4136 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4137 *
4138 * The format is:
4139 * * <Label> <space> <ClientRandom> <space> <Secret>
4140 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4141 */
4142
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05004143#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004144void SSL_CTX_keylog(const SSL *ssl, const char *line)
4145{
4146 struct ssl_keylog *keylog;
4147 char *lastarg = NULL;
4148 char *dst = NULL;
4149
4150 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4151 if (!keylog)
4152 return;
4153
4154 lastarg = strrchr(line, ' ');
4155 if (lastarg == NULL || ++lastarg == NULL)
4156 return;
4157
4158 dst = pool_alloc(pool_head_ssl_keylog_str);
4159 if (!dst)
4160 return;
4161
4162 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4163 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4164
4165 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4166 if (keylog->client_random)
4167 goto error;
4168 keylog->client_random = dst;
4169
4170 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4171 if (keylog->client_early_traffic_secret)
4172 goto error;
4173 keylog->client_early_traffic_secret = dst;
4174
4175 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4176 if(keylog->client_handshake_traffic_secret)
4177 goto error;
4178 keylog->client_handshake_traffic_secret = dst;
4179
4180 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4181 if (keylog->server_handshake_traffic_secret)
4182 goto error;
4183 keylog->server_handshake_traffic_secret = dst;
4184
4185 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4186 if (keylog->client_traffic_secret_0)
4187 goto error;
4188 keylog->client_traffic_secret_0 = dst;
4189
4190 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4191 if (keylog->server_traffic_secret_0)
4192 goto error;
4193 keylog->server_traffic_secret_0 = dst;
4194
4195 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4196 if (keylog->early_exporter_secret)
4197 goto error;
4198 keylog->early_exporter_secret = dst;
4199
4200 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4201 if (keylog->exporter_secret)
4202 goto error;
4203 keylog->exporter_secret = dst;
4204 } else {
4205 goto error;
4206 }
4207
4208 return;
4209
4210error:
4211 pool_free(pool_head_ssl_keylog_str, dst);
4212
4213 return;
4214}
4215#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004216
William Lallemand8b453912019-11-21 15:48:10 +01004217/*
4218 * This function applies the SSL configuration on a SSL_CTX
4219 * It returns an error code and fills the <err> buffer
4220 */
4221int 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 +01004222{
4223 struct proxy *curproxy = bind_conf->frontend;
4224 int cfgerr = 0;
4225 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004226 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004227 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004228#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004229 const char *conf_ciphersuites;
4230#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004231 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004232
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004233 if (ssl_conf) {
4234 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4235 int i, min, max;
4236 int flags = MC_SSL_O_ALL;
4237
4238 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004239 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4240 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004241 if (min)
4242 flags |= (methodVersions[min].flag - 1);
4243 if (max)
4244 flags |= ~((methodVersions[max].flag << 1) - 1);
4245 min = max = CONF_TLSV_NONE;
4246 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4247 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4248 if (min)
4249 max = i;
4250 else
4251 min = max = i;
4252 }
4253 /* save real min/max */
4254 conf_ssl_methods->min = min;
4255 conf_ssl_methods->max = max;
4256 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004257 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4258 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004259 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004260 }
4261 }
4262
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004263 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004264 case SSL_SOCK_VERIFY_NONE:
4265 verify = SSL_VERIFY_NONE;
4266 break;
4267 case SSL_SOCK_VERIFY_OPTIONAL:
4268 verify = SSL_VERIFY_PEER;
4269 break;
4270 case SSL_SOCK_VERIFY_REQUIRED:
4271 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4272 break;
4273 }
4274 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4275 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004276 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 +01004277 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 +01004278 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 +01004279 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004280 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004281 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004282 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004283 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004284 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004285 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004286 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4287 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4288 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4289 cfgerr |= ERR_ALERT | ERR_FATAL;
4290 }
4291 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004292 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004293 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 +02004294 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004295 }
Emeric Brun850efd52014-01-29 12:24:34 +01004296 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004297 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4298 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004299 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004300 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004301#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004302 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004303 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4304
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004305 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004306 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4307 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004308 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004309 }
Emeric Brun561e5742012-10-02 15:20:55 +02004310 else {
4311 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4312 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004313 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004314#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004315 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004316 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004317#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004318 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004319 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004320 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4321 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004322 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004323 }
4324 }
4325#endif
4326
William Lallemand4f45bb92017-10-30 20:08:51 +01004327 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004328 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4329 if (conf_ciphers &&
4330 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004331 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4332 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004333 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004334 }
4335
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004336#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004337 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4338 if (conf_ciphersuites &&
4339 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004340 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4341 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004342 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004343 }
4344#endif
4345
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004346#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004347 /* If tune.ssl.default-dh-param has not been set,
4348 neither has ssl-default-dh-file and no static DH
4349 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004350 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004351 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004352 (ssl_dh_ptr_index == -1 ||
4353 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004354 /* default to dh-param 2048 */
4355 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004356 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004357
Willy Tarreauef934602016-12-22 23:12:01 +01004358 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004359 if (local_dh_1024 == NULL) {
4360 local_dh_1024 = ssl_get_dh_1024();
4361 }
Willy Tarreauef934602016-12-22 23:12:01 +01004362 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004363 if (local_dh_2048 == NULL) {
4364 local_dh_2048 = ssl_get_dh_2048();
4365 }
Willy Tarreauef934602016-12-22 23:12:01 +01004366 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004367 if (local_dh_4096 == NULL) {
4368 local_dh_4096 = ssl_get_dh_4096();
4369 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004370 }
4371 }
4372 }
4373#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004374
Emeric Brunfc0421f2012-09-07 17:30:07 +02004375 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004376#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004377 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004378#endif
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05004379#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004380 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
4381#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004382
Bernard Spil13c53f82018-02-15 13:34:58 +01004383#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004384 ssl_conf_cur = NULL;
4385 if (ssl_conf && ssl_conf->npn_str)
4386 ssl_conf_cur = ssl_conf;
4387 else if (bind_conf->ssl_conf.npn_str)
4388 ssl_conf_cur = &bind_conf->ssl_conf;
4389 if (ssl_conf_cur)
4390 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004391#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004392#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004393 ssl_conf_cur = NULL;
4394 if (ssl_conf && ssl_conf->alpn_str)
4395 ssl_conf_cur = ssl_conf;
4396 else if (bind_conf->ssl_conf.alpn_str)
4397 ssl_conf_cur = &bind_conf->ssl_conf;
4398 if (ssl_conf_cur)
4399 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004400#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004401#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004402 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4403 if (conf_curves) {
4404 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004405 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4406 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004407 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004408 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004409 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004410 }
4411#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004412#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004413 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004414 int i;
4415 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004416#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004417 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004418 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4419 NULL);
4420
4421 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004422 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004423 return cfgerr;
4424 }
4425#else
4426 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4427 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4428 ECDHE_DEFAULT_CURVE);
4429#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004430
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004431 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004432 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004433 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4434 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004435 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004436 }
4437 else {
4438 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4439 EC_KEY_free(ecdh);
4440 }
4441 }
4442#endif
4443
Emeric Brunfc0421f2012-09-07 17:30:07 +02004444 return cfgerr;
4445}
4446
Evan Broderbe554312013-06-27 00:05:25 -07004447static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4448{
4449 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4450 size_t prefixlen, suffixlen;
4451
4452 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004453 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004454 return 1;
4455
Evan Broderbe554312013-06-27 00:05:25 -07004456 /* The rest of this logic is based on RFC 6125, section 6.4.3
4457 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4458
Emeric Bruna848dae2013-10-08 11:27:28 +02004459 pattern_wildcard = NULL;
4460 pattern_left_label_end = pattern;
4461 while (*pattern_left_label_end != '.') {
4462 switch (*pattern_left_label_end) {
4463 case 0:
4464 /* End of label not found */
4465 return 0;
4466 case '*':
4467 /* If there is more than one wildcards */
4468 if (pattern_wildcard)
4469 return 0;
4470 pattern_wildcard = pattern_left_label_end;
4471 break;
4472 }
4473 pattern_left_label_end++;
4474 }
4475
4476 /* If it's not trivial and there is no wildcard, it can't
4477 * match */
4478 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004479 return 0;
4480
4481 /* Make sure all labels match except the leftmost */
4482 hostname_left_label_end = strchr(hostname, '.');
4483 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004484 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004485 return 0;
4486
4487 /* Make sure the leftmost label of the hostname is long enough
4488 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004489 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004490 return 0;
4491
4492 /* Finally compare the string on either side of the
4493 * wildcard */
4494 prefixlen = pattern_wildcard - pattern;
4495 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004496 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4497 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004498 return 0;
4499
4500 return 1;
4501}
4502
4503static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4504{
4505 SSL *ssl;
4506 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004507 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004508 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004509 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004510
4511 int depth;
4512 X509 *cert;
4513 STACK_OF(GENERAL_NAME) *alt_names;
4514 int i;
4515 X509_NAME *cert_subject;
4516 char *str;
4517
4518 if (ok == 0)
4519 return ok;
4520
4521 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004522 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004523 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004524
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004525 /* We're checking if the provided hostnames match the desired one. The
4526 * desired hostname comes from the SNI we presented if any, or if not
4527 * provided then it may have been explicitly stated using a "verifyhost"
4528 * directive. If neither is set, we don't care about the name so the
4529 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004530 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004531 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004532 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004533 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004534 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004535 if (!servername)
4536 return ok;
4537 }
Evan Broderbe554312013-06-27 00:05:25 -07004538
4539 /* We only need to verify the CN on the actual server cert,
4540 * not the indirect CAs */
4541 depth = X509_STORE_CTX_get_error_depth(ctx);
4542 if (depth != 0)
4543 return ok;
4544
4545 /* At this point, the cert is *not* OK unless we can find a
4546 * hostname match */
4547 ok = 0;
4548
4549 cert = X509_STORE_CTX_get_current_cert(ctx);
4550 /* It seems like this might happen if verify peer isn't set */
4551 if (!cert)
4552 return ok;
4553
4554 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4555 if (alt_names) {
4556 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4557 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4558 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004559#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004560 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4561#else
Evan Broderbe554312013-06-27 00:05:25 -07004562 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004563#endif
Evan Broderbe554312013-06-27 00:05:25 -07004564 ok = ssl_sock_srv_hostcheck(str, servername);
4565 OPENSSL_free(str);
4566 }
4567 }
4568 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004569 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004570 }
4571
4572 cert_subject = X509_get_subject_name(cert);
4573 i = -1;
4574 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4575 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004576 ASN1_STRING *value;
4577 value = X509_NAME_ENTRY_get_data(entry);
4578 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004579 ok = ssl_sock_srv_hostcheck(str, servername);
4580 OPENSSL_free(str);
4581 }
4582 }
4583
Willy Tarreau71d058c2017-07-26 20:09:56 +02004584 /* report the mismatch and indicate if SNI was used or not */
4585 if (!ok && !conn->err_code)
4586 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004587 return ok;
4588}
4589
Emeric Brun94324a42012-10-11 14:00:19 +02004590/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004591int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004592{
Willy Tarreau03209342016-12-22 17:08:28 +01004593 struct proxy *curproxy = srv->proxy;
Emeric Brun94324a42012-10-11 14:00:19 +02004594 int cfgerr = 0;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004595 SSL_CTX *ctx = srv->ssl_ctx.ctx;
Emeric Brun94324a42012-10-11 14:00:19 +02004596
Thierry Fournier383085f2013-01-24 14:15:43 +01004597 /* Make sure openssl opens /dev/urandom before the chroot */
4598 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004599 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004600 cfgerr++;
4601 }
4602
Willy Tarreaufce03112015-01-15 21:32:40 +01004603 /* Automatic memory computations need to know we use SSL there */
4604 global.ssl_used_backend = 1;
4605
4606 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004607 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004608 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004609 ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4610 curproxy->id, srv->id,
4611 srv->conf.file, srv->conf.line);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004612 cfgerr++;
4613 return cfgerr;
4614 }
4615 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004616 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004617 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004618
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004619 /* The context will be uninitialized if there wasn't any "cert" option
4620 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004621 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004622 ctx = SSL_CTX_new(SSLv23_client_method());
4623 if (!ctx) {
4624 ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4625 proxy_type_str(curproxy), curproxy->id,
4626 srv->id);
4627 cfgerr++;
4628 return cfgerr;
4629 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004630
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004631 srv->ssl_ctx.ctx = ctx;
4632 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004633
4634 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, srv->ssl_ctx.ctx);
4635
4636 return cfgerr;
4637}
4638
4639
4640/* Initialize an SSL context that will be used on the backend side.
4641 * Returns an error count.
4642 */
4643int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
4644{
4645 struct proxy *curproxy = srv->proxy;
4646 int cfgerr = 0;
4647 long options =
4648 SSL_OP_ALL | /* all known workarounds for bugs */
4649 SSL_OP_NO_SSLv2 |
4650 SSL_OP_NO_COMPRESSION;
4651 long mode =
4652 SSL_MODE_ENABLE_PARTIAL_WRITE |
4653 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4654 SSL_MODE_RELEASE_BUFFERS |
4655 SSL_MODE_SMALL_BUFFERS;
4656 int verify = SSL_VERIFY_NONE;
4657 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4658 int i, min, max, hole;
4659 int flags = MC_SSL_O_ALL;
4660
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004661 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004662 ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4663 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4664 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004665 else
4666 flags = conf_ssl_methods->flags;
4667
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004668 /* Real min and max should be determinate with configuration and openssl's capabilities */
4669 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004670 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004671 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004672 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004673
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004674 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004675 min = max = CONF_TLSV_NONE;
4676 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004677 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004678 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004679 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004680 if (min) {
4681 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004682 ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4683 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4684 proxy_type_str(curproxy), curproxy->id, srv->id,
4685 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004686 hole = 0;
4687 }
4688 max = i;
4689 }
4690 else {
4691 min = max = i;
4692 }
4693 }
4694 else {
4695 if (min)
4696 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004697 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004698 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004699 ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4700 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004701 cfgerr += 1;
4702 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004703
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004704#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004705 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004706 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004707 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004708 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004709 else
4710 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4711 if (flags & methodVersions[i].flag)
4712 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004713#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004714 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004715 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4716 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004717#endif
4718
4719 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4720 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004721 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004722
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004723#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004724 if (global_ssl.async)
4725 mode |= SSL_MODE_ASYNC;
4726#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004727 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004728
Emeric Brun850efd52014-01-29 12:24:34 +01004729 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4730 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004731 switch (srv->ssl_ctx.verify) {
4732 case SSL_SOCK_VERIFY_NONE:
4733 verify = SSL_VERIFY_NONE;
4734 break;
4735 case SSL_SOCK_VERIFY_REQUIRED:
4736 verify = SSL_VERIFY_PEER;
4737 break;
4738 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004739 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004740 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004741 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004742 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004743 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004744 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004745 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to set CA file '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004746 curproxy->id, srv->id,
4747 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004748 cfgerr++;
4749 }
4750 }
Emeric Brun850efd52014-01-29 12:24:34 +01004751 else {
4752 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Christopher Faulet767a84b2017-11-24 16:50:31 +01004753 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled by default but no CA file specified. If you're running on a LAN where you're certain to trust the server's certificate, please set an explicit 'verify none' statement on the 'server' line, or use 'ssl-server-verify none' in the global section to disable server-side verifications by default.\n",
4754 curproxy->id, srv->id,
4755 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004756 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01004757 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4758 curproxy->id, srv->id,
4759 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004760 cfgerr++;
4761 }
Emeric Brunef42d922012-10-11 16:11:36 +02004762#ifdef X509_V_FLAG_CRL_CHECK
4763 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004764 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02004765
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004766 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004767 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4768 curproxy->id, srv->id,
4769 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004770 cfgerr++;
4771 }
4772 else {
4773 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4774 }
4775 }
4776#endif
4777 }
4778
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004779 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
4780 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004781 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004782 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004783 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4784 curproxy->id, srv->id,
4785 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004786 cfgerr++;
4787 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004788
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004789#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004790 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004791 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004792 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4793 curproxy->id, srv->id,
4794 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4795 cfgerr++;
4796 }
4797#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004798#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4799 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004800 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01004801#endif
4802#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4803 if (srv->ssl_ctx.alpn_str)
4804 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4805#endif
4806
Emeric Brun94324a42012-10-11 14:00:19 +02004807
4808 return cfgerr;
4809}
4810
Frédéric Lécailleec216522020-11-23 14:33:30 +01004811/*
4812 * Create an initial CTX used to start the SSL connections.
4813 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
4814 * Returns 0 if succeeded, or something >0 if not.
4815 */
4816#ifdef USE_QUIC
4817static int ssl_initial_ctx(struct bind_conf *bind_conf)
4818{
4819 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
4820 return ssl_quic_initial_ctx(bind_conf);
4821 else
4822 return ssl_sock_initial_ctx(bind_conf);
4823}
4824#else
4825static int ssl_initial_ctx(struct bind_conf *bind_conf)
4826{
4827 return ssl_sock_initial_ctx(bind_conf);
4828}
4829#endif
4830
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004831/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004832 * be NULL, in which case nothing is done. Returns the number of errors
4833 * encountered.
4834 */
Willy Tarreau03209342016-12-22 17:08:28 +01004835int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004836{
4837 struct ebmb_node *node;
4838 struct sni_ctx *sni;
4839 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004840 int errcode = 0;
4841 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004842
Willy Tarreaufce03112015-01-15 21:32:40 +01004843 /* Automatic memory computations need to know we use SSL there */
4844 global.ssl_used_frontend = 1;
4845
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004846 /* Make sure openssl opens /dev/urandom before the chroot */
4847 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004848 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004849 err++;
4850 }
4851 /* Create initial_ctx used to start the ssl connection before do switchctx */
4852 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01004853 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004854 /* It should not be necessary to call this function, but it's
4855 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01004856 to initial_ctx in ssl_initial_ctx. */
William Lallemand8b453912019-11-21 15:48:10 +01004857 errcode |= ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004858 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004859 if (bind_conf->default_ctx)
William Lallemand8b453912019-11-21 15:48:10 +01004860 errcode |= ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, &errmsg);
Emeric Brun0bed9942014-10-30 19:25:24 +01004861
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004862 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004863 while (node) {
4864 sni = ebmb_entry(node, struct sni_ctx, name);
Emeric Brun0bed9942014-10-30 19:25:24 +01004865 if (!sni->order && sni->ctx != bind_conf->default_ctx)
4866 /* only initialize the CTX on its first occurrence and
4867 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004868 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004869 node = ebmb_next(node);
4870 }
4871
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004872 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004873 while (node) {
4874 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004875 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004876 /* only initialize the CTX on its first occurrence and
4877 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004878 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
4879 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004880 node = ebmb_next(node);
4881 }
William Lallemand8b453912019-11-21 15:48:10 +01004882
4883 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004884 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004885 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004886 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004887 err++;
4888 }
4889
4890 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004891 return err;
4892}
4893
Willy Tarreau55d37912016-12-21 23:38:39 +01004894/* Prepares all the contexts for a bind_conf and allocates the shared SSL
4895 * context if needed. Returns < 0 on error, 0 on success. The warnings and
4896 * alerts are directly emitted since the rest of the stack does it below.
4897 */
4898int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
4899{
4900 struct proxy *px = bind_conf->frontend;
4901 int alloc_ctx;
4902 int err;
4903
4904 if (!bind_conf->is_ssl) {
4905 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004906 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
4907 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01004908 }
4909 return 0;
4910 }
4911 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004912 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004913 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
4914 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004915 }
4916 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004917 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
4918 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004919 return -1;
4920 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004921 }
William Lallemandc61c0b32017-12-04 18:46:39 +01004922 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004923 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02004924 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01004925 sizeof(*sh_ssl_sess_tree),
4926 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02004927 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004928 if (alloc_ctx == SHCTX_E_INIT_LOCK)
4929 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");
4930 else
4931 ha_alert("Unable to allocate SSL session cache.\n");
4932 return -1;
4933 }
4934 /* free block callback */
4935 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
4936 /* init the root tree within the extra space */
4937 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
4938 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01004939 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004940 err = 0;
4941 /* initialize all certificate contexts */
4942 err += ssl_sock_prepare_all_ctx(bind_conf);
4943
4944 /* initialize CA variables if the certificates generation is enabled */
4945 err += ssl_sock_load_ca(bind_conf);
4946
4947 return -err;
4948}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004949
4950/* release ssl context allocated for servers. */
4951void ssl_sock_free_srv_ctx(struct server *srv)
4952{
Olivier Houchardc7566002018-11-20 23:33:50 +01004953#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4954 if (srv->ssl_ctx.alpn_str)
Willy Tarreaue709e822021-02-26 21:06:32 +01004955 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01004956#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01004957#ifdef OPENSSL_NPN_NEGOTIATED
Olivier Houchardc7566002018-11-20 23:33:50 +01004958 if (srv->ssl_ctx.npn_str)
Willy Tarreaue709e822021-02-26 21:06:32 +01004959 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01004960#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02004961 if (srv->ssl_ctx.reused_sess) {
4962 int i;
4963
4964 for (i = 0; i < global.nbthread; i++)
Willy Tarreaue709e822021-02-26 21:06:32 +01004965 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
4966 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02004967 }
4968
Willy Tarreaue709e822021-02-26 21:06:32 +01004969 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004970 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01004971 srv->ssl_ctx.ctx = NULL;
4972 }
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004973}
4974
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004975/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004976 * be NULL, in which case nothing is done. The default_ctx is nullified too.
4977 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004978void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004979{
4980 struct ebmb_node *node, *back;
4981 struct sni_ctx *sni;
4982
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004983 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004984 while (node) {
4985 sni = ebmb_entry(node, struct sni_ctx, name);
4986 back = ebmb_next(node);
4987 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004988 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02004989 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004990 free(sni);
4991 node = back;
4992 }
4993
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004994 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004995 while (node) {
4996 sni = ebmb_entry(node, struct sni_ctx, name);
4997 back = ebmb_next(node);
4998 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004999 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005000 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005001 free(sni);
5002 node = back;
5003 }
William Lallemandb2408692020-06-24 09:54:29 +02005004
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005005 SSL_CTX_free(bind_conf->initial_ctx);
5006 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005007 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005008 bind_conf->default_ctx = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005009 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005010}
William Lallemandb2408692020-06-24 09:54:29 +02005011
5012
5013void ssl_sock_deinit()
5014{
5015 crtlist_deinit(); /* must be free'd before the ckchs */
5016 ckch_deinit();
5017}
5018REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005019
Willy Tarreau795cdab2016-12-22 17:30:54 +01005020/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5021void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5022{
5023 ssl_sock_free_ca(bind_conf);
5024 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005025 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005026 free(bind_conf->ca_sign_file);
5027 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005028 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005029 free(bind_conf->keys_ref->filename);
5030 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005031 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005032 free(bind_conf->keys_ref);
5033 }
5034 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005035 bind_conf->ca_sign_pass = NULL;
5036 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005037}
5038
Christopher Faulet31af49d2015-06-09 17:29:50 +02005039/* Load CA cert file and private key used to generate certificates */
5040int
Willy Tarreau03209342016-12-22 17:08:28 +01005041ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005042{
Willy Tarreau03209342016-12-22 17:08:28 +01005043 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03005044 struct cert_key_and_chain *ckch = NULL;
5045 int ret = 0;
5046 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005047
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02005048 if (!bind_conf->generate_certs)
Shimi Gersner5846c492020-08-23 13:58:12 +03005049 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005050
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005051#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005052 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005053 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005054 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005055 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005056 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005057#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005058
Christopher Faulet31af49d2015-06-09 17:29:50 +02005059 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005060 ha_alert("Proxy '%s': cannot enable certificate generation, "
5061 "no CA certificate File configured at [%s:%d].\n",
5062 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005063 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005064 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005065
Shimi Gersner5846c492020-08-23 13:58:12 +03005066 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02005067 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03005068 if (!ckch) {
5069 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5070 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5071 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005072 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005073
5074 /* Try to parse file */
5075 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
5076 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5077 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005078 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005079 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005080 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005081
5082 /* Fail if missing cert or pkey */
5083 if ((!ckch->cert) || (!ckch->key)) {
5084 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5085 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5086 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005087 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005088
Shimi Gersner5846c492020-08-23 13:58:12 +03005089 /* Final assignment to bind */
5090 bind_conf->ca_sign_ckch = ckch;
5091 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005092
Shimi Gersner5846c492020-08-23 13:58:12 +03005093 failed:
5094 if (ckch) {
5095 ssl_sock_free_cert_key_and_chain_contents(ckch);
5096 free(ckch);
5097 }
5098
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005099 bind_conf->generate_certs = 0;
Shimi Gersner5846c492020-08-23 13:58:12 +03005100 ret++;
5101 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005102}
5103
5104/* Release CA cert and private key used to generate certificated */
5105void
5106ssl_sock_free_ca(struct bind_conf *bind_conf)
5107{
Shimi Gersner5846c492020-08-23 13:58:12 +03005108 if (bind_conf->ca_sign_ckch) {
5109 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005110 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005111 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005112}
5113
Emeric Brun46591952012-05-18 15:47:34 +02005114/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005115 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5116 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5117 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5118 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005119 * 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 +01005120 * as parameters to this function.
5121 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5122 * CO_ER_SSL_NO_MEM.
5123 */
5124int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5125 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5126{
5127 int retry = 1;
5128
5129 retry:
5130 /* Alloc a new SSL session. */
5131 *ssl = SSL_new(ssl_ctx);
5132 if (!*ssl) {
5133 if (!retry--)
5134 goto err;
5135
5136 pool_gc(NULL);
5137 goto retry;
5138 }
5139
5140 *bio = BIO_new(bio_meth);
5141 if (!*bio) {
5142 SSL_free(*ssl);
5143 *ssl = NULL;
5144 if (!retry--)
5145 goto err;
5146
5147 pool_gc(NULL);
5148 goto retry;
5149 }
5150
5151 BIO_set_data(*bio, ctx);
5152 SSL_set_bio(*ssl, *bio, *bio);
5153
5154 /* set connection pointer. */
5155 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5156 SSL_free(*ssl);
5157 *ssl = NULL;
5158 if (!retry--)
5159 goto err;
5160
5161 pool_gc(NULL);
5162 goto retry;
5163 }
5164
5165 return 0;
5166
5167 err:
5168 conn->err_code = CO_ER_SSL_NO_MEM;
5169 return -1;
5170}
5171
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005172/* This function is called when all the XPRT have been initialized. We can
5173 * now attempt to start the SSL handshake.
5174 */
5175static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5176{
5177 struct ssl_sock_ctx *ctx = xprt_ctx;
5178
5179 if (ctx->xprt->start) {
5180 int ret;
5181
5182 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5183 if (ret < 0)
5184 return ret;
5185 }
5186 tasklet_wakeup(ctx->wait_event.tasklet);
5187
5188 return 0;
5189}
5190
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005191/*
Emeric Brun46591952012-05-18 15:47:34 +02005192 * This function is called if SSL * context is not yet allocated. The function
5193 * is designed to be called before any other data-layer operation and sets the
5194 * handshake flag on the connection. It is safe to call it multiple times.
5195 * It returns 0 on success and -1 in error case.
5196 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005197static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005198{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005199 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005200 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005201 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005202 return 0;
5203
Olivier Houchard66ab4982019-02-26 18:37:15 +01005204 ctx = pool_alloc(ssl_sock_ctx_pool);
5205 if (!ctx) {
5206 conn->err_code = CO_ER_SSL_NO_MEM;
5207 return -1;
5208 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005209 ctx->wait_event.tasklet = tasklet_new();
5210 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005211 conn->err_code = CO_ER_SSL_NO_MEM;
5212 pool_free(ssl_sock_ctx_pool, ctx);
5213 return -1;
5214 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005215 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5216 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005217 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005218 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005219 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005220 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005221 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005222 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005223 ctx->xprt_st = 0;
5224 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005225
5226 /* Only work with sockets for now, this should be adapted when we'll
5227 * add QUIC support.
5228 */
5229 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005230 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005231 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5232 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005233 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005234
Willy Tarreau20879a02012-12-03 16:32:10 +01005235 if (global.maxsslconn && sslconns >= global.maxsslconn) {
5236 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005237 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005238 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005239
Emeric Brun46591952012-05-18 15:47:34 +02005240 /* If it is in client mode initiate SSL session
5241 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005242 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005243 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5244 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005245 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005246
Olivier Houchard66ab4982019-02-26 18:37:15 +01005247 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005248 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005249 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5250 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5251 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 +01005252 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005253 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005254 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005255 } else if (sess) {
5256 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005257 }
5258 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005259 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005260
Emeric Brun46591952012-05-18 15:47:34 +02005261 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005262 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005263
Willy Tarreau4781b152021-04-06 13:53:36 +02005264 _HA_ATOMIC_INC(&sslconns);
5265 _HA_ATOMIC_INC(&totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005266 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005267 return 0;
5268 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005269 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005270 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005271
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005272 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5273 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005274 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005275
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005276#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005277 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005278 b_alloc(&ctx->early_buf);
5279 SSL_set_max_early_data(ctx->ssl,
5280 /* Only allow early data if we managed to allocate
5281 * a buffer.
5282 */
5283 (!b_is_null(&ctx->early_buf)) ?
5284 global.tune.bufsize - global.tune.maxrewrite : 0);
5285 }
5286#endif
5287
Olivier Houchard66ab4982019-02-26 18:37:15 +01005288 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005289
Emeric Brun46591952012-05-18 15:47:34 +02005290 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005291 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005292#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005293 if (bc->ssl_conf.early_data)
5294 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005295#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005296
Willy Tarreau4781b152021-04-06 13:53:36 +02005297 _HA_ATOMIC_INC(&sslconns);
5298 _HA_ATOMIC_INC(&totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005299 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005300 return 0;
5301 }
5302 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005303 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005304err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005305 if (ctx && ctx->wait_event.tasklet)
5306 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005307 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005308 return -1;
5309}
5310
5311
5312/* This is the callback which is used when an SSL handshake is pending. It
5313 * updates the FD status if it wants some polling before being called again.
5314 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5315 * otherwise it returns non-zero and removes itself from the connection's
5316 * flags (the bit is provided in <flag> by the caller).
5317 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005318static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005319{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005320 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005321 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005322 struct ssl_counters *counters = NULL;
5323 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005324 struct listener *li;
5325 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005326 socklen_t lskerr;
5327 int skerr;
5328
Emeric Brun46591952012-05-18 15:47:34 +02005329
Willy Tarreau3c728722014-01-23 13:50:42 +01005330 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005331 return 0;
5332
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005333 /* get counters */
5334 switch (obj_type(conn->target)) {
5335 case OBJ_TYPE_LISTENER:
5336 li = objt_listener(conn->target);
5337 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5338 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5339 &ssl_stats_module);
5340 break;
5341
5342 case OBJ_TYPE_SERVER:
5343 srv = objt_server(conn->target);
5344 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5345 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5346 &ssl_stats_module);
5347 break;
5348
5349 default:
5350 break;
5351 }
5352
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005353 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005354 goto out_error;
5355
Willy Tarreau06300382021-02-02 15:42:25 +01005356 /* don't start calculating a handshake on a dead connection */
5357 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5358 goto out_error;
5359
5360 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5361 * status from the lower layers, so let's check the FD directly. Ideally
5362 * the xprt layers should provide some status indicating their knowledge
5363 * of shutdowns or error.
5364 */
5365 skerr = 0;
5366 lskerr = sizeof(skerr);
5367 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5368 skerr != 0)
5369 goto out_error;
5370
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005371#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005372 /*
5373 * Check if we have early data. If we do, we have to read them
5374 * before SSL_do_handshake() is called, And there's no way to
5375 * detect early data, except to try to read them
5376 */
5377 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005378 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005379
Olivier Houchard54907bb2019-12-19 15:02:39 +01005380 while (1) {
5381 ret = SSL_read_early_data(ctx->ssl,
5382 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5383 &read_data);
5384 if (ret == SSL_READ_EARLY_DATA_ERROR)
5385 goto check_error;
5386 if (read_data > 0) {
5387 conn->flags |= CO_FL_EARLY_DATA;
5388 b_add(&ctx->early_buf, read_data);
5389 }
5390 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5391 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5392 if (!b_data(&ctx->early_buf))
5393 b_free(&ctx->early_buf);
5394 break;
5395 }
5396 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005397 }
5398#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005399 /* If we use SSL_do_handshake to process a reneg initiated by
5400 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5401 * Usually SSL_write and SSL_read are used and process implicitly
5402 * the reneg handshake.
5403 * Here we use SSL_peek as a workaround for reneg.
5404 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005405 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005406 char c;
5407
Olivier Houchard66ab4982019-02-26 18:37:15 +01005408 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005409 if (ret <= 0) {
5410 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005411 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005412
Emeric Brun674b7432012-11-08 19:21:55 +01005413 if (ret == SSL_ERROR_WANT_WRITE) {
5414 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005415 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005416 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005417 return 0;
5418 }
5419 else if (ret == SSL_ERROR_WANT_READ) {
5420 /* handshake may have been completed but we have
5421 * no more data to read.
5422 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005423 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005424 ret = 1;
5425 goto reneg_ok;
5426 }
5427 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005428 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005429 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005430 return 0;
5431 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005432#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005433 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005434 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005435 return 0;
5436 }
5437#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005438 else if (ret == SSL_ERROR_SYSCALL) {
5439 /* if errno is null, then connection was successfully established */
5440 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5441 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005442 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005443#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5444 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005445 conn->err_code = CO_ER_SSL_HANDSHAKE;
5446#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005447 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005448#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005449 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005450 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005451 empty_handshake = state == TLS_ST_BEFORE;
5452#else
Lukas Tribus49799162019-07-08 14:29:15 +02005453 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5454 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005455#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005456 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005457 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005458 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005459 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5460 else
5461 conn->err_code = CO_ER_SSL_EMPTY;
5462 }
5463 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005464 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005465 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5466 else
5467 conn->err_code = CO_ER_SSL_ABORT;
5468 }
5469 }
5470 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005471 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005472 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005473 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005474 conn->err_code = CO_ER_SSL_HANDSHAKE;
5475 }
Lukas Tribus49799162019-07-08 14:29:15 +02005476#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005477 }
Emeric Brun674b7432012-11-08 19:21:55 +01005478 goto out_error;
5479 }
5480 else {
5481 /* Fail on all other handshake errors */
5482 /* Note: OpenSSL may leave unread bytes in the socket's
5483 * buffer, causing an RST to be emitted upon close() on
5484 * TCP sockets. We first try to drain possibly pending
5485 * data to avoid this as much as possible.
5486 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005487 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005488 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005489 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005490 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005491 goto out_error;
5492 }
5493 }
5494 /* read some data: consider handshake completed */
5495 goto reneg_ok;
5496 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005497 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005498check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005499 if (ret != 1) {
5500 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005501 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005502
5503 if (ret == SSL_ERROR_WANT_WRITE) {
5504 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005505 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005506 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005507 return 0;
5508 }
5509 else if (ret == SSL_ERROR_WANT_READ) {
5510 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005511 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005512 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5513 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005514 return 0;
5515 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005516#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005517 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005518 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005519 return 0;
5520 }
5521#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005522 else if (ret == SSL_ERROR_SYSCALL) {
5523 /* if errno is null, then connection was successfully established */
5524 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5525 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005526 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005527#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5528 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005529 conn->err_code = CO_ER_SSL_HANDSHAKE;
5530#else
5531 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005532#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005533 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005534 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005535 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005536#else
Lukas Tribus49799162019-07-08 14:29:15 +02005537 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5538 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005539#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005540 if (empty_handshake) {
5541 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005542 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005543 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5544 else
5545 conn->err_code = CO_ER_SSL_EMPTY;
5546 }
5547 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005548 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005549 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5550 else
5551 conn->err_code = CO_ER_SSL_ABORT;
5552 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005553 }
5554 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005555 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005556 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5557 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005558 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005559 }
Lukas Tribus49799162019-07-08 14:29:15 +02005560#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005561 }
Willy Tarreau89230192012-09-28 20:22:13 +02005562 goto out_error;
5563 }
Emeric Brun46591952012-05-18 15:47:34 +02005564 else {
5565 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005566 /* Note: OpenSSL may leave unread bytes in the socket's
5567 * buffer, causing an RST to be emitted upon close() on
5568 * TCP sockets. We first try to drain possibly pending
5569 * data to avoid this as much as possible.
5570 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005571 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005572 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005573 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005574 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005575 goto out_error;
5576 }
5577 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005578#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005579 else {
5580 /*
5581 * If the server refused the early data, we have to send a
5582 * 425 to the client, as we no longer have the data to sent
5583 * them again.
5584 */
5585 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005586 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005587 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5588 goto out_error;
5589 }
5590 }
5591 }
5592#endif
5593
Emeric Brun46591952012-05-18 15:47:34 +02005594
Emeric Brun674b7432012-11-08 19:21:55 +01005595reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005596
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005597#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005598 /* ASYNC engine API doesn't support moving read/write
5599 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005600 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005601 */
5602 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005603 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005604#endif
Emeric Brun46591952012-05-18 15:47:34 +02005605 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005606 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005607 if (objt_server(conn->target)) {
5608 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5609 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5610 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005611 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005612 else {
5613 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5614 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5615 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5616 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005617
Willy Tarreau42995282020-11-06 13:19:18 +01005618 if (counters) {
5619 ++counters->sess;
5620 ++counters_px->sess;
5621 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005622 }
Willy Tarreau42995282020-11-06 13:19:18 +01005623 else if (counters) {
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005624 ++counters->reused_sess;
5625 ++counters_px->reused_sess;
Emeric Brun46591952012-05-18 15:47:34 +02005626 }
5627
5628 /* The connection is now established at both layers, it's time to leave */
5629 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5630 return 1;
5631
5632 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005633 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005634 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005635 ERR_clear_error();
5636
Emeric Brun9fa89732012-10-04 17:09:56 +02005637 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01005638 if (objt_server(conn->target)) {
5639 struct server *s = __objt_server(conn->target);
5640 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
5641 * one cache per thread, it only prevents to flush it from the CLI in
5642 * another thread */
5643
5644 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005645 if (s->ssl_ctx.reused_sess[tid].ptr)
5646 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005647 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02005648 }
5649
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005650 if (counters) {
5651 ++counters->failed_handshake;
5652 ++counters_px->failed_handshake;
5653 }
5654
Emeric Brun46591952012-05-18 15:47:34 +02005655 /* Fail on all other handshake errors */
5656 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005657 if (!conn->err_code)
5658 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005659 return 0;
5660}
5661
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005662/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5663 * event subscriber <es> is not allowed to change from a previous call as long
5664 * as at least one event is still subscribed. The <event_type> must only be a
5665 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5666 * unless the transport layer was already released.
5667 */
5668static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005669{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005670 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005671
Olivier Houchard0ff28652019-06-24 18:57:39 +02005672 if (!ctx)
5673 return -1;
5674
Willy Tarreau113d52b2020-01-10 09:20:26 +01005675 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005676 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005677
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005678 ctx->subs = es;
5679 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005680
5681 /* we may have to subscribe to lower layers for new events */
5682 event_type &= ~ctx->wait_event.events;
5683 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5684 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005685 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005686}
5687
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005688/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5689 * The <es> pointer is not allowed to differ from the one passed to the
5690 * subscribe() call. It always returns zero.
5691 */
5692static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005693{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005694 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005695
Willy Tarreau113d52b2020-01-10 09:20:26 +01005696 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005697 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005698
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005699 es->events &= ~event_type;
5700 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005701 ctx->subs = NULL;
5702
5703 /* If we subscribed, and we're not doing the handshake,
5704 * then we subscribed because the upper layer asked for it,
5705 * as the upper layer is no longer interested, we can
5706 * unsubscribe too.
5707 */
5708 event_type &= ctx->wait_event.events;
5709 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5710 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005711
5712 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005713}
5714
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005715/* The connection has been taken over, so destroy the old tasklet and create
5716 * a new one. The original thread ID must be passed into orig_tid
5717 * It should be called with the takeover lock for the old thread held.
5718 * Returns 0 on success, and -1 on failure
5719 */
5720static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
5721{
5722 struct ssl_sock_ctx *ctx = xprt_ctx;
5723 struct tasklet *tl = tasklet_new();
5724
5725 if (!tl)
5726 return -1;
5727
5728 ctx->wait_event.tasklet->context = NULL;
5729 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
5730 ctx->wait_event.tasklet = tl;
5731 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5732 ctx->wait_event.tasklet->context = ctx;
5733 return 0;
5734}
5735
Willy Tarreau41491682021-03-02 17:29:56 +01005736/* notify the next xprt that the connection is about to become idle and that it
5737 * may be stolen at any time after the function returns and that any tasklet in
5738 * the chain must be careful before dereferencing its context.
5739 */
5740static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
5741{
5742 struct ssl_sock_ctx *ctx = xprt_ctx;
5743
5744 if (!ctx || !ctx->wait_event.tasklet)
5745 return;
5746
5747 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5748 if (ctx->xprt)
5749 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
5750}
5751
5752/* notify the next xprt that the connection is not idle anymore and that it may
5753 * not be stolen before the next xprt_set_idle().
5754 */
5755static void ssl_set_used(struct connection *conn, void *xprt_ctx)
5756{
5757 struct ssl_sock_ctx *ctx = xprt_ctx;
5758
5759 if (!ctx || !ctx->wait_event.tasklet)
5760 return;
5761
5762 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5763 if (ctx->xprt)
5764 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
5765}
5766
Olivier Houchard2e055482019-05-27 19:50:12 +02005767/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5768 * Returns 0 on success, and non-zero on failure.
5769 */
5770static 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)
5771{
5772 struct ssl_sock_ctx *ctx = xprt_ctx;
5773
5774 if (oldxprt_ops != NULL)
5775 *oldxprt_ops = ctx->xprt;
5776 if (oldxprt_ctx != NULL)
5777 *oldxprt_ctx = ctx->xprt_ctx;
5778 ctx->xprt = toadd_ops;
5779 ctx->xprt_ctx = toadd_ctx;
5780 return 0;
5781}
5782
Olivier Houchard5149b592019-05-23 17:47:36 +02005783/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5784 * return 0, otherwise just call the remove_xprt method from the underlying
5785 * XPRT.
5786 */
5787static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5788{
5789 struct ssl_sock_ctx *ctx = xprt_ctx;
5790
5791 if (ctx->xprt_ctx == toremove_ctx) {
5792 ctx->xprt_ctx = newctx;
5793 ctx->xprt = newops;
5794 return 0;
5795 }
5796 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5797}
5798
Willy Tarreau144f84a2021-03-02 16:09:26 +01005799struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02005800{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005801 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005802 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005803 struct connection *conn;
5804 int conn_in_list;
5805 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005806
Willy Tarreau41491682021-03-02 17:29:56 +01005807 if (state & TASK_F_USR1) {
5808 /* the tasklet was idling on an idle connection, it might have
5809 * been stolen, let's be careful!
5810 */
5811 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5812 if (tl->context == NULL) {
5813 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5814 tasklet_free(tl);
5815 return NULL;
5816 }
5817 conn = ctx->conn;
5818 conn_in_list = conn->flags & CO_FL_LIST_MASK;
5819 if (conn_in_list)
5820 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005821 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01005822 } else {
5823 conn = ctx->conn;
5824 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005825 }
Willy Tarreau41491682021-03-02 17:29:56 +01005826
Olivier Houchardea8dd942019-05-20 14:02:16 +02005827 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01005828 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005829 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005830 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5831 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01005832 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005833 }
5834 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005835 /* If we had an error, or the handshake is done and I/O is available,
5836 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005837 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005838 * we can't be sure conn_fd_handler() will be called again.
5839 */
5840 if ((ctx->conn->flags & CO_FL_ERROR) ||
5841 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005842 int woke = 0;
5843
5844 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005845 if (ctx->subs) {
5846 tasklet_wakeup(ctx->subs->tasklet);
5847 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005848 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005849 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005850 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005851
Olivier Houchardea8dd942019-05-20 14:02:16 +02005852 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005853 * upper layers know. If we have no mux, create it,
5854 * and once we have a mux, call its wake method if we didn't
5855 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005856 */
5857 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005858 if (!ctx->conn->mux)
5859 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005860 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005861 ret = ctx->conn->mux->wake(ctx->conn);
5862 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005863 }
5864 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05005865#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01005866 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005867 else if (b_data(&ctx->early_buf) && ctx->subs &&
5868 ctx->subs->events & SUB_RETRY_RECV) {
5869 tasklet_wakeup(ctx->subs->tasklet);
5870 ctx->subs->events &= ~SUB_RETRY_RECV;
5871 if (!ctx->subs->events)
5872 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005873 }
5874#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005875leave:
5876 if (!ret && conn_in_list) {
5877 struct server *srv = objt_server(conn->target);
5878
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005879 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005880 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau430bf4a2021-03-04 09:45:32 +01005881 ebmb_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005882 else
Willy Tarreau430bf4a2021-03-04 09:45:32 +01005883 ebmb_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005884 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005885 }
Willy Tarreau74163142021-03-13 11:30:19 +01005886 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005887}
5888
Emeric Brun46591952012-05-18 15:47:34 +02005889/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01005890 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02005891 * buffer wraps, in which case a second call may be performed. The connection's
5892 * flags are updated with whatever special event is detected (error, read0,
5893 * empty). The caller is responsible for taking care of those events and
5894 * avoiding the call if inappropriate. The function does not call the
5895 * connection's polling update function, so the caller is responsible for this.
5896 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005897static 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 +02005898{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005899 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02005900 ssize_t ret;
5901 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02005902
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005903 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005904 goto out_error;
5905
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05005906#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01005907 if (b_data(&ctx->early_buf)) {
5908 try = b_contig_space(buf);
5909 if (try > b_data(&ctx->early_buf))
5910 try = b_data(&ctx->early_buf);
5911 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
5912 b_add(buf, try);
5913 b_del(&ctx->early_buf, try);
5914 if (b_data(&ctx->early_buf) == 0)
5915 b_free(&ctx->early_buf);
5916 return try;
5917 }
5918#endif
5919
Willy Tarreau911db9b2020-01-23 16:27:54 +01005920 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005921 /* a handshake was requested */
5922 return 0;
5923
Emeric Brun46591952012-05-18 15:47:34 +02005924 /* read the largest possible block. For this, we perform only one call
5925 * to recv() unless the buffer wraps and we exactly fill the first hunk,
5926 * in which case we accept to do it once again. A new attempt is made on
5927 * EINTR too.
5928 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01005929 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005930
Willy Tarreau591d4452018-06-15 17:21:00 +02005931 try = b_contig_space(buf);
5932 if (!try)
5933 break;
5934
Willy Tarreauabf08d92014-01-14 11:31:27 +01005935 if (try > count)
5936 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02005937
Olivier Houchard66ab4982019-02-26 18:37:15 +01005938 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005939
Emeric Brune1f38db2012-09-03 20:36:47 +02005940 if (conn->flags & CO_FL_ERROR) {
5941 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005942 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005943 }
Emeric Brun46591952012-05-18 15:47:34 +02005944 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02005945 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005946 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005947 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005948 }
Emeric Brun46591952012-05-18 15:47:34 +02005949 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005950 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005951 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005952 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02005953 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005954 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005955#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005956 /* Async mode can be re-enabled, because we're leaving data state.*/
5957 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005958 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005959#endif
Emeric Brun46591952012-05-18 15:47:34 +02005960 break;
5961 }
5962 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005963 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005964 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5965 SUB_RETRY_RECV,
5966 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01005967 /* handshake is running, and it may need to re-enable read */
5968 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005969#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005970 /* Async mode can be re-enabled, because we're leaving data state.*/
5971 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005972 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005973#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005974 break;
5975 }
Emeric Brun46591952012-05-18 15:47:34 +02005976 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005977 } else if (ret == SSL_ERROR_ZERO_RETURN)
5978 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005979 /* For SSL_ERROR_SYSCALL, make sure to clear the error
5980 * stack before shutting down the connection for
5981 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005982 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
5983 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02005984 /* otherwise it's a real error */
5985 goto out_error;
5986 }
5987 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005988 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005989 return done;
5990
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005991 clear_ssl_error:
5992 /* Clear openssl global errors stack */
5993 ssl_sock_dump_errors(conn);
5994 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02005995 read0:
5996 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005997 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005998
Emeric Brun46591952012-05-18 15:47:34 +02005999 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006000 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006001 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006002 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006003 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006004 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006005}
6006
6007
Willy Tarreau787db9a2018-06-14 18:31:46 +02006008/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6009 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6010 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006011 * Only one call to send() is performed, unless the buffer wraps, in which case
6012 * a second call may be performed. The connection's flags are updated with
6013 * whatever special event is detected (error, empty). The caller is responsible
6014 * for taking care of those events and avoiding the call if inappropriate. The
6015 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006016 * is responsible for this. The buffer's output is not adjusted, it's up to the
6017 * caller to take care of this. It's up to the caller to update the buffer's
6018 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006019 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006020static 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 +02006021{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006022 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006023 ssize_t ret;
6024 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006025
6026 done = 0;
6027
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006028 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006029 goto out_error;
6030
Willy Tarreau911db9b2020-01-23 16:27:54 +01006031 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006032 /* a handshake was requested */
6033 return 0;
6034
6035 /* send the largest possible block. For this we perform only one call
6036 * to send() unless the buffer wraps and we exactly fill the first hunk,
6037 * in which case we accept to do it once again.
6038 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006039 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006040#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006041 size_t written_data;
6042#endif
6043
Willy Tarreau787db9a2018-06-14 18:31:46 +02006044 try = b_contig_data(buf, done);
6045 if (try > count)
6046 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006047
Willy Tarreau7bed9452014-02-02 02:00:24 +01006048 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006049 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006050 global_ssl.max_record && try > global_ssl.max_record) {
6051 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006052 }
6053 else {
6054 /* we need to keep the information about the fact that
6055 * we're not limiting the upcoming send(), because if it
6056 * fails, we'll have to retry with at least as many data.
6057 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006058 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006059 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006060
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006061#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006062 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006063 unsigned int max_early;
6064
Olivier Houchard522eea72017-11-03 16:27:47 +01006065 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006066 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006067 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006068 if (SSL_get0_session(ctx->ssl))
6069 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006070 else
6071 max_early = 0;
6072 }
6073
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006074 if (try + ctx->sent_early_data > max_early) {
6075 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006076 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006077 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006078 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006079 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006080 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006081 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006082 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006083 if (ret == 1) {
6084 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006085 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006086 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006087 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006088 /* Initiate the handshake, now */
6089 tasklet_wakeup(ctx->wait_event.tasklet);
6090 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006091
Olivier Houchardc2aae742017-09-22 18:26:28 +02006092 }
6093
6094 } else
6095#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006096 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006097
Emeric Brune1f38db2012-09-03 20:36:47 +02006098 if (conn->flags & CO_FL_ERROR) {
6099 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006100 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006101 }
Emeric Brun46591952012-05-18 15:47:34 +02006102 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006103 /* A send succeeded, so we can consider ourself connected */
6104 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006105 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006106 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006107 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006108 }
6109 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006110 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006111
Emeric Brun46591952012-05-18 15:47:34 +02006112 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006113 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006114 /* handshake is running, and it may need to re-enable write */
6115 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006116 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006117#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006118 /* Async mode can be re-enabled, because we're leaving data state.*/
6119 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006120 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006121#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006122 break;
6123 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006124
Emeric Brun46591952012-05-18 15:47:34 +02006125 break;
6126 }
6127 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006128 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006129 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006130 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6131 SUB_RETRY_RECV,
6132 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006133#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006134 /* Async mode can be re-enabled, because we're leaving data state.*/
6135 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006136 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006137#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006138 break;
6139 }
Emeric Brun46591952012-05-18 15:47:34 +02006140 goto out_error;
6141 }
6142 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006143 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006144 return done;
6145
6146 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006147 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006148 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006149 ERR_clear_error();
6150
Emeric Brun46591952012-05-18 15:47:34 +02006151 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006152 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006153}
6154
Willy Tarreau832e2422021-05-13 10:11:03 +02006155void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006156
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006157 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006158
Olivier Houchardea8dd942019-05-20 14:02:16 +02006159
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006160 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006161 if (ctx->wait_event.events != 0)
6162 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6163 ctx->wait_event.events,
6164 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006165 if (ctx->subs) {
6166 ctx->subs->events = 0;
6167 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006168 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006169
Olivier Houchard692c1d02019-05-23 18:41:47 +02006170 if (ctx->xprt->close)
6171 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006172#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006173 if (global_ssl.async) {
6174 OSSL_ASYNC_FD all_fd[32], afd;
6175 size_t num_all_fds = 0;
6176 int i;
6177
Olivier Houchard66ab4982019-02-26 18:37:15 +01006178 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006179 if (num_all_fds > 32) {
6180 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6181 return;
6182 }
6183
Olivier Houchard66ab4982019-02-26 18:37:15 +01006184 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006185
6186 /* If an async job is pending, we must try to
6187 to catch the end using polling before calling
6188 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006189 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006190 for (i=0 ; i < num_all_fds ; i++) {
6191 /* switch on an handler designed to
6192 * handle the SSL_free
6193 */
6194 afd = all_fd[i];
6195 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006196 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006197 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006198 /* To ensure that the fd cache won't be used
6199 * and we'll catch a real RD event.
6200 */
6201 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006202 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006203 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006204 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006205 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006206 return;
6207 }
Emeric Brun3854e012017-05-17 20:42:48 +02006208 /* Else we can remove the fds from the fdtab
6209 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006210 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006211 * because the fd is owned by the engine.
6212 * the engine is responsible to close
6213 */
6214 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +02006215 fd_stop_both(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006216 }
6217#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006218 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006219 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006220 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006221 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006222 _HA_ATOMIC_DEC(&sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006223 }
Emeric Brun46591952012-05-18 15:47:34 +02006224}
6225
6226/* This function tries to perform a clean shutdown on an SSL connection, and in
6227 * any case, flags the connection as reusable if no handshake was in progress.
6228 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006229static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006230{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006231 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006232
Willy Tarreau911db9b2020-01-23 16:27:54 +01006233 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006234 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006235 if (!clean)
6236 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006237 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006238 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006239 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006240 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006241 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006242 ERR_clear_error();
6243 }
Emeric Brun46591952012-05-18 15:47:34 +02006244}
6245
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006246
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006247/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006248int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6249{
6250 struct ssl_sock_ctx *ctx;
6251 X509 *crt;
6252
6253 if (!ssl_sock_is_ssl(conn))
6254 return 0;
6255
6256 ctx = conn->xprt_ctx;
6257
6258 crt = SSL_get_certificate(ctx->ssl);
6259 if (!crt)
6260 return 0;
6261
6262 return cert_get_pkey_algo(crt, out);
6263}
6264
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006265/* used for ppv2 cert signature (can be used for logging) */
6266const char *ssl_sock_get_cert_sig(struct connection *conn)
6267{
Christopher Faulet82004142019-09-10 10:12:03 +02006268 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006269
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006270 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6271 X509 *crt;
6272
6273 if (!ssl_sock_is_ssl(conn))
6274 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006275 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006276 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006277 if (!crt)
6278 return NULL;
6279 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6280 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6281}
6282
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006283/* used for ppv2 authority */
6284const char *ssl_sock_get_sni(struct connection *conn)
6285{
6286#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006287 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006288
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006289 if (!ssl_sock_is_ssl(conn))
6290 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006291 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006292 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006293#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006294 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006295#endif
6296}
6297
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006298/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006299const char *ssl_sock_get_cipher_name(struct connection *conn)
6300{
Christopher Faulet82004142019-09-10 10:12:03 +02006301 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006302
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006303 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006304 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006305 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006306 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006307}
6308
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006309/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006310const char *ssl_sock_get_proto_version(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 Hocdet01da5712017-10-13 16:59:49 +02006314 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006315 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006316 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006317 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006318}
6319
Olivier Houchardab28a322018-12-21 19:45:40 +01006320void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6321{
6322#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02006323 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006324
Olivier Houcharde488ea82019-06-28 14:10:33 +02006325 if (!ssl_sock_is_ssl(conn))
6326 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006327 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006328 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006329#endif
6330}
6331
Willy Tarreau119a4082016-12-22 21:58:38 +01006332/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6333 * to disable SNI.
6334 */
Willy Tarreau63076412015-07-10 11:33:32 +02006335void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6336{
6337#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006338 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006339
Willy Tarreau119a4082016-12-22 21:58:38 +01006340 char *prev_name;
6341
Willy Tarreau63076412015-07-10 11:33:32 +02006342 if (!ssl_sock_is_ssl(conn))
6343 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006344 ctx = conn->xprt_ctx;
Willy Tarreau63076412015-07-10 11:33:32 +02006345
Willy Tarreau119a4082016-12-22 21:58:38 +01006346 /* if the SNI changes, we must destroy the reusable context so that a
6347 * new connection will present a new SNI. As an optimization we could
6348 * later imagine having a small cache of ssl_ctx to hold a few SNI per
6349 * server.
6350 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006351 prev_name = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau119a4082016-12-22 21:58:38 +01006352 if ((!prev_name && hostname) ||
6353 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006354 SSL_set_session(ctx->ssl, NULL);
Willy Tarreau119a4082016-12-22 21:58:38 +01006355
Olivier Houchard66ab4982019-02-26 18:37:15 +01006356 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006357#endif
6358}
6359
Emeric Brun0abf8362014-06-24 18:26:41 +02006360/* Extract peer certificate's common name into the chunk dest
6361 * Returns
6362 * the len of the extracted common name
6363 * or 0 if no CN found in DN
6364 * or -1 on error case (i.e. no peer certificate)
6365 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006366int ssl_sock_get_remote_common_name(struct connection *conn,
6367 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006368{
Christopher Faulet82004142019-09-10 10:12:03 +02006369 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04006370 X509 *crt = NULL;
6371 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006372 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006373 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006374 .area = (char *)&find_cn,
6375 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006376 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006377 int result = -1;
David Safb76832014-05-08 23:42:08 -04006378
6379 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02006380 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02006381 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006382
6383 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006384 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006385 if (!crt)
6386 goto out;
6387
6388 name = X509_get_subject_name(crt);
6389 if (!name)
6390 goto out;
David Safb76832014-05-08 23:42:08 -04006391
Emeric Brun0abf8362014-06-24 18:26:41 +02006392 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6393out:
David Safb76832014-05-08 23:42:08 -04006394 if (crt)
6395 X509_free(crt);
6396
6397 return result;
6398}
6399
Dave McCowan328fb582014-07-30 10:39:13 -04006400/* returns 1 if client passed a certificate for this session, 0 if not */
6401int ssl_sock_get_cert_used_sess(struct connection *conn)
6402{
Christopher Faulet82004142019-09-10 10:12:03 +02006403 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006404 X509 *crt = NULL;
6405
6406 if (!ssl_sock_is_ssl(conn))
6407 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006408 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006409
6410 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006411 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006412 if (!crt)
6413 return 0;
6414
6415 X509_free(crt);
6416 return 1;
6417}
6418
6419/* returns 1 if client passed a certificate for this connection, 0 if not */
6420int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006421{
Christopher Faulet82004142019-09-10 10:12:03 +02006422 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006423
David Safb76832014-05-08 23:42:08 -04006424 if (!ssl_sock_is_ssl(conn))
6425 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006426 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006427 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006428}
6429
6430/* returns result from SSL verify */
6431unsigned int ssl_sock_get_verify_result(struct connection *conn)
6432{
Christopher Faulet82004142019-09-10 10:12:03 +02006433 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006434
David Safb76832014-05-08 23:42:08 -04006435 if (!ssl_sock_is_ssl(conn))
6436 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006437 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006438 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006439}
6440
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006441/* Returns the application layer protocol name in <str> and <len> when known.
6442 * Zero is returned if the protocol name was not found, otherwise non-zero is
6443 * returned. The string is allocated in the SSL context and doesn't have to be
6444 * freed by the caller. NPN is also checked if available since older versions
6445 * of openssl (1.0.1) which are more common in field only support this one.
6446 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006447static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006448{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006449#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6450 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006451 struct ssl_sock_ctx *ctx = xprt_ctx;
6452 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006453 return 0;
6454
6455 *str = NULL;
6456
6457#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006458 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006459 if (*str)
6460 return 1;
6461#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006462#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006463 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006464 if (*str)
6465 return 1;
6466#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006467#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006468 return 0;
6469}
6470
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006471/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006472int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006473{
6474 X509 *ca;
6475 X509_NAME *name = NULL;
6476 ASN1_OCTET_STRING *skid = NULL;
6477 STACK_OF(X509) *chain = NULL;
6478 struct issuer_chain *issuer;
6479 struct eb64_node *node;
6480 char *path;
6481 u64 key;
6482 int ret = 0;
6483
6484 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6485 if (chain == NULL) {
6486 chain = sk_X509_new_null();
6487 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6488 name = X509_get_subject_name(ca);
6489 }
6490 if (!sk_X509_push(chain, ca)) {
6491 X509_free(ca);
6492 goto end;
6493 }
6494 }
6495 if (!chain) {
6496 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6497 goto end;
6498 }
6499 if (!skid) {
6500 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6501 goto end;
6502 }
6503 if (!name) {
6504 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6505 goto end;
6506 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006507 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006508 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006509 issuer = container_of(node, typeof(*issuer), node);
6510 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6511 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6512 goto end;
6513 }
6514 }
6515 issuer = calloc(1, sizeof *issuer);
6516 path = strdup(fp);
6517 if (!issuer || !path) {
6518 free(issuer);
6519 free(path);
6520 goto end;
6521 }
6522 issuer->node.key = key;
6523 issuer->path = path;
6524 issuer->chain = chain;
6525 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006526 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006527 ret = 1;
6528 end:
6529 if (skid)
6530 ASN1_OCTET_STRING_free(skid);
6531 if (chain)
6532 sk_X509_pop_free(chain, X509_free);
6533 return ret;
6534}
6535
William Lallemandda8584c2020-05-14 10:14:37 +02006536 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006537{
6538 AUTHORITY_KEYID *akid;
6539 struct issuer_chain *issuer = NULL;
6540
6541 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006542 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006543 struct eb64_node *node;
6544 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006545 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006546 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6547 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6548 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6549 issuer = ti;
6550 break;
6551 }
6552 }
6553 AUTHORITY_KEYID_free(akid);
6554 }
6555 return issuer;
6556}
6557
William Lallemanddad31052020-05-14 17:47:32 +02006558void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006559{
6560 struct eb64_node *node, *back;
6561 struct issuer_chain *issuer;
6562
William Lallemande0f3fd52020-02-25 14:53:06 +01006563 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006564 while (node) {
6565 issuer = container_of(node, typeof(*issuer), node);
6566 back = eb64_next(node);
6567 eb64_delete(node);
6568 free(issuer->path);
6569 sk_X509_pop_free(issuer->chain, X509_free);
6570 free(issuer);
6571 node = back;
6572 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006573}
6574
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006575#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006576static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006577 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006578
Emeric Brun3854e012017-05-17 20:42:48 +02006579 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006580 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006581 err_code = ERR_ABORT;
6582 }
6583 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006584}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006585#endif
6586
Willy Tarreaude5675a2021-01-20 14:41:29 +01006587/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006588 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006589 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006590static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006591{
6592 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006593 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006594
6595 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006596 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006597
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006598 if (sctx->conn != conn) {
6599 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6600 ret = 1;
6601 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01006602 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6603
6604 if (sctx->xprt) {
6605 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6606 if (sctx->xprt_ctx)
6607 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6608 }
6609
6610 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006611
6612 /* as soon as a shutdown is reported the lower layer unregisters its
6613 * subscriber, so the situations below are transient and rare enough to
6614 * be reported as suspicious. In any case they shouldn't last.
6615 */
6616 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
6617 ret = 1;
6618 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
6619 ret = 1;
6620
Willy Tarreaude5675a2021-01-20 14:41:29 +01006621 chunk_appendf(&trash, " .subs=%p", sctx->subs);
6622 if (sctx->subs) {
6623 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006624 if (sctx->subs->tasklet->calls >= 1000000)
6625 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006626 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
6627 sctx->subs->tasklet->calls,
6628 sctx->subs->tasklet->context);
6629 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
6630 chunk_appendf(&trash, ")");
6631 }
6632 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
6633 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006634 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006635}
6636
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006637#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02006638/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006639 * each reference. The variable <ref> must point to the current node's list
6640 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02006641 */
William Lallemand32af2032016-10-29 18:09:35 +02006642static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006643struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02006644{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006645 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006646 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02006647
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006648 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006649 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006650 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02006651
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006652 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02006653}
6654
6655static inline
6656struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6657{
6658 int id;
6659 char *error;
6660
6661 /* If the reference starts by a '#', this is numeric id. */
6662 if (reference[0] == '#') {
6663 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6664 id = strtol(reference + 1, &error, 10);
6665 if (*error != '\0')
6666 return NULL;
6667
6668 /* Perform the unique id lookup. */
6669 return tlskeys_ref_lookupid(id);
6670 }
6671
6672 /* Perform the string lookup. */
6673 return tlskeys_ref_lookup(reference);
6674}
6675#endif
6676
6677
6678#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6679
6680static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6681
6682static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6683 return cli_io_handler_tlskeys_files(appctx);
6684}
6685
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006686/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6687 * (next index to be dumped), and cli.p0 (next key reference).
6688 */
William Lallemand32af2032016-10-29 18:09:35 +02006689static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6690
6691 struct stream_interface *si = appctx->owner;
6692
6693 switch (appctx->st2) {
6694 case STAT_ST_INIT:
6695 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006696 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006697 * later and restart at the state "STAT_ST_INIT".
6698 */
6699 chunk_reset(&trash);
6700
6701 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6702 chunk_appendf(&trash, "# id secret\n");
6703 else
6704 chunk_appendf(&trash, "# id (file)\n");
6705
Willy Tarreau06d80a92017-10-19 14:32:15 +02006706 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006707 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006708 return 0;
6709 }
6710
William Lallemand32af2032016-10-29 18:09:35 +02006711 /* Now, we start the browsing of the references lists.
6712 * Note that the following call to LIST_ELEM return bad pointer. The only
6713 * available field of this pointer is <list>. It is used with the function
6714 * tlskeys_list_get_next() for retruning the first available entry
6715 */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006716 if (appctx->ctx.cli.p0 == NULL)
6717 appctx->ctx.cli.p0 = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006718
6719 appctx->st2 = STAT_ST_LIST;
6720 /* fall through */
6721
6722 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006723 while (appctx->ctx.cli.p0) {
6724 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006725
6726 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006727 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006728 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006729
6730 if (appctx->ctx.cli.i1 == 0)
6731 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6732
William Lallemand32af2032016-10-29 18:09:35 +02006733 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006734 int head;
6735
6736 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6737 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006738 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006739 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006740
6741 chunk_reset(t2);
6742 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006743 if (ref->key_size_bits == 128) {
6744 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6745 sizeof(struct tls_sess_key_128),
6746 t2->area, t2->size);
6747 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6748 t2->area);
6749 }
6750 else if (ref->key_size_bits == 256) {
6751 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6752 sizeof(struct tls_sess_key_256),
6753 t2->area, t2->size);
6754 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6755 t2->area);
6756 }
6757 else {
6758 /* This case should never happen */
6759 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6760 }
William Lallemand32af2032016-10-29 18:09:35 +02006761
Willy Tarreau06d80a92017-10-19 14:32:15 +02006762 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006763 /* let's try again later from this stream. We add ourselves into
6764 * this stream's users so that it can remove us upon termination.
6765 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006766 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006767 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006768 return 0;
6769 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006770 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006771 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006772 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006773 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006774 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006775 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006776 /* let's try again later from this stream. We add ourselves into
6777 * this stream's users so that it can remove us upon termination.
6778 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006779 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006780 return 0;
6781 }
6782
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006783 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006784 break;
6785
6786 /* get next list entry and check the end of the list */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006787 appctx->ctx.cli.p0 = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006788 }
6789
6790 appctx->st2 = STAT_ST_FIN;
6791 /* fall through */
6792
6793 default:
6794 appctx->st2 = STAT_ST_FIN;
6795 return 1;
6796 }
6797 return 0;
6798}
6799
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006800/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006801static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006802{
William Lallemand32af2032016-10-29 18:09:35 +02006803 /* no parameter, shows only file list */
6804 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006805 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006806 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006807 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006808 }
6809
6810 if (args[2][0] == '*') {
6811 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006812 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006813 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006814 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006815 if (!appctx->ctx.cli.p0)
6816 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006817 }
William Lallemand32af2032016-10-29 18:09:35 +02006818 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006819 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006820}
6821
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006822static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006823{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006824 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006825 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006826
William Lallemand32af2032016-10-29 18:09:35 +02006827 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006828 if (!*args[3] || !*args[4])
6829 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 +02006830
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006831 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006832 if (!ref)
6833 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006834
Willy Tarreau1c913e42018-08-22 05:26:57 +02006835 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006836 if (ret < 0)
6837 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006838
Willy Tarreau1c913e42018-08-22 05:26:57 +02006839 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006840 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6841 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006842
Willy Tarreau9d008692019-08-09 11:21:01 +02006843 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006844}
William Lallemandd4f946c2019-12-05 10:26:40 +01006845#endif
William Lallemand419e6342020-04-08 12:05:39 +02006846
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006847static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006848{
6849#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6850 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006851 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006852
6853 if (!payload)
6854 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006855
6856 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006857 if (!*payload)
6858 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006859
6860 /* remove \r and \n from the payload */
6861 for (i = 0, j = 0; payload[i]; i++) {
6862 if (payload[i] == '\r' || payload[i] == '\n')
6863 continue;
6864 payload[j++] = payload[i];
6865 }
6866 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006867
Willy Tarreau1c913e42018-08-22 05:26:57 +02006868 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006869 if (ret < 0)
6870 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006871
Willy Tarreau1c913e42018-08-22 05:26:57 +02006872 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02006873 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02006874 if (err)
6875 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
6876 else
6877 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006878 }
Willy Tarreau9d008692019-08-09 11:21:01 +02006879
6880 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006881#else
Willy Tarreau9d008692019-08-09 11:21:01 +02006882 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 +02006883#endif
6884
Elliot Otchet71f82972020-01-15 08:12:14 -05006885}
6886
William Lallemand32af2032016-10-29 18:09:35 +02006887/* register cli keywords */
6888static struct cli_kw_list cli_kws = {{ },{
6889#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Willy Tarreaub205bfd2021-05-07 11:38:37 +02006890 { { "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 },
6891 { { "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 +02006892#endif
Willy Tarreaub205bfd2021-05-07 11:38:37 +02006893 { { "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 +02006894 { { NULL }, NULL, NULL, NULL }
6895}};
6896
Willy Tarreau0108d902018-11-25 19:14:37 +01006897INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02006898
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02006899/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02006900struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02006901 .snd_buf = ssl_sock_from_buf,
6902 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01006903 .subscribe = ssl_subscribe,
6904 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02006905 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02006906 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02006907 .rcv_pipe = NULL,
6908 .snd_pipe = NULL,
6909 .shutr = NULL,
6910 .shutw = ssl_sock_shutw,
6911 .close = ssl_sock_close,
6912 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01006913 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01006914 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01006915 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01006916 .prepare_srv = ssl_sock_prepare_srv_ctx,
6917 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006918 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006919 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01006920 .set_idle = ssl_set_idle,
6921 .set_used = ssl_set_used,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01006922 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01006923 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02006924};
6925
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006926enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
6927 struct session *sess, struct stream *s, int flags)
6928{
6929 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006930 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006931
6932 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006933 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006934
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006935 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006936 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006937 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006938 s->req.flags |= CF_READ_NULL;
6939 return ACT_RET_YIELD;
6940 }
6941 }
6942 return (ACT_RET_CONT);
6943}
6944
6945static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
6946{
6947 rule->action_ptr = ssl_action_wait_for_hs;
6948
6949 return ACT_RET_PRS_OK;
6950}
6951
6952static struct action_kw_list http_req_actions = {ILH, {
6953 { "wait-for-handshake", ssl_parse_wait_for_hs },
6954 { /* END */ }
6955}};
6956
Willy Tarreau0108d902018-11-25 19:14:37 +01006957INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
6958
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05006959#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006960
6961static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6962{
6963 if (ptr) {
6964 chunk_destroy(ptr);
6965 free(ptr);
6966 }
6967}
6968
6969#endif
William Lallemand76b4a122020-08-04 17:41:39 +02006970
6971#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
6972static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6973{
6974 struct ocsp_cbk_arg *ocsp_arg;
6975
6976 if (ptr) {
6977 ocsp_arg = ptr;
6978
6979 if (ocsp_arg->is_single) {
6980 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
6981 ocsp_arg->s_ocsp = NULL;
6982 } else {
6983 int i;
6984
6985 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
6986 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
6987 ocsp_arg->m_ocsp[i] = NULL;
6988 }
6989 }
6990 free(ocsp_arg);
6991 }
6992}
6993#endif
6994
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006995static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6996{
Willy Tarreaubafbe012017-11-24 17:34:44 +01006997 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006998}
William Lallemand7d42ef52020-07-06 11:41:30 +02006999
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05007000#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007001static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7002{
7003 struct ssl_keylog *keylog;
7004
7005 if (!ptr)
7006 return;
7007
7008 keylog = ptr;
7009
7010 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7011 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7012 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7013 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7014 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7015 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7016 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7017 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7018
7019 pool_free(pool_head_ssl_keylog, ptr);
7020}
7021#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007022
Emeric Brun46591952012-05-18 15:47:34 +02007023__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02007024static void __ssl_sock_init(void)
7025{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007026#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007027 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007028 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007029#endif
Emeric Brun46591952012-05-18 15:47:34 +02007030
Willy Tarreauef934602016-12-22 23:12:01 +01007031 if (global_ssl.listen_default_ciphers)
7032 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7033 if (global_ssl.connect_default_ciphers)
7034 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007035#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007036 if (global_ssl.listen_default_ciphersuites)
7037 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7038 if (global_ssl.connect_default_ciphersuites)
7039 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7040#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007041
Willy Tarreau13e14102016-12-22 20:25:26 +01007042 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007043#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007044 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007045#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007046#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007047 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007048 n = sk_SSL_COMP_num(cm);
7049 while (n--) {
7050 (void) sk_SSL_COMP_pop(cm);
7051 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007052#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007053
Willy Tarreau5db847a2019-05-09 14:13:35 +02007054#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007055 ssl_locking_init();
7056#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007057#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007058 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7059#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007060
7061#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7062 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7063#endif
7064
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007065 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007066 ssl_capture_ptr_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_capture_free_func);
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05007067#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007068 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7069#endif
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007070#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007071 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007072 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007073#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007074#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7075 hap_register_post_check(tlskeys_finalize_config);
7076#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007077
7078 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7079 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7080
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007081 hap_register_post_deinit(ssl_free_global_issuers);
7082
Willy Tarreau80713382018-11-26 10:19:54 +01007083#ifndef OPENSSL_NO_DH
7084 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7085 hap_register_post_deinit(ssl_free_dh);
7086#endif
7087#ifndef OPENSSL_NO_ENGINE
7088 hap_register_post_deinit(ssl_free_engines);
7089#endif
7090 /* Load SSL string for the verbose & debug mode. */
7091 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02007092 ha_meth = BIO_meth_new(0x666, "ha methods");
7093 BIO_meth_set_write(ha_meth, ha_ssl_write);
7094 BIO_meth_set_read(ha_meth, ha_ssl_read);
7095 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7096 BIO_meth_set_create(ha_meth, ha_ssl_new);
7097 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7098 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7099 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007100
7101 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007102
Dragan Dosen9ac98092020-05-11 15:51:45 +02007103 /* Try to register dedicated SSL/TLS protocol message callbacks for
7104 * heartbleed attack (CVE-2014-0160) and clienthello.
7105 */
7106 hap_register_post_check(ssl_sock_register_msg_callbacks);
7107
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007108 /* Try to free all callbacks that were registered by using
7109 * ssl_sock_register_msg_callback().
7110 */
7111 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007112}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007113
Willy Tarreau80713382018-11-26 10:19:54 +01007114/* Compute and register the version string */
7115static void ssl_register_build_options()
7116{
7117 char *ptr = NULL;
7118 int i;
7119
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007120 memprintf(&ptr, "Built with OpenSSL version : "
7121#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007122 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007123#else /* OPENSSL_IS_BORINGSSL */
7124 OPENSSL_VERSION_TEXT
7125 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007126 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007127 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007128#endif
7129 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007130#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007131 "no (library version too old)"
7132#elif defined(OPENSSL_NO_TLSEXT)
7133 "no (disabled via OPENSSL_NO_TLSEXT)"
7134#else
7135 "yes"
7136#endif
7137 "", ptr);
7138
7139 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7140#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7141 "yes"
7142#else
7143#ifdef OPENSSL_NO_TLSEXT
7144 "no (because of OPENSSL_NO_TLSEXT)"
7145#else
7146 "no (version might be too old, 0.9.8f min needed)"
7147#endif
7148#endif
7149 "", ptr);
7150
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007151 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7152 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7153 if (methodVersions[i].option)
7154 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007155
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007156 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007157}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007158
Willy Tarreau80713382018-11-26 10:19:54 +01007159INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007160
Emeric Brun46591952012-05-18 15:47:34 +02007161
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007162#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007163void ssl_free_engines(void) {
7164 struct ssl_engine_list *wl, *wlb;
7165 /* free up engine list */
7166 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7167 ENGINE_finish(wl->e);
7168 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007169 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007170 free(wl);
7171 }
7172}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007173#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007174
Remi Gacogned3a23c32015-05-28 16:39:47 +02007175#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007176void ssl_free_dh(void) {
7177 if (local_dh_1024) {
7178 DH_free(local_dh_1024);
7179 local_dh_1024 = NULL;
7180 }
7181 if (local_dh_2048) {
7182 DH_free(local_dh_2048);
7183 local_dh_2048 = NULL;
7184 }
7185 if (local_dh_4096) {
7186 DH_free(local_dh_4096);
7187 local_dh_4096 = NULL;
7188 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007189 if (global_dh) {
7190 DH_free(global_dh);
7191 global_dh = NULL;
7192 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007193}
7194#endif
7195
7196__attribute__((destructor))
7197static void __ssl_sock_deinit(void)
7198{
7199#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007200 if (ssl_ctx_lru_tree) {
7201 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007202 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007203 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007204#endif
7205
Willy Tarreau5db847a2019-05-09 14:13:35 +02007206#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007207 ERR_remove_state(0);
7208 ERR_free_strings();
7209
7210 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007211#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007212
Willy Tarreau5db847a2019-05-09 14:13:35 +02007213#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007214 CRYPTO_cleanup_all_ex_data();
7215#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007216 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007217}
7218
William Dauchyf6370442020-11-14 19:25:33 +01007219/* Activate ssl on server <s>.
7220 * do nothing if there is no change to apply
7221 *
7222 * Must be called with the server lock held.
7223 */
7224void ssl_sock_set_srv(struct server *s, signed char use_ssl)
7225{
7226 if (s->use_ssl == use_ssl)
7227 return;
7228
7229 s->use_ssl = use_ssl;
7230 if (s->use_ssl == 1)
7231 s->xprt = &ssl_sock;
7232 else
7233 s->xprt = s->check.xprt = s->agent.xprt = xprt_get(XPRT_RAW);
7234}
7235
Emeric Brun46591952012-05-18 15:47:34 +02007236/*
7237 * Local variables:
7238 * c-indent-level: 8
7239 * c-basic-offset: 8
7240 * End:
7241 */