blob: e5f6029caa657e569fbdde1080377fc0bb3dd5ea [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>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020073#include <haproxy/stats-t.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>
Emeric Brun46591952012-05-18 15:47:34 +020081
Emeric Brun46591952012-05-18 15:47:34 +020082
Willy Tarreau9356dac2019-05-10 09:22:53 +020083/* ***** READ THIS before adding code here! *****
84 *
85 * Due to API incompatibilities between multiple OpenSSL versions and their
86 * derivatives, it's often tempting to add macros to (re-)define certain
87 * symbols. Please do not do this here, and do it in common/openssl-compat.h
88 * exclusively so that the whole code consistently uses the same macros.
89 *
90 * Whenever possible if a macro is missing in certain versions, it's better
91 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
92 */
93
Willy Tarreau71b734c2014-01-28 15:19:44 +010094int sslconns = 0;
95int totalsslconns = 0;
Emeric Brunece0c332017-12-06 13:51:49 +010096int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +020097
William Lallemande0f3fd52020-02-25 14:53:06 +010098static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
99
William Lallemand7fd8b452020-05-07 15:20:43 +0200100struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100101#ifdef LISTEN_DEFAULT_CIPHERS
102 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
103#endif
104#ifdef CONNECT_DEFAULT_CIPHERS
105 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
106#endif
Emmanuel Hocdet839af572019-05-14 16:27:35 +0200107#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200108#ifdef LISTEN_DEFAULT_CIPHERSUITES
109 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
110#endif
111#ifdef CONNECT_DEFAULT_CIPHERSUITES
112 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
113#endif
114#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100115 .listen_default_ssloptions = BC_SSL_O_NONE,
116 .connect_default_ssloptions = SRV_SSL_O_NONE,
117
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200118 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
119 .listen_default_sslmethods.min = CONF_TLSV_NONE,
120 .listen_default_sslmethods.max = CONF_TLSV_NONE,
121 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
122 .connect_default_sslmethods.min = CONF_TLSV_NONE,
123 .connect_default_sslmethods.max = CONF_TLSV_NONE,
124
Willy Tarreauef934602016-12-22 23:12:01 +0100125#ifdef DEFAULT_SSL_MAX_RECORD
126 .max_record = DEFAULT_SSL_MAX_RECORD,
127#endif
128 .default_dh_param = SSL_DEFAULT_DH_PARAM,
129 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Thierry FOURNIER5bf77322017-02-25 12:45:22 +0100130 .capture_cipherlist = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100131 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200132 .extra_files_noext = 0,
William Lallemandb3246942021-06-09 16:46:12 +0200133#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200134 .keylog = 0
135#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100136};
137
Olivier Houcharda8955d52019-04-07 22:00:38 +0200138static BIO_METHOD *ha_meth;
139
Olivier Houchard66ab4982019-02-26 18:37:15 +0100140DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
141
Olivier Houchardea8dd942019-05-20 14:02:16 +0200142static struct task *ssl_sock_io_cb(struct task *, void *, unsigned short);
Willy Tarreau9a5a0e02021-01-20 14:55:01 +0100143
144/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
145struct task *ssl_sock_io_cb(struct task *, void *, unsigned short);
146
Olivier Houchard000694c2019-05-23 14:45:12 +0200147static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200148
Olivier Houcharda8955d52019-04-07 22:00:38 +0200149/* Methods to implement OpenSSL BIO */
150static int ha_ssl_write(BIO *h, const char *buf, int num)
151{
152 struct buffer tmpbuf;
153 struct ssl_sock_ctx *ctx;
154 int ret;
155
156 ctx = BIO_get_data(h);
157 tmpbuf.size = num;
158 tmpbuf.area = (void *)(uintptr_t)buf;
159 tmpbuf.data = num;
160 tmpbuf.head = 0;
161 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200162 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200163 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200164 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200165 } else if (ret == 0)
166 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200167 return ret;
168}
169
170static int ha_ssl_gets(BIO *h, char *buf, int size)
171{
172
173 return 0;
174}
175
176static int ha_ssl_puts(BIO *h, const char *str)
177{
178
179 return ha_ssl_write(h, str, strlen(str));
180}
181
182static int ha_ssl_read(BIO *h, char *buf, int size)
183{
184 struct buffer tmpbuf;
185 struct ssl_sock_ctx *ctx;
186 int ret;
187
188 ctx = BIO_get_data(h);
189 tmpbuf.size = size;
190 tmpbuf.area = buf;
191 tmpbuf.data = 0;
192 tmpbuf.head = 0;
193 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200194 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200195 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200196 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200197 } else if (ret == 0)
198 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200199
200 return ret;
201}
202
203static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
204{
205 int ret = 0;
206 switch (cmd) {
207 case BIO_CTRL_DUP:
208 case BIO_CTRL_FLUSH:
209 ret = 1;
210 break;
211 }
212 return ret;
213}
214
215static int ha_ssl_new(BIO *h)
216{
217 BIO_set_init(h, 1);
218 BIO_set_data(h, NULL);
219 BIO_clear_flags(h, ~0);
220 return 1;
221}
222
223static int ha_ssl_free(BIO *data)
224{
225
226 return 1;
227}
228
229
Willy Tarreau5db847a2019-05-09 14:13:35 +0200230#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100231
Emeric Brun821bb9b2017-06-15 16:37:39 +0200232static HA_RWLOCK_T *ssl_rwlocks;
233
234
235unsigned long ssl_id_function(void)
236{
237 return (unsigned long)tid;
238}
239
240void ssl_locking_function(int mode, int n, const char * file, int line)
241{
242 if (mode & CRYPTO_LOCK) {
243 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100244 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200245 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100246 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200247 }
248 else {
249 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100250 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200251 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100252 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200253 }
254}
255
256static int ssl_locking_init(void)
257{
258 int i;
259
260 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
261 if (!ssl_rwlocks)
262 return -1;
263
264 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100265 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200266
267 CRYPTO_set_id_callback(ssl_id_function);
268 CRYPTO_set_locking_callback(ssl_locking_function);
269
270 return 0;
271}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100272
Emeric Brun821bb9b2017-06-15 16:37:39 +0200273#endif
274
Willy Tarreauaf613e82020-06-05 08:40:51 +0200275__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200276
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100277
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200278/*
Emmanuel Hocdetb270e812019-11-21 19:09:31 +0100279 * deduplicate cafile (and crlfile)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200280 */
281struct cafile_entry {
282 X509_STORE *ca_store;
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200283 STACK_OF(X509_NAME) *ca_list;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200284 struct ebmb_node node;
285 char path[0];
286};
287
288static struct eb_root cafile_tree = EB_ROOT_UNIQUE;
289
290static X509_STORE* ssl_store_get0_locations_file(char *path)
291{
292 struct ebmb_node *eb;
293
294 eb = ebst_lookup(&cafile_tree, path);
295 if (eb) {
296 struct cafile_entry *ca_e;
297 ca_e = ebmb_entry(eb, struct cafile_entry, node);
298 return ca_e->ca_store;
299 }
300 return NULL;
301}
302
Remi Tricot-Le Bretonbcec63e2021-03-23 16:41:53 +0100303int ssl_store_load_locations_file(char *path, int create_if_none)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200304{
Remi Tricot-Le Bretonbcec63e2021-03-23 16:41:53 +0100305 X509_STORE *store = ssl_store_get0_locations_file(path);
306
307 /* If this function is called by the CLI, we should not call the
308 * X509_STORE_load_locations function because it performs forbidden disk
309 * accesses. */
310 if (!store && create_if_none) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200311 struct cafile_entry *ca_e;
Remi Tricot-Le Bretonbcec63e2021-03-23 16:41:53 +0100312 store = X509_STORE_new();
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200313 if (X509_STORE_load_locations(store, path, NULL)) {
314 int pathlen;
315 pathlen = strlen(path);
316 ca_e = calloc(1, sizeof(*ca_e) + pathlen + 1);
317 if (ca_e) {
318 memcpy(ca_e->path, path, pathlen + 1);
319 ca_e->ca_store = store;
320 ebst_insert(&cafile_tree, &ca_e->node);
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200321 }
Remi Tricot-Le Bretonbcec63e2021-03-23 16:41:53 +0100322 } else {
323 X509_STORE_free(store);
324 store = NULL;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200325 }
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200326 }
Remi Tricot-Le Bretonbcec63e2021-03-23 16:41:53 +0100327 return (store != NULL);
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200328}
329
330/* mimic what X509_STORE_load_locations do with store_ctx */
331static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
332{
333 X509_STORE *store;
334 store = ssl_store_get0_locations_file(path);
335 if (store_ctx && store) {
336 int i;
337 X509_OBJECT *obj;
338 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
339 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
340 obj = sk_X509_OBJECT_value(objs, i);
341 switch (X509_OBJECT_get_type(obj)) {
342 case X509_LU_X509:
343 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
344 break;
345 case X509_LU_CRL:
346 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
347 break;
348 default:
349 break;
350 }
351 }
352 return 1;
353 }
354 return 0;
355}
356
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500357/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200358static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
359{
360 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
361 return ssl_set_cert_crl_file(store_ctx, path);
362}
363
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200364/*
365 Extract CA_list from CA_file already in tree.
366 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
367 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
368*/
369static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
370{
371 struct ebmb_node *eb;
372 struct cafile_entry *ca_e;
373
374 eb = ebst_lookup(&cafile_tree, path);
375 if (!eb)
376 return NULL;
377 ca_e = ebmb_entry(eb, struct cafile_entry, node);
378
379 if (ca_e->ca_list == NULL) {
380 int i;
381 unsigned long key;
382 struct eb_root ca_name_tree = EB_ROOT;
383 struct eb64_node *node, *back;
384 struct {
385 struct eb64_node node;
386 X509_NAME *xname;
387 } *ca_name;
388 STACK_OF(X509_OBJECT) *objs;
389 STACK_OF(X509_NAME) *skn;
390 X509 *x;
391 X509_NAME *xn;
392
393 skn = sk_X509_NAME_new_null();
394 /* take x509 from cafile_tree */
395 objs = X509_STORE_get0_objects(ca_e->ca_store);
396 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
397 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
398 if (!x)
399 continue;
400 xn = X509_get_subject_name(x);
401 if (!xn)
402 continue;
403 /* Check for duplicates. */
404 key = X509_NAME_hash(xn);
405 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
406 node && ca_name == NULL;
407 node = eb64_next(node)) {
408 ca_name = container_of(node, typeof(*ca_name), node);
409 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
410 ca_name = NULL;
411 }
412 /* find a duplicate */
413 if (ca_name)
414 continue;
415 ca_name = calloc(1, sizeof *ca_name);
416 xn = X509_NAME_dup(xn);
417 if (!ca_name ||
418 !xn ||
419 !sk_X509_NAME_push(skn, xn)) {
420 free(ca_name);
421 X509_NAME_free(xn);
422 sk_X509_NAME_pop_free(skn, X509_NAME_free);
423 sk_X509_NAME_free(skn);
424 skn = NULL;
425 break;
426 }
427 ca_name->node.key = key;
428 ca_name->xname = xn;
429 eb64_insert(&ca_name_tree, &ca_name->node);
430 }
431 ca_e->ca_list = skn;
432 /* remove temporary ca_name tree */
433 node = eb64_first(&ca_name_tree);
434 while (node) {
435 ca_name = container_of(node, typeof(*ca_name), node);
436 back = eb64_next(node);
437 eb64_delete(node);
438 free(ca_name);
439 node = back;
440 }
441 }
442 return ca_e->ca_list;
443}
444
Willy Tarreaubafbe012017-11-24 17:34:44 +0100445struct pool_head *pool_head_ssl_capture = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200446int ssl_capture_ptr_index = -1;
Thierry FOURNIER28962c92018-06-17 21:37:05 +0200447static int ssl_app_data_index = -1;
Willy Tarreauef934602016-12-22 23:12:01 +0100448
William Lallemandb3246942021-06-09 16:46:12 +0200449#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200450int ssl_keylog_index = -1;
451struct pool_head *pool_head_ssl_keylog = NULL;
452struct pool_head *pool_head_ssl_keylog_str = NULL;
453#endif
454
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200455#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
456struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
457#endif
458
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200459#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200460unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000461struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
462struct ssl_engine_list {
463 struct list list;
464 ENGINE *e;
465};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200466#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000467
Remi Gacogne8de54152014-07-15 11:36:40 +0200468#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200469static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200470static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200471static DH *local_dh_1024 = NULL;
472static DH *local_dh_2048 = NULL;
473static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100474static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200475#endif /* OPENSSL_NO_DH */
476
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100477#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200478/* X509V3 Extensions that will be added on generated certificates */
479#define X509V3_EXT_SIZE 5
480static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
481 "basicConstraints",
482 "nsComment",
483 "subjectKeyIdentifier",
484 "authorityKeyIdentifier",
485 "keyUsage",
486};
487static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
488 "CA:FALSE",
489 "\"OpenSSL Generated Certificate\"",
490 "hash",
491 "keyid,issuer:always",
492 "nonRepudiation,digitalSignature,keyEncipherment"
493};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200494/* LRU cache to store generated certificate */
495static struct lru64_head *ssl_ctx_lru_tree = NULL;
496static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200497static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100498__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200499
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200500#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
501
yanbzhube2774d2015-12-10 15:07:30 -0500502/* The order here matters for picking a default context,
503 * keep the most common keytype at the bottom of the list
504 */
505const char *SSL_SOCK_KEYTYPE_NAMES[] = {
506 "dsa",
507 "ecdsa",
508 "rsa"
509};
yanbzhube2774d2015-12-10 15:07:30 -0500510
William Lallemandc3cd35f2017-11-28 11:04:43 +0100511static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100512static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
513
Dragan Dosen9ac98092020-05-11 15:51:45 +0200514/* Dedicated callback functions for heartbeat and clienthello.
515 */
516#ifdef TLS1_RT_HEARTBEAT
517static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
518 int content_type, const void *buf, size_t len,
519 SSL *ssl);
520#endif
521static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
522 int content_type, const void *buf, size_t len,
523 SSL *ssl);
524
William Lallemandb3246942021-06-09 16:46:12 +0200525#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200526static void ssl_init_keylog(struct connection *conn, int write_p, int version,
527 int content_type, const void *buf, size_t len,
528 SSL *ssl);
529#endif
530
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200531/* List head of all registered SSL/TLS protocol message callbacks. */
532struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
533
534/* Registers the function <func> in order to be called on SSL/TLS protocol
535 * message processing. It will return 0 if the function <func> is not set
536 * or if it fails to allocate memory.
537 */
538int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
539{
540 struct ssl_sock_msg_callback *cbk;
541
542 if (!func)
543 return 0;
544
545 cbk = calloc(1, sizeof(*cbk));
546 if (!cbk) {
547 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
548 return 0;
549 }
550
551 cbk->func = func;
552
553 LIST_ADDQ(&ssl_sock_msg_callbacks, &cbk->list);
554
555 return 1;
556}
557
Dragan Dosen9ac98092020-05-11 15:51:45 +0200558/* Used to register dedicated SSL/TLS protocol message callbacks.
559 */
560static int ssl_sock_register_msg_callbacks(void)
561{
562#ifdef TLS1_RT_HEARTBEAT
563 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
564 return ERR_ABORT;
565#endif
566 if (global_ssl.capture_cipherlist > 0) {
567 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
568 return ERR_ABORT;
569 }
William Lallemandb3246942021-06-09 16:46:12 +0200570#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200571 if (global_ssl.keylog > 0) {
572 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
573 return ERR_ABORT;
574 }
575#endif
576
Dragan Dosen9ac98092020-05-11 15:51:45 +0200577 return 0;
578}
579
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200580/* Used to free all SSL/TLS protocol message callbacks that were
581 * registered by using ssl_sock_register_msg_callback().
582 */
583static void ssl_sock_unregister_msg_callbacks(void)
584{
585 struct ssl_sock_msg_callback *cbk, *cbkback;
586
587 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
588 LIST_DEL(&cbk->list);
589 free(cbk);
590 }
591}
592
Dragan Doseneb607fe2020-05-11 17:17:06 +0200593SSL *ssl_sock_get_ssl_object(struct connection *conn)
594{
595 if (!ssl_sock_is_ssl(conn))
596 return NULL;
597
598 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
599}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100600/*
601 * This function gives the detail of the SSL error. It is used only
602 * if the debug mode and the verbose mode are activated. It dump all
603 * the SSL error until the stack was empty.
604 */
605static forceinline void ssl_sock_dump_errors(struct connection *conn)
606{
607 unsigned long ret;
608
609 if (unlikely(global.mode & MODE_DEBUG)) {
610 while(1) {
611 ret = ERR_get_error();
612 if (ret == 0)
613 return;
Willy Tarreau07451ac2021-03-02 19:32:39 +0100614 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
615 conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100616 ERR_func_error_string(ret), ERR_reason_error_string(ret));
617 }
618 }
619}
620
yanbzhube2774d2015-12-10 15:07:30 -0500621
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200622#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200623int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000624{
625 int err_code = ERR_ABORT;
626 ENGINE *engine;
627 struct ssl_engine_list *el;
628
629 /* grab the structural reference to the engine */
630 engine = ENGINE_by_id(engine_id);
631 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100632 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000633 goto fail_get;
634 }
635
636 if (!ENGINE_init(engine)) {
637 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100638 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000639 goto fail_init;
640 }
641
642 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100643 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000644 goto fail_set_method;
645 }
646
647 el = calloc(1, sizeof(*el));
Remi Tricot-Le Bretone10ab282021-05-12 17:45:21 +0200648 if (!el)
649 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000650 el->e = engine;
651 LIST_ADD(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100652 nb_engines++;
653 if (global_ssl.async)
654 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000655 return 0;
656
Remi Tricot-Le Bretone10ab282021-05-12 17:45:21 +0200657fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000658fail_set_method:
659 /* release the functional reference from ENGINE_init() */
660 ENGINE_finish(engine);
661
662fail_init:
663 /* release the structural reference from ENGINE_by_id() */
664 ENGINE_free(engine);
665
666fail_get:
667 return err_code;
668}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200669#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000670
Willy Tarreau5db847a2019-05-09 14:13:35 +0200671#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +0200672/*
673 * openssl async fd handler
674 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200675void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000676{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200677 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000678
Emeric Brun3854e012017-05-17 20:42:48 +0200679 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000680 * to poll this fd until it is requested
681 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000682 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000683 fd_cant_recv(fd);
684
685 /* crypto engine is available, let's notify the associated
686 * connection that it can pursue its processing.
687 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200688 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000689}
690
Emeric Brun3854e012017-05-17 20:42:48 +0200691/*
692 * openssl async delayed SSL_free handler
693 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200694void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000695{
696 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200697 OSSL_ASYNC_FD all_fd[32];
698 size_t num_all_fds = 0;
699 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000700
Emeric Brun3854e012017-05-17 20:42:48 +0200701 /* We suppose that the async job for a same SSL *
702 * are serialized. So if we are awake it is
703 * because the running job has just finished
704 * and we can remove all async fds safely
705 */
706 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
707 if (num_all_fds > 32) {
708 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
709 return;
710 }
711
712 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
713 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200714 fd_stop_both(all_fd[i]);
Emeric Brun3854e012017-05-17 20:42:48 +0200715
716 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000717 SSL_free(ssl);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +0100718 _HA_ATOMIC_SUB(&sslconns, 1);
719 _HA_ATOMIC_SUB(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000720}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000721/*
Emeric Brun3854e012017-05-17 20:42:48 +0200722 * function used to manage a returned SSL_ERROR_WANT_ASYNC
723 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000724 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200725static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000726{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100727 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200728 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200729 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000730 size_t num_add_fds = 0;
731 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200732 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000733
734 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
735 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200736 if (num_add_fds > 32 || num_del_fds > 32) {
737 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 +0000738 return;
739 }
740
Emeric Brun3854e012017-05-17 20:42:48 +0200741 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000742
Emeric Brun3854e012017-05-17 20:42:48 +0200743 /* We remove unused fds from the fdtab */
744 for (i=0 ; i < num_del_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200745 fd_stop_both(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000746
Emeric Brun3854e012017-05-17 20:42:48 +0200747 /* We add new fds to the fdtab */
748 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200749 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000750 }
751
Emeric Brun3854e012017-05-17 20:42:48 +0200752 num_add_fds = 0;
753 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
754 if (num_add_fds > 32) {
755 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
756 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000757 }
Emeric Brun3854e012017-05-17 20:42:48 +0200758
759 /* We activate the polling for all known async fds */
760 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000761 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200762 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000763 /* To ensure that the fd cache won't be used
764 * We'll prefer to catch a real RD event
765 * because handling an EAGAIN on this fd will
766 * result in a context switch and also
767 * some engines uses a fd in blocking mode.
768 */
769 fd_cant_recv(add_fd[i]);
770 }
Emeric Brun3854e012017-05-17 20:42:48 +0200771
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000772}
773#endif
774
William Lallemand104a7a62019-10-14 14:14:59 +0200775#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200776/*
777 * This function returns the number of seconds elapsed
778 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
779 * date presented un ASN1_GENERALIZEDTIME.
780 *
781 * In parsing error case, it returns -1.
782 */
783static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
784{
785 long epoch;
786 char *p, *end;
787 const unsigned short month_offset[12] = {
788 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
789 };
Remi Tricot-Le Breton7e8c60a2021-06-09 17:16:18 +0200790 unsigned long year, month;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200791
792 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
793
794 p = (char *)d->data;
795 end = p + d->length;
796
797 if (end - p < 4) return -1;
798 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
799 p += 4;
800 if (end - p < 2) return -1;
801 month = 10 * (p[0] - '0') + p[1] - '0';
802 if (month < 1 || month > 12) return -1;
803 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
804 We consider leap years and the current month (<marsh or not) */
805 epoch = ( ((year - 1970) * 365)
806 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
807 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
808 + month_offset[month-1]
809 ) * 24 * 60 * 60;
810 p += 2;
811 if (end - p < 2) return -1;
812 /* Add the number of seconds of completed days of current month */
813 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
814 p += 2;
815 if (end - p < 2) return -1;
816 /* Add the completed hours of the current day */
817 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
818 p += 2;
819 if (end - p < 2) return -1;
820 /* Add the completed minutes of the current hour */
821 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
822 p += 2;
823 if (p == end) return -1;
824 /* Test if there is available seconds */
825 if (p[0] < '0' || p[0] > '9')
826 goto nosec;
827 if (end - p < 2) return -1;
828 /* Add the seconds of the current minute */
829 epoch += 10 * (p[0] - '0') + p[1] - '0';
830 p += 2;
831 if (p == end) return -1;
832 /* Ignore seconds float part if present */
833 if (p[0] == '.') {
834 do {
835 if (++p == end) return -1;
836 } while (p[0] >= '0' && p[0] <= '9');
837 }
838
839nosec:
840 if (p[0] == 'Z') {
841 if (end - p != 1) return -1;
842 return epoch;
843 }
844 else if (p[0] == '+') {
845 if (end - p != 5) return -1;
846 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700847 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 +0200848 }
849 else if (p[0] == '-') {
850 if (end - p != 5) return -1;
851 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700852 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 +0200853 }
854
855 return -1;
856}
857
William Lallemand104a7a62019-10-14 14:14:59 +0200858/*
859 * struct alignment works here such that the key.key is the same as key_data
860 * Do not change the placement of key_data
861 */
862struct certificate_ocsp {
863 struct ebmb_node key;
864 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
865 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200866 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200867 long expire;
868};
869
870struct ocsp_cbk_arg {
871 int is_single;
872 int single_kt;
873 union {
874 struct certificate_ocsp *s_ocsp;
875 /*
876 * m_ocsp will have multiple entries dependent on key type
877 * Entry 0 - DSA
878 * Entry 1 - ECDSA
879 * Entry 2 - RSA
880 */
881 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
882 };
883};
884
Emeric Brun1d3865b2014-06-20 15:37:32 +0200885static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200886
887/* This function starts to check if the OCSP response (in DER format) contained
888 * in chunk 'ocsp_response' is valid (else exits on error).
889 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
890 * contained in the OCSP Response and exits on error if no match.
891 * If it's a valid OCSP Response:
892 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
893 * pointed by 'ocsp'.
894 * If 'ocsp' is NULL, the function looks up into the OCSP response's
895 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
896 * from the response) and exits on error if not found. Finally, If an OCSP response is
897 * already present in the container, it will be overwritten.
898 *
899 * Note: OCSP response containing more than one OCSP Single response is not
900 * considered valid.
901 *
902 * Returns 0 on success, 1 in error case.
903 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200904static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
905 struct certificate_ocsp *ocsp,
906 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200907{
908 OCSP_RESPONSE *resp;
909 OCSP_BASICRESP *bs = NULL;
910 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200911 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200912 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200913 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200914 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200915 int reason;
916 int ret = 1;
917
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200918 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
919 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200920 if (!resp) {
921 memprintf(err, "Unable to parse OCSP response");
922 goto out;
923 }
924
925 rc = OCSP_response_status(resp);
926 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
927 memprintf(err, "OCSP response status not successful");
928 goto out;
929 }
930
931 bs = OCSP_response_get1_basic(resp);
932 if (!bs) {
933 memprintf(err, "Failed to get basic response from OCSP Response");
934 goto out;
935 }
936
937 count_sr = OCSP_resp_count(bs);
938 if (count_sr > 1) {
939 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
940 goto out;
941 }
942
943 sr = OCSP_resp_get0(bs, 0);
944 if (!sr) {
945 memprintf(err, "Failed to get OCSP single response");
946 goto out;
947 }
948
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200949 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
950
Emeric Brun4147b2e2014-06-16 18:36:30 +0200951 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200952 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200953 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200954 goto out;
955 }
956
Emeric Brun13a6b482014-06-20 15:44:34 +0200957 if (!nextupd) {
958 memprintf(err, "OCSP single response: missing nextupdate");
959 goto out;
960 }
961
Emeric Brunc8b27b62014-06-19 14:16:17 +0200962 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200963 if (!rc) {
964 memprintf(err, "OCSP single response: no longer valid.");
965 goto out;
966 }
967
968 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200969 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +0200970 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
971 goto out;
972 }
973 }
974
975 if (!ocsp) {
976 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
977 unsigned char *p;
978
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200979 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200980 if (!rc) {
981 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
982 goto out;
983 }
984
985 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
986 memprintf(err, "OCSP single response: Certificate ID too long");
987 goto out;
988 }
989
990 p = key;
991 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200992 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200993 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
994 if (!ocsp) {
995 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
996 goto out;
997 }
998 }
999
1000 /* According to comments on "chunk_dup", the
1001 previous chunk buffer will be freed */
1002 if (!chunk_dup(&ocsp->response, ocsp_response)) {
1003 memprintf(err, "OCSP response: Memory allocation error");
1004 goto out;
1005 }
1006
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001007 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
Remi Tricot-Le Breton7e8c60a2021-06-09 17:16:18 +02001008 if (ocsp->expire < 0) {
1009 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1010 goto out;
1011 }
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001012
Emeric Brun4147b2e2014-06-16 18:36:30 +02001013 ret = 0;
1014out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001015 ERR_clear_error();
1016
Emeric Brun4147b2e2014-06-16 18:36:30 +02001017 if (bs)
1018 OCSP_BASICRESP_free(bs);
1019
1020 if (resp)
1021 OCSP_RESPONSE_free(resp);
1022
1023 return ret;
1024}
1025/*
1026 * External function use to update the OCSP response in the OCSP response's
1027 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1028 * to update in DER format.
1029 *
1030 * Returns 0 on success, 1 in error case.
1031 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001032int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001033{
1034 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1035}
1036
William Lallemand4a660132019-10-14 14:51:41 +02001037#endif
1038
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001039#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1040static 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)
1041{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001042 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001043 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001044 struct connection *conn;
1045 int head;
1046 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001047 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001048
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001049 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001050 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001051 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1052
1053 keys = ref->tlskeys;
1054 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001055
1056 if (enc) {
1057 memcpy(key_name, keys[head].name, 16);
1058
1059 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001060 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001061
Emeric Brun9e754772019-01-10 17:51:55 +01001062 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001063
Emeric Brun9e754772019-01-10 17:51:55 +01001064 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1065 goto end;
1066
Willy Tarreau9356dac2019-05-10 09:22:53 +02001067 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001068 ret = 1;
1069 }
1070 else if (ref->key_size_bits == 256 ) {
1071
1072 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1073 goto end;
1074
Willy Tarreau9356dac2019-05-10 09:22:53 +02001075 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001076 ret = 1;
1077 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001078 } else {
1079 for (i = 0; i < TLS_TICKETS_NO; i++) {
1080 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1081 goto found;
1082 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001083 ret = 0;
1084 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001085
Christopher Faulet16f45c82018-02-16 11:23:49 +01001086 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001087 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001088 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 +01001089 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1090 goto end;
1091 /* 2 for key renewal, 1 if current key is still valid */
1092 ret = i ? 2 : 1;
1093 }
1094 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001095 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 +01001096 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1097 goto end;
1098 /* 2 for key renewal, 1 if current key is still valid */
1099 ret = i ? 2 : 1;
1100 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001101 }
Emeric Brun9e754772019-01-10 17:51:55 +01001102
Christopher Faulet16f45c82018-02-16 11:23:49 +01001103 end:
1104 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1105 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001106}
1107
1108struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1109{
1110 struct tls_keys_ref *ref;
1111
1112 list_for_each_entry(ref, &tlskeys_reference, list)
1113 if (ref->filename && strcmp(filename, ref->filename) == 0)
1114 return ref;
1115 return NULL;
1116}
1117
1118struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1119{
1120 struct tls_keys_ref *ref;
1121
1122 list_for_each_entry(ref, &tlskeys_reference, list)
1123 if (ref->unique_id == unique_id)
1124 return ref;
1125 return NULL;
1126}
1127
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001128/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001129 * match existing ones, this function returns -1
1130 * else it returns 0 on success.
1131 */
1132int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001133 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001134{
Emeric Brun9e754772019-01-10 17:51:55 +01001135 if (ref->key_size_bits == 128) {
1136 if (tlskey->data != sizeof(struct tls_sess_key_128))
1137 return -1;
1138 }
1139 else if (ref->key_size_bits == 256) {
1140 if (tlskey->data != sizeof(struct tls_sess_key_256))
1141 return -1;
1142 }
1143 else
1144 return -1;
1145
Christopher Faulet16f45c82018-02-16 11:23:49 +01001146 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001147 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1148 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001149 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1150 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001151
1152 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001153}
1154
Willy Tarreau83061a82018-07-13 11:56:34 +02001155int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001156{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001157 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1158
1159 if(!ref) {
1160 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1161 return 1;
1162 }
Emeric Brun9e754772019-01-10 17:51:55 +01001163 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1164 memprintf(err, "Invalid key size");
1165 return 1;
1166 }
1167
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001168 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001169}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001170
1171/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001172 * automatic ids. It's called just after the basic checks. It returns
1173 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001174 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001175static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001176{
1177 int i = 0;
1178 struct tls_keys_ref *ref, *ref2, *ref3;
1179 struct list tkr = LIST_HEAD_INIT(tkr);
1180
1181 list_for_each_entry(ref, &tlskeys_reference, list) {
1182 if (ref->unique_id == -1) {
1183 /* Look for the first free id. */
1184 while (1) {
1185 list_for_each_entry(ref2, &tlskeys_reference, list) {
1186 if (ref2->unique_id == i) {
1187 i++;
1188 break;
1189 }
1190 }
1191 if (&ref2->list == &tlskeys_reference)
1192 break;
1193 }
1194
1195 /* Uses the unique id and increment it for the next entry. */
1196 ref->unique_id = i;
1197 i++;
1198 }
1199 }
1200
1201 /* This sort the reference list by id. */
1202 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
1203 LIST_DEL(&ref->list);
1204 list_for_each_entry(ref3, &tkr, list) {
1205 if (ref->unique_id < ref3->unique_id) {
1206 LIST_ADDQ(&ref3->list, &ref->list);
1207 break;
1208 }
1209 }
1210 if (&ref3->list == &tkr)
1211 LIST_ADDQ(&tkr, &ref->list);
1212 }
1213
1214 /* swap root */
1215 LIST_ADD(&tkr, &tlskeys_reference);
1216 LIST_DEL(&tkr);
Willy Tarreaud1c57502016-12-22 22:46:15 +01001217 return 0;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001218}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001219#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1220
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001221#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001222int ocsp_ex_index = -1;
1223
yanbzhube2774d2015-12-10 15:07:30 -05001224int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1225{
1226 switch (evp_keytype) {
1227 case EVP_PKEY_RSA:
1228 return 2;
1229 case EVP_PKEY_DSA:
1230 return 0;
1231 case EVP_PKEY_EC:
1232 return 1;
1233 }
1234
1235 return -1;
1236}
1237
Emeric Brun4147b2e2014-06-16 18:36:30 +02001238/*
1239 * Callback used to set OCSP status extension content in server hello.
1240 */
1241int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1242{
yanbzhube2774d2015-12-10 15:07:30 -05001243 struct certificate_ocsp *ocsp;
1244 struct ocsp_cbk_arg *ocsp_arg;
1245 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001246 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001247 EVP_PKEY *ssl_pkey;
1248 int key_type;
1249 int index;
1250
William Lallemand76b4a122020-08-04 17:41:39 +02001251 ctx = SSL_get_SSL_CTX(ssl);
1252 if (!ctx)
1253 return SSL_TLSEXT_ERR_NOACK;
1254
1255 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1256 if (!ocsp_arg)
1257 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001258
1259 ssl_pkey = SSL_get_privatekey(ssl);
1260 if (!ssl_pkey)
1261 return SSL_TLSEXT_ERR_NOACK;
1262
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001263 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001264
1265 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1266 ocsp = ocsp_arg->s_ocsp;
1267 else {
1268 /* For multiple certs per context, we have to find the correct OCSP response based on
1269 * the certificate type
1270 */
1271 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1272
1273 if (index < 0)
1274 return SSL_TLSEXT_ERR_NOACK;
1275
1276 ocsp = ocsp_arg->m_ocsp[index];
1277
1278 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001279
1280 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001281 !ocsp->response.area ||
1282 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001283 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001284 return SSL_TLSEXT_ERR_NOACK;
1285
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001286 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001287 if (!ssl_buf)
1288 return SSL_TLSEXT_ERR_NOACK;
1289
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001290 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1291 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001292
1293 return SSL_TLSEXT_ERR_OK;
1294}
1295
William Lallemand4a660132019-10-14 14:51:41 +02001296#endif
1297
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001298#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001299
1300
1301/*
1302 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1303 * used anymore. Also removes it from the tree if free'd.
1304 */
1305static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1306{
1307 if (!ocsp)
1308 return;
1309
1310 ocsp->refcount--;
1311 if (ocsp->refcount <= 0) {
1312 ebmb_delete(&ocsp->key);
1313 chunk_destroy(&ocsp->response);
1314 free(ocsp);
1315 }
1316}
1317
1318
Emeric Brun4147b2e2014-06-16 18:36:30 +02001319/*
1320 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001321 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1322 * status extension, the issuer's certificate is mandatory. It should be
1323 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001324 *
William Lallemand246c0242019-10-11 08:59:13 +02001325 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1326 * OCSP response. If file is empty or content is not a valid OCSP response,
1327 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1328 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001329 *
1330 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001331 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001332 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001333static 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 +02001334{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001335 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001336 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001337 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001338 struct certificate_ocsp *ocsp = NULL, *iocsp;
1339 char *warn = NULL;
1340 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001341 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001342
Emeric Brun4147b2e2014-06-16 18:36:30 +02001343
William Lallemand246c0242019-10-11 08:59:13 +02001344 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001345 if (!x)
1346 goto out;
1347
William Lallemand246c0242019-10-11 08:59:13 +02001348 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001349 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1350 if (chain) {
1351 /* check if one of the certificate of the chain is the issuer */
1352 for (i = 0; i < sk_X509_num(chain); i++) {
1353 X509 *ti = sk_X509_value(chain, i);
1354 if (X509_check_issued(ti, x) == X509_V_OK) {
1355 issuer = ti;
1356 break;
1357 }
1358 }
1359 }
William Lallemand246c0242019-10-11 08:59:13 +02001360 if (!issuer)
1361 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001362
1363 cid = OCSP_cert_to_id(0, x, issuer);
1364 if (!cid)
1365 goto out;
1366
1367 i = i2d_OCSP_CERTID(cid, NULL);
1368 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1369 goto out;
1370
Vincent Bernat02779b62016-04-03 13:48:43 +02001371 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001372 if (!ocsp)
1373 goto out;
1374
1375 p = ocsp->key_data;
1376 i2d_OCSP_CERTID(cid, &p);
1377
1378 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1379 if (iocsp == ocsp)
1380 ocsp = NULL;
1381
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001382#ifndef SSL_CTX_get_tlsext_status_cb
1383# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1384 *cb = (void (*) (void))ctx->tlsext_status_cb;
1385#endif
1386 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1387
1388 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001389 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001390 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001391
William Lallemanda560c062020-07-31 11:43:20 +02001392 cb_arg = calloc(1, sizeof(*cb_arg));
1393 if (!cb_arg)
1394 goto out;
1395
yanbzhube2774d2015-12-10 15:07:30 -05001396 cb_arg->is_single = 1;
1397 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001398 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001399
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001400 pkey = X509_get_pubkey(x);
1401 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1402 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001403
1404 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001405 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 */
1406
yanbzhube2774d2015-12-10 15:07:30 -05001407 } else {
1408 /*
1409 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1410 * Update that cb_arg with the new cert's staple
1411 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001412 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001413 struct certificate_ocsp *tmp_ocsp;
1414 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001415 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001416 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001417
William Lallemand76b4a122020-08-04 17:41:39 +02001418 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001419
1420 /*
1421 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1422 * the order of operations below matter, take care when changing it
1423 */
1424 tmp_ocsp = cb_arg->s_ocsp;
1425 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1426 cb_arg->s_ocsp = NULL;
1427 cb_arg->m_ocsp[index] = tmp_ocsp;
1428 cb_arg->is_single = 0;
1429 cb_arg->single_kt = 0;
1430
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001431 pkey = X509_get_pubkey(x);
1432 key_type = EVP_PKEY_base_id(pkey);
1433 EVP_PKEY_free(pkey);
1434
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001435 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001436 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001437 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001438 iocsp->refcount++;
1439 }
yanbzhube2774d2015-12-10 15:07:30 -05001440 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001441
1442 ret = 0;
1443
1444 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001445 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001446 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001447 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001448 }
1449
1450out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001451 if (cid)
1452 OCSP_CERTID_free(cid);
1453
1454 if (ocsp)
1455 free(ocsp);
1456
1457 if (warn)
1458 free(warn);
1459
Emeric Brun4147b2e2014-06-16 18:36:30 +02001460 return ret;
1461}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001462#endif
1463
1464#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001465static 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 +02001466{
William Lallemand4a660132019-10-14 14:51:41 +02001467 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 +02001468}
1469#endif
1470
William Lallemand4a660132019-10-14 14:51:41 +02001471
Ilya Shipitsine4f38f92021-02-06 18:55:27 +05001472#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001473
1474#define CT_EXTENSION_TYPE 18
1475
William Lallemand03c331c2020-05-13 10:10:01 +02001476int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001477
1478int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1479{
Willy Tarreau83061a82018-07-13 11:56:34 +02001480 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001481
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001482 *out = (unsigned char *) sctl->area;
1483 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001484
1485 return 1;
1486}
1487
1488int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1489{
1490 return 1;
1491}
1492
William Lallemanda17f4112019-10-10 15:16:44 +02001493static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001494{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001495 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001496
William Lallemanda17f4112019-10-10 15:16:44 +02001497 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 +01001498 goto out;
1499
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001500 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1501
1502 ret = 0;
1503
1504out:
1505 return ret;
1506}
1507
1508#endif
1509
Emeric Brune1f38db2012-09-03 20:36:47 +02001510void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1511{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001512 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001513 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001514 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001515 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001516
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001517#ifndef SSL_OP_NO_RENEGOTIATION
1518 /* Please note that BoringSSL defines this macro to zero so don't
1519 * change this to #if and do not assign a default value to this macro!
1520 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001521 if (where & SSL_CB_HANDSHAKE_START) {
1522 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001523 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 +02001524 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001525 conn->err_code = CO_ER_SSL_RENEG;
1526 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001527 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001528#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001529
1530 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001531 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001532 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001533 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001534 consider that the buffering was activated,
1535 so we rise the output buffer size from 4k
1536 to 16k */
1537 write_bio = SSL_get_wbio(ssl);
1538 if (write_bio != SSL_get_rbio(ssl)) {
1539 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001540 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001541 }
1542 }
1543 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001544}
1545
Emeric Brune64aef12012-09-21 13:15:06 +02001546/* Callback is called for each certificate of the chain during a verify
1547 ok is set to 1 if preverify detect no error on current certificate.
1548 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001549int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001550{
1551 SSL *ssl;
1552 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001553 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001554 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001555
1556 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001557 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001558
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001559 ctx = conn->xprt_ctx;
1560
1561 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001562
Emeric Brun81c00f02012-09-21 14:31:21 +02001563 if (ok) /* no errors */
1564 return ok;
1565
1566 depth = X509_STORE_CTX_get_error_depth(x_store);
1567 err = X509_STORE_CTX_get_error(x_store);
1568
1569 /* check if CA error needs to be ignored */
1570 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001571 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1572 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1573 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001574 }
1575
Willy Tarreau731248f2020-02-04 14:02:02 +01001576 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001577 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001578 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001579 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001580 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001581
Willy Tarreau20879a02012-12-03 16:32:10 +01001582 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001583 return 0;
1584 }
1585
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001586 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1587 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001588
Emeric Brun81c00f02012-09-21 14:31:21 +02001589 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001590 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001591 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001592 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001593 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001594 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001595
Willy Tarreau20879a02012-12-03 16:32:10 +01001596 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001597 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001598}
1599
Dragan Dosen9ac98092020-05-11 15:51:45 +02001600#ifdef TLS1_RT_HEARTBEAT
1601static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1602 int content_type, const void *buf, size_t len,
1603 SSL *ssl)
1604{
1605 /* test heartbeat received (write_p is set to 0
1606 for a received record) */
1607 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1608 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1609 const unsigned char *p = buf;
1610 unsigned int payload;
1611
1612 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1613
1614 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1615 if (*p != TLS1_HB_REQUEST)
1616 return;
1617
1618 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1619 goto kill_it;
1620
1621 payload = (p[1] * 256) + p[2];
1622 if (3 + payload + 16 <= len)
1623 return; /* OK no problem */
1624 kill_it:
1625 /* We have a clear heartbleed attack (CVE-2014-0160), the
1626 * advertised payload is larger than the advertised packet
1627 * length, so we have garbage in the buffer between the
1628 * payload and the end of the buffer (p+len). We can't know
1629 * if the SSL stack is patched, and we don't know if we can
1630 * safely wipe out the area between p+3+len and payload.
1631 * So instead, we prevent the response from being sent by
1632 * setting the max_send_fragment to 0 and we report an SSL
1633 * error, which will kill this connection. It will be reported
1634 * above as SSL_ERROR_SSL while an other handshake failure with
1635 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1636 */
1637 ssl->max_send_fragment = 0;
1638 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1639 }
1640}
1641#endif
1642
1643static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1644 int content_type, const void *buf, size_t len,
1645 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001646{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001647 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001648 unsigned char *msg;
1649 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001650 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001651
1652 /* This function is called for "from client" and "to server"
1653 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001654 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001655 */
1656
1657 /* "write_p" is set to 0 is the bytes are received messages,
1658 * otherwise it is set to 1.
1659 */
1660 if (write_p != 0)
1661 return;
1662
1663 /* content_type contains the type of message received or sent
1664 * according with the SSL/TLS protocol spec. This message is
1665 * encoded with one byte. The value 256 (two bytes) is used
1666 * for designing the SSL/TLS record layer. According with the
1667 * rfc6101, the expected message (other than 256) are:
1668 * - change_cipher_spec(20)
1669 * - alert(21)
1670 * - handshake(22)
1671 * - application_data(23)
1672 * - (255)
1673 * We are interessed by the handshake and specially the client
1674 * hello.
1675 */
1676 if (content_type != 22)
1677 return;
1678
1679 /* The message length is at least 4 bytes, containing the
1680 * message type and the message length.
1681 */
1682 if (len < 4)
1683 return;
1684
1685 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001686 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001687 * - hello_request(0)
1688 * - client_hello(1)
1689 * - server_hello(2)
1690 * - certificate(11)
1691 * - server_key_exchange (12)
1692 * - certificate_request(13)
1693 * - server_hello_done(14)
1694 * We are interested by the client hello.
1695 */
1696 msg = (unsigned char *)buf;
1697 if (msg[0] != 1)
1698 return;
1699
1700 /* Next three bytes are the length of the message. The total length
1701 * must be this decoded length + 4. If the length given as argument
1702 * is not the same, we abort the protocol dissector.
1703 */
1704 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1705 if (len < rec_len + 4)
1706 return;
1707 msg += 4;
1708 end = msg + rec_len;
1709 if (end < msg)
1710 return;
1711
1712 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1713 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001714 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1715 */
1716 msg += 1 + 1 + 4 + 28;
1717 if (msg > end)
1718 return;
1719
1720 /* Next, is session id:
1721 * if present, we have to jump by length + 1 for the size information
1722 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001723 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001724 if (msg[0] > 0)
1725 msg += msg[0];
1726 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001727 if (msg > end)
1728 return;
1729
1730 /* Next two bytes are the ciphersuite length. */
1731 if (msg + 2 > end)
1732 return;
1733 rec_len = (msg[0] << 8) + msg[1];
1734 msg += 2;
1735 if (msg + rec_len > end || msg + rec_len < msg)
1736 return;
1737
Willy Tarreaubafbe012017-11-24 17:34:44 +01001738 capture = pool_alloc_dirty(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001739 if (!capture)
1740 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001741 /* Compute the xxh64 of the ciphersuite. */
1742 capture->xxh64 = XXH64(msg, rec_len, 0);
1743
1744 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001745 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1746 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001747 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001748
1749 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001750}
William Lallemand7d42ef52020-07-06 11:41:30 +02001751
1752
William Lallemandb3246942021-06-09 16:46:12 +02001753#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001754static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1755 int content_type, const void *buf, size_t len,
1756 SSL *ssl)
1757{
1758 struct ssl_keylog *keylog;
1759
1760 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1761 return;
1762
1763 keylog = pool_alloc(pool_head_ssl_keylog);
1764 if (!keylog)
1765 return;
1766
1767 memset(keylog, 0, sizeof(*keylog));
1768
1769 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1770 pool_free(pool_head_ssl_keylog, keylog);
1771 return;
1772 }
1773}
1774#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001775
Emeric Brun29f037d2014-04-25 19:05:36 +02001776/* Callback is called for ssl protocol analyse */
1777void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1778{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001779 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1780 struct ssl_sock_msg_callback *cbk;
1781
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001782 /* Try to call all callback functions that were registered by using
1783 * ssl_sock_register_msg_callback().
1784 */
1785 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1786 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1787 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001788}
1789
Bernard Spil13c53f82018-02-15 13:34:58 +01001790#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001791static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1792 const unsigned char *in, unsigned int inlen,
1793 void *arg)
1794{
1795 struct server *srv = arg;
1796
1797 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1798 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1799 return SSL_TLSEXT_ERR_OK;
1800 return SSL_TLSEXT_ERR_NOACK;
1801}
1802#endif
1803
1804#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001805/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001806 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001807 */
1808static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1809 unsigned int *len, void *arg)
1810{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001811 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001812
1813 *data = (const unsigned char *)conf->npn_str;
1814 *len = conf->npn_len;
1815 return SSL_TLSEXT_ERR_OK;
1816}
1817#endif
1818
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001819#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001820/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001821 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001822 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001823static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1824 unsigned char *outlen,
1825 const unsigned char *server,
1826 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001827{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001828 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001829
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001830 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1831 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1832 return SSL_TLSEXT_ERR_NOACK;
1833 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001834 return SSL_TLSEXT_ERR_OK;
1835}
1836#endif
1837
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001838#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001839#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001840
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001841/* Configure a DNS SAN extenion on a certificate. */
1842int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1843 int failure = 0;
1844 X509_EXTENSION *san_ext = NULL;
1845 CONF *conf = NULL;
1846 struct buffer *san_name = get_trash_chunk();
1847
1848 conf = NCONF_new(NULL);
1849 if (!conf) {
1850 failure = 1;
1851 goto cleanup;
1852 }
1853
1854 /* Build an extension based on the DNS entry above */
1855 chunk_appendf(san_name, "DNS:%s", servername);
1856 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1857 if (!san_ext) {
1858 failure = 1;
1859 goto cleanup;
1860 }
1861
1862 /* Add the extension */
1863 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1864 failure = 1;
1865 goto cleanup;
1866 }
1867
1868 /* Success */
1869 failure = 0;
1870
1871cleanup:
1872 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1873 if (NULL != conf) NCONF_free(conf);
1874
1875 return failure;
1876}
1877
Christopher Faulet30548802015-06-11 13:39:32 +02001878/* Create a X509 certificate with the specified servername and serial. This
1879 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001880static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001881ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001882{
Shimi Gersner5846c492020-08-23 13:58:12 +03001883 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1884 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001885 SSL_CTX *ssl_ctx = NULL;
1886 X509 *newcrt = NULL;
1887 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001888 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001889 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001890 X509_NAME *name;
1891 const EVP_MD *digest;
1892 X509V3_CTX ctx;
1893 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001894 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001895
Christopher Faulet48a83322017-07-28 16:56:09 +02001896 /* Get the private key of the default certificate and use it */
Ilya Shipitsin842976d2020-12-19 03:12:12 +05001897#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001898 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1899#else
1900 tmp_ssl = SSL_new(bind_conf->default_ctx);
1901 if (tmp_ssl)
1902 pkey = SSL_get_privatekey(tmp_ssl);
1903#endif
1904 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001905 goto mkcert_error;
1906
1907 /* Create the certificate */
1908 if (!(newcrt = X509_new()))
1909 goto mkcert_error;
1910
1911 /* Set version number for the certificate (X509v3) and the serial
1912 * number */
1913 if (X509_set_version(newcrt, 2L) != 1)
1914 goto mkcert_error;
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01001915 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001916
1917 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001918 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1919 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001920 goto mkcert_error;
1921
1922 /* set public key in the certificate */
1923 if (X509_set_pubkey(newcrt, pkey) != 1)
1924 goto mkcert_error;
1925
1926 /* Set issuer name from the CA */
1927 if (!(name = X509_get_subject_name(cacert)))
1928 goto mkcert_error;
1929 if (X509_set_issuer_name(newcrt, name) != 1)
1930 goto mkcert_error;
1931
1932 /* Set the subject name using the same, but the CN */
1933 name = X509_NAME_dup(name);
1934 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1935 (const unsigned char *)servername,
1936 -1, -1, 0) != 1) {
1937 X509_NAME_free(name);
1938 goto mkcert_error;
1939 }
1940 if (X509_set_subject_name(newcrt, name) != 1) {
1941 X509_NAME_free(name);
1942 goto mkcert_error;
1943 }
1944 X509_NAME_free(name);
1945
1946 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001947 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001948 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1949 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1950 X509_EXTENSION *ext;
1951
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001952 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001953 goto mkcert_error;
1954 if (!X509_add_ext(newcrt, ext, -1)) {
1955 X509_EXTENSION_free(ext);
1956 goto mkcert_error;
1957 }
1958 X509_EXTENSION_free(ext);
1959 }
1960
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001961 /* Add SAN extension */
1962 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
1963 goto mkcert_error;
1964 }
1965
Christopher Faulet31af49d2015-06-09 17:29:50 +02001966 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001967
1968 key_type = EVP_PKEY_base_id(capkey);
1969
1970 if (key_type == EVP_PKEY_DSA)
1971 digest = EVP_sha1();
1972 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001973 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001974 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001975 digest = EVP_sha256();
1976 else {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02001977#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000000fL) && !defined(OPENSSL_IS_BORINGSSL)
Christopher Faulet7969a332015-10-09 11:15:03 +02001978 int nid;
1979
1980 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1981 goto mkcert_error;
1982 if (!(digest = EVP_get_digestbynid(nid)))
1983 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02001984#else
1985 goto mkcert_error;
1986#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02001987 }
1988
Christopher Faulet31af49d2015-06-09 17:29:50 +02001989 if (!(X509_sign(newcrt, capkey, digest)))
1990 goto mkcert_error;
1991
1992 /* Create and set the new SSL_CTX */
1993 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
1994 goto mkcert_error;
1995 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1996 goto mkcert_error;
1997 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
1998 goto mkcert_error;
1999 if (!SSL_CTX_check_private_key(ssl_ctx))
2000 goto mkcert_error;
2001
Shimi Gersner5846c492020-08-23 13:58:12 +03002002 /* Build chaining the CA cert and the rest of the chain, keep these order */
2003#if defined(SSL_CTX_add1_chain_cert)
2004 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2005 goto mkcert_error;
2006 }
2007
2008 if (bind_conf->ca_sign_ckch->chain) {
2009 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2010 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2011 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2012 goto mkcert_error;
2013 }
2014 }
2015 }
2016#endif
2017
Christopher Faulet31af49d2015-06-09 17:29:50 +02002018 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002019
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002020#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002021 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002022#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002023#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2024 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002025 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002026 EC_KEY *ecc;
2027 int nid;
2028
2029 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2030 goto end;
2031 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2032 goto end;
2033 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2034 EC_KEY_free(ecc);
2035 }
2036#endif
2037 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002038 return ssl_ctx;
2039
2040 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002041 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002042 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002043 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2044 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002045 return NULL;
2046}
2047
Christopher Faulet7969a332015-10-09 11:15:03 +02002048SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002049ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02002050{
Willy Tarreau07d94e42018-09-20 10:57:52 +02002051 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01002052 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002053
Olivier Houchard66ab4982019-02-26 18:37:15 +01002054 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02002055}
2056
Christopher Faulet30548802015-06-11 13:39:32 +02002057/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002058 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002059SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002060ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002061{
2062 struct lru64 *lru = NULL;
2063
2064 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002065 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002066 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002067 if (lru && lru->domain) {
2068 if (ssl)
2069 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002070 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002071 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002072 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002073 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002074 }
2075 return NULL;
2076}
2077
Emeric Brun821bb9b2017-06-15 16:37:39 +02002078/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2079 * function is not thread-safe, it should only be used to check if a certificate
2080 * exists in the lru cache (with no warranty it will not be removed by another
2081 * thread). It is kept for backward compatibility. */
2082SSL_CTX *
2083ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2084{
2085 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2086}
2087
Christopher Fauletd2cab922015-07-28 16:03:47 +02002088/* Set a certificate int the LRU cache used to store generated
2089 * certificate. Return 0 on success, otherwise -1 */
2090int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002091ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002092{
2093 struct lru64 *lru = NULL;
2094
2095 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002096 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002097 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002098 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002099 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002100 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002101 }
Christopher Faulet30548802015-06-11 13:39:32 +02002102 if (lru->domain && lru->data)
2103 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002104 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002105 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002106 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002107 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002108 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002109}
2110
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002111/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002112unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002113ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002114{
2115 return XXH32(data, len, ssl_ctx_lru_seed);
2116}
2117
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002118/* Generate a cert and immediately assign it to the SSL session so that the cert's
2119 * refcount is maintained regardless of the cert's presence in the LRU cache.
2120 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002121static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002122ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002123{
Shimi Gersner5846c492020-08-23 13:58:12 +03002124 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002125 SSL_CTX *ssl_ctx = NULL;
2126 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002127 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002128
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002129 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002130 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002131 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002132 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002133 if (lru && lru->domain)
2134 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002135 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002136 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002137 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002138 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002139 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002140 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002141 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002142 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002143 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002144 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002145 SSL_set_SSL_CTX(ssl, ssl_ctx);
2146 /* No LRU cache, this CTX will be released as soon as the session dies */
2147 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002148 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002149 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002150 return 0;
2151}
2152static int
2153ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2154{
2155 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002156 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002157
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002158 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002159 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002160 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002161 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002162 }
2163 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002164}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002165#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002166
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002167#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002168
2169static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002170{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002171#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002172 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002173 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2174#endif
2175}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002176static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2177 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002178 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2179}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002180static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002181#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002182 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002183 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2184#endif
2185}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002186static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002187#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002188 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002189 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2190#endif
2191}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002192/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002193static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2194/* Unusable in this context. */
2195static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2196static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2197static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2198static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2199static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002200#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002201
2202static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2203 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002204 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2205}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002206static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2207 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2208 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2209}
2210static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2211 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002212 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2213}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002214static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2215 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2216 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2217}
2218static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2219 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002220 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2221}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002222static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2223 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2224 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2225}
2226static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2227 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002228 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2229}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002230static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2231 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2232 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2233}
2234static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002235#if SSL_OP_NO_TLSv1_3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002236 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002237 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2238#endif
2239}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002240static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
2241#if SSL_OP_NO_TLSv1_3
2242 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2243 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002244#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002245}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002246#endif
2247static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2248static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002249
William Lallemand7fd8b452020-05-07 15:20:43 +02002250struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002251 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2252 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2253 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2254 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2255 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2256 {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 +02002257};
2258
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002259static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2260{
2261 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2262 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2263 SSL_set_SSL_CTX(ssl, ctx);
2264}
2265
Willy Tarreau5db847a2019-05-09 14:13:35 +02002266#if ((HA_OPENSSL_VERSION_NUMBER >= 0x10101000L) || defined(OPENSSL_IS_BORINGSSL))
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002267
2268static int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
2269{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002270 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002271 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002272
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002273 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2274 return SSL_TLSEXT_ERR_OK;
2275 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002276}
2277
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002278#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002279static int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
2280{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002281 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002282#else
2283static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
2284{
2285#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002286 struct connection *conn;
2287 struct bind_conf *s;
2288 const uint8_t *extension_data;
2289 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002290 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002291
2292 char *wildp = NULL;
2293 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002294 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002295 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002296 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002297 int i;
2298
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002299 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002300 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002301
Olivier Houchard9679ac92017-10-27 14:58:08 +02002302 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002303 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002304#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002305 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2306 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002307#else
2308 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2309#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002310 /*
2311 * The server_name extension was given too much extensibility when it
2312 * was written, so parsing the normal case is a bit complex.
2313 */
2314 size_t len;
2315 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002316 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002317 /* Extract the length of the supplied list of names. */
2318 len = (*extension_data++) << 8;
2319 len |= *extension_data++;
2320 if (len + 2 != extension_len)
2321 goto abort;
2322 /*
2323 * The list in practice only has a single element, so we only consider
2324 * the first one.
2325 */
2326 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2327 goto abort;
2328 extension_len = len - 1;
2329 /* Now we can finally pull out the byte array with the actual hostname. */
2330 if (extension_len <= 2)
2331 goto abort;
2332 len = (*extension_data++) << 8;
2333 len |= *extension_data++;
2334 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2335 || memchr(extension_data, 0, len) != NULL)
2336 goto abort;
2337 servername = extension_data;
2338 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002339 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002340#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2341 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002342 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002343 }
2344#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002345 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002346 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002347 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002348 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002349 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002350 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002351 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002352 goto abort;
2353 }
2354
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002355 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002356#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002357 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002358#else
2359 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2360#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002361 uint8_t sign;
2362 size_t len;
2363 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002364 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002365 len = (*extension_data++) << 8;
2366 len |= *extension_data++;
2367 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002368 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002369 if (len % 2 != 0)
2370 goto abort;
2371 for (; len > 0; len -= 2) {
2372 extension_data++; /* hash */
2373 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002374 switch (sign) {
2375 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002376 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002377 break;
2378 case TLSEXT_signature_ecdsa:
2379 has_ecdsa_sig = 1;
2380 break;
2381 default:
2382 continue;
2383 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002384 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002385 break;
2386 }
2387 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002388 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002389 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002390 }
2391 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002392 const SSL_CIPHER *cipher;
2393 size_t len;
2394 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002395 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002396#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002397 len = ctx->cipher_suites_len;
2398 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002399#else
2400 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2401#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002402 if (len % 2 != 0)
2403 goto abort;
2404 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002405#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002406 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002407 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002408#else
2409 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2410#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002411 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002412 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002413 break;
2414 }
2415 }
2416 }
2417
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002418 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002419 trash.area[i] = tolower(servername[i]);
2420 if (!wildp && (trash.area[i] == '.'))
2421 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002422 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002423 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002424
William Lallemand150bfa82019-09-19 17:12:49 +02002425 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002426
William Lallemand94bd3192020-08-14 14:43:35 +02002427 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2428 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002429 for (i = 0; i < 2; i++) {
2430 if (i == 0) /* lookup in full qualified names */
2431 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002432 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002433 node = ebst_lookup(&s->sni_w_ctx, wildp);
2434 else
2435 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002436
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002437 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002438
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002439 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002440 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002441 struct sni_ctx *sni, *sni_tmp;
2442 int skip = 0;
2443
2444 if (i == 1 && wildp) { /* wildcard */
2445 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2446 sni = container_of(n, struct sni_ctx, name);
2447 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
2448 if (sni_tmp->neg && (!strcmp((const char *)sni_tmp->name.key, trash.area))) {
2449 skip = 1;
2450 break;
2451 }
2452 }
2453 if (skip)
2454 continue;
2455 }
2456
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002457 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002458 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002459 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002460 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002461 break;
2462 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002463 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002464 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002465 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002466 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002467 if (!node_anonymous)
2468 node_anonymous = n;
2469 break;
2470 }
2471 }
2472 }
William Lallemand94bd3192020-08-14 14:43:35 +02002473 }
2474 /* Once the certificates are found, select them depending on what is
2475 * supported in the client and by key_signature priority order: EDSA >
2476 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002477 if (has_ecdsa_sig && node_ecdsa)
2478 node = node_ecdsa;
2479 else if (has_rsa_sig && node_rsa)
2480 node = node_rsa;
2481 else if (node_anonymous)
2482 node = node_anonymous;
2483 else if (node_ecdsa)
2484 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2485 else
2486 node = node_rsa; /* no rsa signature case (far far away) */
2487
William Lallemand94bd3192020-08-14 14:43:35 +02002488 if (node) {
2489 /* switch ctx */
2490 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2491 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2492 if (conf) {
2493 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2494 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2495 if (conf->early_data)
2496 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002497 }
William Lallemand94bd3192020-08-14 14:43:35 +02002498 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2499 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002500 }
William Lallemand150bfa82019-09-19 17:12:49 +02002501
William Lallemand02010472019-10-18 11:02:19 +02002502 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002503#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002504 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002505 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002506 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002507 }
2508#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002509 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002510 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002511 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002512 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002513 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002514 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02002515allow_early:
2516#ifdef OPENSSL_IS_BORINGSSL
2517 if (allow_early)
2518 SSL_set_early_data_enabled(ssl, 1);
2519#else
2520 if (!allow_early)
2521 SSL_set_max_early_data(ssl, 0);
2522#endif
2523 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002524 abort:
2525 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2526 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002527#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002528 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002529#else
2530 *al = SSL_AD_UNRECOGNIZED_NAME;
2531 return 0;
2532#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002533}
2534
2535#else /* OPENSSL_IS_BORINGSSL */
2536
Emeric Brunfc0421f2012-09-07 17:30:07 +02002537/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2538 * warning when no match is found, which implies the default (first) cert
2539 * will keep being used.
2540 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002541static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002542{
2543 const char *servername;
2544 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002545 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002546 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002547 int i;
2548 (void)al; /* shut gcc stupid warning */
2549
2550 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002551 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002552#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002553 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2554 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002555#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002556 if (s->strict_sni)
2557 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002558 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002559 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002560 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002561 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002562 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002563
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002564 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002565 if (!servername[i])
2566 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002567 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002568 if (!wildp && (trash.area[i] == '.'))
2569 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002570 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002571 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002572
William Lallemand150bfa82019-09-19 17:12:49 +02002573 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002574 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002575 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002576 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2577 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002578 if (!container_of(n, struct sni_ctx, name)->neg) {
2579 node = n;
2580 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002581 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002582 }
2583 if (!node && wildp) {
2584 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002585 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2586 /* lookup a not neg filter */
2587 if (!container_of(n, struct sni_ctx, name)->neg) {
2588 node = n;
2589 break;
2590 }
2591 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002592 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002593 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002594#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002595 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2596 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002597 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002598 return SSL_TLSEXT_ERR_OK;
2599 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002600#endif
William Lallemand21724f02019-11-04 17:56:13 +01002601 if (s->strict_sni) {
2602 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002603 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002604 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002605 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002606 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002607 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002608 }
2609
2610 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002611 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002612 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002613 return SSL_TLSEXT_ERR_OK;
2614}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002615#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002616#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2617
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002618#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002619
2620static DH * ssl_get_dh_1024(void)
2621{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002622 static unsigned char dh1024_p[]={
2623 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2624 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2625 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2626 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2627 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2628 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2629 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2630 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2631 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2632 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2633 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2634 };
2635 static unsigned char dh1024_g[]={
2636 0x02,
2637 };
2638
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002639 BIGNUM *p;
2640 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002641 DH *dh = DH_new();
2642 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002643 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2644 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002645
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002646 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002647 DH_free(dh);
2648 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002649 } else {
2650 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002651 }
2652 }
2653 return dh;
2654}
2655
2656static DH *ssl_get_dh_2048(void)
2657{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002658 static unsigned char dh2048_p[]={
2659 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2660 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2661 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2662 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2663 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2664 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2665 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2666 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2667 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2668 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2669 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2670 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2671 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2672 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2673 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2674 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2675 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2676 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2677 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2678 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2679 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2680 0xB7,0x1F,0x77,0xF3,
2681 };
2682 static unsigned char dh2048_g[]={
2683 0x02,
2684 };
2685
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002686 BIGNUM *p;
2687 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002688 DH *dh = DH_new();
2689 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002690 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2691 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002692
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002693 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002694 DH_free(dh);
2695 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002696 } else {
2697 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002698 }
2699 }
2700 return dh;
2701}
2702
2703static DH *ssl_get_dh_4096(void)
2704{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002705 static unsigned char dh4096_p[]={
2706 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2707 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2708 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2709 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2710 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2711 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2712 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2713 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2714 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2715 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2716 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2717 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2718 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2719 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2720 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2721 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2722 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2723 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2724 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2725 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2726 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2727 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2728 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2729 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2730 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2731 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2732 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2733 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2734 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2735 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2736 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2737 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2738 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2739 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2740 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2741 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2742 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2743 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2744 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2745 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2746 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2747 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2748 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002749 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002750 static unsigned char dh4096_g[]={
2751 0x02,
2752 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002753
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002754 BIGNUM *p;
2755 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002756 DH *dh = DH_new();
2757 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002758 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2759 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002760
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002761 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002762 DH_free(dh);
2763 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002764 } else {
2765 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002766 }
2767 }
2768 return dh;
2769}
2770
2771/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002772 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002773static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2774{
2775 DH *dh = NULL;
2776 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002777 int type;
2778
2779 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002780
2781 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2782 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2783 */
2784 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2785 keylen = EVP_PKEY_bits(pkey);
2786 }
2787
Willy Tarreauef934602016-12-22 23:12:01 +01002788 if (keylen > global_ssl.default_dh_param) {
2789 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002790 }
2791
Remi Gacogned3a341a2015-05-29 16:26:17 +02002792 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002793 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002794 }
2795 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002796 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002797 }
2798 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002799 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002800 }
2801
2802 return dh;
2803}
2804
Remi Gacogne47783ef2015-05-29 15:53:22 +02002805static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002806{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002807 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002808 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002809
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002810 if (in == NULL)
2811 goto end;
2812
Remi Gacogne47783ef2015-05-29 15:53:22 +02002813 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002814 goto end;
2815
Remi Gacogne47783ef2015-05-29 15:53:22 +02002816 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2817
2818end:
2819 if (in)
2820 BIO_free(in);
2821
Emeric Brune1b4ed42018-08-16 15:14:12 +02002822 ERR_clear_error();
2823
Remi Gacogne47783ef2015-05-29 15:53:22 +02002824 return dh;
2825}
2826
2827int ssl_sock_load_global_dh_param_from_file(const char *filename)
2828{
2829 global_dh = ssl_sock_get_dh_from_file(filename);
2830
2831 if (global_dh) {
2832 return 0;
2833 }
2834
2835 return -1;
2836}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002837#endif
2838
William Lallemand9117de92019-10-04 00:29:42 +02002839/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002840static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002841 struct bind_conf *s, struct ssl_bind_conf *conf,
2842 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002843{
2844 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002845 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002846
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002847 if (*name == '!') {
2848 neg = 1;
2849 name++;
2850 }
2851 if (*name == '*') {
2852 wild = 1;
2853 name++;
2854 }
2855 /* !* filter is a nop */
2856 if (neg && wild)
2857 return order;
2858 if (*name) {
2859 int j, len;
2860 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002861 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02002862 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002863 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002864 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002865 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002866
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002867 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002868 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002869 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002870 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002871 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002872 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002873 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002874 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002875 sc->order = order++;
2876 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002877 sc->wild = wild;
2878 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002879 sc->ckch_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02002880 LIST_ADDQ(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002881 }
2882 return order;
2883}
2884
William Lallemand6af03992019-07-23 15:00:54 +02002885/*
William Lallemand1d29c742019-10-04 00:53:29 +02002886 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2887 * This function can't return an error.
2888 *
2889 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2890 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002891void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002892{
2893
2894 struct sni_ctx *sc0, *sc0b, *sc1;
2895 struct ebmb_node *node;
2896
2897 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2898
2899 /* ignore if sc0 was already inserted in a tree */
2900 if (sc0->name.node.leaf_p)
2901 continue;
2902
2903 /* Check for duplicates. */
2904 if (sc0->wild)
2905 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2906 else
2907 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2908
2909 for (; node; node = ebmb_next_dup(node)) {
2910 sc1 = ebmb_entry(node, struct sni_ctx, name);
2911 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2912 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2913 /* it's a duplicate, we should remove and free it */
2914 LIST_DEL(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002915 SSL_CTX_free(sc0->ctx);
William Lallemand1d29c742019-10-04 00:53:29 +02002916 free(sc0);
2917 sc0 = NULL;
William Lallemande15029b2019-10-14 10:46:58 +02002918 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002919 }
2920 }
2921
2922 /* if duplicate, ignore the insertion */
2923 if (!sc0)
2924 continue;
2925
2926 if (sc0->wild)
2927 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
2928 else
2929 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton358a8222021-03-17 14:56:54 +01002930 }
William Lallemand21724f02019-11-04 17:56:13 +01002931
Remi Tricot-Le Breton358a8222021-03-17 14:56:54 +01002932 /* replace the default_ctx if required with the instance's ctx. */
2933 if (ckch_inst->is_default) {
2934 SSL_CTX_free(bind_conf->default_ctx);
2935 SSL_CTX_up_ref(ckch_inst->ctx);
2936 bind_conf->default_ctx = ckch_inst->ctx;
William Lallemand1d29c742019-10-04 00:53:29 +02002937 }
2938}
2939
2940/*
William Lallemande3af8fb2019-10-08 11:36:53 +02002941 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02002942 */
William Lallemande3af8fb2019-10-08 11:36:53 +02002943struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02002944
William Lallemand2954c472020-03-06 21:54:13 +01002945/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02002946struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02002947
Emeric Brun7a883362019-10-17 13:27:40 +02002948/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002949 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02002950 * DH parameter is loaded into the SSL_CTX and if there is no
2951 * DH parameter available in ckchs nor in global, the default
2952 * DH parameters are applied on the SSL_CTX.
2953 * Returns a bitfield containing the flags:
2954 * ERR_FATAL in any fatal error case
2955 * ERR_ALERT if a reason of the error is availabine in err
2956 * ERR_WARN if a warning is available into err
2957 * The value 0 means there is no error nor warning and
2958 * the operation succeed.
2959 */
William Lallemandfa892222019-07-23 16:06:08 +02002960#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02002961static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
2962 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02002963{
Emeric Brun7a883362019-10-17 13:27:40 +02002964 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02002965 DH *dh = NULL;
2966
William Lallemanda8c73742019-07-31 18:31:34 +02002967 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02002968 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02002969 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
2970 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
2971 err && *err ? *err : "", path);
2972#if defined(SSL_CTX_set_dh_auto)
2973 SSL_CTX_set_dh_auto(ctx, 1);
2974 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2975 err && *err ? *err : "");
2976#else
2977 memprintf(err, "%s, DH ciphers won't be available.\n",
2978 err && *err ? *err : "");
2979#endif
2980 ret |= ERR_WARN;
2981 goto end;
2982 }
William Lallemandfa892222019-07-23 16:06:08 +02002983
2984 if (ssl_dh_ptr_index >= 0) {
2985 /* store a pointer to the DH params to avoid complaining about
2986 ssl-default-dh-param not being set for this SSL_CTX */
2987 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
2988 }
2989 }
2990 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02002991 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
2992 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
2993 err && *err ? *err : "", path);
2994#if defined(SSL_CTX_set_dh_auto)
2995 SSL_CTX_set_dh_auto(ctx, 1);
2996 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2997 err && *err ? *err : "");
2998#else
2999 memprintf(err, "%s, DH ciphers won't be available.\n",
3000 err && *err ? *err : "");
3001#endif
3002 ret |= ERR_WARN;
3003 goto end;
3004 }
William Lallemandfa892222019-07-23 16:06:08 +02003005 }
3006 else {
3007 /* Clear openssl global errors stack */
3008 ERR_clear_error();
3009
Willy Tarreau58ee2312020-11-05 19:38:05 +01003010 if (global_ssl.default_dh_param && global_ssl.default_dh_param <= 1024) {
William Lallemandfa892222019-07-23 16:06:08 +02003011 /* we are limited to DH parameter of 1024 bits anyway */
3012 if (local_dh_1024 == NULL)
3013 local_dh_1024 = ssl_get_dh_1024();
3014
Emeric Brun7a883362019-10-17 13:27:40 +02003015 if (local_dh_1024 == NULL) {
3016 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3017 err && *err ? *err : "", path);
3018 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02003019 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02003020 }
William Lallemandfa892222019-07-23 16:06:08 +02003021
Emeric Bruna9363eb2019-10-17 14:53:03 +02003022 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
3023 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3024 err && *err ? *err : "", path);
3025#if defined(SSL_CTX_set_dh_auto)
3026 SSL_CTX_set_dh_auto(ctx, 1);
3027 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3028 err && *err ? *err : "");
3029#else
3030 memprintf(err, "%s, DH ciphers won't be available.\n",
3031 err && *err ? *err : "");
3032#endif
3033 ret |= ERR_WARN;
3034 goto end;
3035 }
William Lallemandfa892222019-07-23 16:06:08 +02003036 }
3037 else {
3038 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
3039 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003040 }
3041
William Lallemandf9568fc2019-10-16 18:27:58 +02003042end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003043 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003044 return ret;
3045}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003046#endif
William Lallemandfa892222019-07-23 16:06:08 +02003047
yanbzhu488a4d22015-12-01 15:16:07 -05003048/* Loads the info in ckch into ctx
Emeric Bruna96b5822019-10-17 13:25:14 +02003049 * Returns a bitfield containing the flags:
3050 * ERR_FATAL in any fatal error case
3051 * ERR_ALERT if the reason of the error is available in err
3052 * ERR_WARN if a warning is available into err
3053 * The value 0 means there is no error nor warning and
3054 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003055 */
3056static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3057{
Emeric Bruna96b5822019-10-17 13:25:14 +02003058 int errcode = 0;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003059 STACK_OF(X509) *find_chain = NULL;
Emeric Bruna96b5822019-10-17 13:25:14 +02003060
yanbzhu488a4d22015-12-01 15:16:07 -05003061 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3062 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3063 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003064 errcode |= ERR_ALERT | ERR_FATAL;
3065 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003066 }
3067
3068 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3069 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3070 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003071 errcode |= ERR_ALERT | ERR_FATAL;
3072 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003073 }
3074
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003075 if (ckch->chain) {
3076 find_chain = ckch->chain;
3077 } else {
3078 /* Find Certificate Chain in global */
3079 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003080 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003081 if (issuer)
3082 find_chain = issuer->chain;
3083 }
William Lallemand85888572020-02-27 14:48:35 +01003084
William Lallemand935d8292020-08-12 20:02:10 +02003085 if (!find_chain) {
3086 /* always put a null chain stack in the SSL_CTX so it does not
3087 * try to build the chain from the verify store */
3088 find_chain = sk_X509_new_null();
3089 }
3090
William Lallemandf187ce62020-06-02 18:27:20 +02003091 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003092#ifdef SSL_CTX_set1_chain
William Lallemand935d8292020-08-12 20:02:10 +02003093 if (!SSL_CTX_set1_chain(ctx, find_chain)) {
3094 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3095 err && *err ? *err : "", path);
3096 errcode |= ERR_ALERT | ERR_FATAL;
3097 goto end;
3098 }
William Lallemandf187ce62020-06-02 18:27:20 +02003099#else
3100 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003101 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02003102 STACK_OF(X509) *chain;
3103 chain = X509_chain_up_ref(find_chain);
3104 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003105 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003106 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3107 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003108 X509_free(ca);
3109 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003110 errcode |= ERR_ALERT | ERR_FATAL;
3111 goto end;
3112 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003113 }
William Lallemandf187ce62020-06-02 18:27:20 +02003114#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003115
William Lallemand9a1d8392020-08-10 17:28:23 +02003116#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003117 /* remove the Root CA from the SSL_CTX if the option is activated */
3118 if (global_ssl.skip_self_issued_ca) {
3119 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3120 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3121 err && *err ? *err : "", path);
3122 errcode |= ERR_ALERT | ERR_FATAL;
3123 goto end;
3124 }
3125 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003126#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003127
William Lallemandfa892222019-07-23 16:06:08 +02003128#ifndef OPENSSL_NO_DH
3129 /* store a NULL pointer to indicate we have not yet loaded
3130 a custom DH param file */
3131 if (ssl_dh_ptr_index >= 0) {
3132 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3133 }
3134
Emeric Brun7a883362019-10-17 13:27:40 +02003135 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3136 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003137 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3138 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003139 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003140 }
3141#endif
3142
Ilya Shipitsine4f38f92021-02-06 18:55:27 +05003143#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003144 if (sctl_ex_index >= 0 && ckch->sctl) {
3145 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3146 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003147 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003148 errcode |= ERR_ALERT | ERR_FATAL;
3149 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003150 }
3151 }
3152#endif
3153
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003154#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003155 /* Load OCSP Info into context */
3156 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003157 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003158 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",
3159 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003160 errcode |= ERR_ALERT | ERR_FATAL;
3161 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003162 }
3163 }
William Lallemand246c0242019-10-11 08:59:13 +02003164#endif
3165
Emeric Bruna96b5822019-10-17 13:25:14 +02003166 end:
3167 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003168}
3169
William Lallemand614ca0d2019-10-07 13:52:11 +02003170/*
3171 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003172 *
3173 * Returns a bitfield containing the flags:
3174 * ERR_FATAL in any fatal error case
3175 * ERR_ALERT if the reason of the error is available in err
3176 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003177 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003178int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003179 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003180{
William Lallemandc9402072019-05-15 15:33:54 +02003181 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003182 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003183 int order = 0;
3184 X509_NAME *xname;
3185 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003186 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003187 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003188#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3189 STACK_OF(GENERAL_NAME) *names;
3190#endif
William Lallemand36b84632019-07-18 19:28:17 +02003191 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003192 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003193 int errcode = 0;
3194
3195 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003196
William Lallemande3af8fb2019-10-08 11:36:53 +02003197 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003198 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003199
William Lallemande3af8fb2019-10-08 11:36:53 +02003200 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003201
William Lallemandc9402072019-05-15 15:33:54 +02003202 ctx = SSL_CTX_new(SSLv23_server_method());
3203 if (!ctx) {
3204 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3205 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003206 errcode |= ERR_ALERT | ERR_FATAL;
3207 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003208 }
3209
Emeric Bruna96b5822019-10-17 13:25:14 +02003210 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3211 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003212 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003213
3214 ckch_inst = ckch_inst_new();
3215 if (!ckch_inst) {
3216 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3217 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003218 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003219 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003220 }
3221
William Lallemand36b84632019-07-18 19:28:17 +02003222 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003223 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003224 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003225 switch(EVP_PKEY_base_id(pkey)) {
3226 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003227 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003228 break;
3229 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003230 kinfo.sig = TLSEXT_signature_ecdsa;
3231 break;
3232 case EVP_PKEY_DSA:
3233 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003234 break;
3235 }
3236 EVP_PKEY_free(pkey);
3237 }
3238
Emeric Brun50bcecc2013-04-22 13:05:23 +02003239 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003240 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003241 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 +02003242 if (order < 0) {
3243 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003244 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003245 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003246 }
3247 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003248 }
3249 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003250#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003251 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003252 if (names) {
3253 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3254 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3255 if (name->type == GEN_DNS) {
3256 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003257 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003258 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003259 if (order < 0) {
3260 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003261 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003262 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003263 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003264 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003265 }
3266 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003267 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003268 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003269#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003270 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003271 i = -1;
3272 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3273 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003274 ASN1_STRING *value;
3275
3276 value = X509_NAME_ENTRY_get_data(entry);
3277 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003278 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003279 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003280 if (order < 0) {
3281 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003282 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003283 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003284 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003285 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003286 }
3287 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003288 /* we must not free the SSL_CTX anymore below, since it's already in
3289 * the tree, so it will be discovered and cleaned in time.
3290 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003291
Emeric Brunfc0421f2012-09-07 17:30:07 +02003292#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003293 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003294 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3295 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003296 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003297 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003298 }
3299#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003300 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003301 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003302 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003303 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003304 SSL_CTX_up_ref(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003305 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003306
Remi Tricot-Le Breton358a8222021-03-17 14:56:54 +01003307 /* Always keep a reference to the newly constructed SSL_CTX in the
3308 * instance. This way if the instance has no SNIs, the SSL_CTX will
3309 * still be linked. */
3310 SSL_CTX_up_ref(ctx);
3311 ckch_inst->ctx = ctx;
3312
William Lallemand9117de92019-10-04 00:29:42 +02003313 /* everything succeed, the ckch instance can be used */
3314 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003315 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003316 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003317
William Lallemand02e19a52020-04-08 16:11:26 +02003318 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3319
Emeric Brun054563d2019-10-17 13:16:58 +02003320 *ckchi = ckch_inst;
3321 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003322
3323error:
3324 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003325 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003326 if (ckch_inst->is_default)
3327 SSL_CTX_free(ctx);
3328
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003329 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003330 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003331 }
William Lallemandd9199372019-10-04 15:37:05 +02003332 SSL_CTX_free(ctx);
3333
Emeric Brun054563d2019-10-17 13:16:58 +02003334 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003335}
3336
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003337/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003338static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3339 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003340 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003341{
Emeric Brun054563d2019-10-17 13:16:58 +02003342 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003343
3344 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003345 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 +02003346
Emeric Brun054563d2019-10-17 13:16:58 +02003347 if (errcode & ERR_CODE)
3348 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003349
William Lallemand24bde432020-03-09 16:48:43 +01003350 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003351
3352 /* succeed, add the instance to the ckch_store's list of instance */
William Lallemand24bde432020-03-09 16:48:43 +01003353 LIST_ADDQ(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003354 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003355}
3356
William Lallemand6be66ec2020-03-06 22:26:32 +01003357
William Lallemand4c68bba2020-03-30 18:45:10 +02003358
3359
3360/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3361 * done once. Zero is returned if the operation fails. No error is returned
3362 * if the random is said as not implemented, because we expect that openssl
3363 * will use another method once needed.
3364 */
3365static int ssl_initialize_random()
3366{
3367 unsigned char random;
3368 static int random_initialized = 0;
3369
3370 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3371 random_initialized = 1;
3372
3373 return random_initialized;
3374}
3375
William Lallemand2954c472020-03-06 21:54:13 +01003376/* Load a crt-list file, this is done in 2 parts:
3377 * - store the content of the file in a crtlist structure with crtlist_entry structures
3378 * - generate the instances by iterating on entries in the crtlist struct
3379 *
3380 * Nothing is locked there, this function is used in the configuration parser.
3381 *
3382 * Returns a set of ERR_* flags possibly with an error in <err>.
3383 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003384int 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 +01003385{
3386 struct crtlist *crtlist = NULL;
3387 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003388 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003389 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003390 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003391 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003392
William Lallemand79d31ec2020-03-25 15:10:49 +01003393 bind_conf_node = malloc(sizeof(*bind_conf_node));
3394 if (!bind_conf_node) {
3395 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3396 cfgerr |= ERR_FATAL | ERR_ALERT;
3397 goto error;
3398 }
3399 bind_conf_node->next = NULL;
3400 bind_conf_node->bind_conf = bind_conf;
3401
William Lallemand41ca9302020-04-08 13:15:18 +02003402 /* strip trailing slashes, including first one */
3403 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3404 *end = 0;
3405
William Lallemand2954c472020-03-06 21:54:13 +01003406 /* look for an existing crtlist or create one */
3407 eb = ebst_lookup(&crtlists_tree, file);
3408 if (eb) {
3409 crtlist = ebmb_entry(eb, struct crtlist, node);
3410 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003411 /* load a crt-list OR a directory */
3412 if (dir)
3413 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3414 else
3415 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3416
William Lallemand2954c472020-03-06 21:54:13 +01003417 if (!(cfgerr & ERR_CODE))
3418 ebst_insert(&crtlists_tree, &crtlist->node);
3419 }
3420
3421 if (cfgerr & ERR_CODE) {
3422 cfgerr |= ERR_FATAL | ERR_ALERT;
3423 goto error;
3424 }
3425
3426 /* generates ckch instance from the crtlist_entry */
3427 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3428 struct ckch_store *store;
3429 struct ckch_inst *ckch_inst = NULL;
3430
3431 store = entry->node.key;
3432 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3433 if (cfgerr & ERR_CODE) {
3434 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3435 goto error;
3436 }
William Lallemand49398312020-03-30 17:01:33 +02003437 LIST_ADDQ(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003438 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003439 }
William Lallemand2954c472020-03-06 21:54:13 +01003440
William Lallemand79d31ec2020-03-25 15:10:49 +01003441 /* add the bind_conf to the list */
3442 bind_conf_node->next = crtlist->bind_conf;
3443 crtlist->bind_conf = bind_conf_node;
3444
William Lallemand2954c472020-03-06 21:54:13 +01003445 return cfgerr;
3446error:
3447 {
William Lallemand49398312020-03-30 17:01:33 +02003448 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003449 struct ckch_inst *inst, *s_inst;
3450
William Lallemand49398312020-03-30 17:01:33 +02003451 lastentry = entry; /* which entry we tried to generate last */
3452 if (lastentry) {
3453 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3454 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3455 break;
3456
3457 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003458
William Lallemand49398312020-03-30 17:01:33 +02003459 /* this was not generated for this bind_conf, skip */
3460 if (inst->bind_conf != bind_conf)
3461 continue;
3462
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003463 /* free the sni_ctx and instance */
3464 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003465 }
William Lallemand2954c472020-03-06 21:54:13 +01003466 }
William Lallemand2954c472020-03-06 21:54:13 +01003467 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003468 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003469 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003470 return cfgerr;
3471}
3472
William Lallemand06b22a82020-03-16 14:45:55 +01003473/* Returns a set of ERR_* flags possibly with an error in <err>. */
3474int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3475{
3476 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003477 int cfgerr = 0;
3478 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003479 struct ckch_inst *ckch_inst = NULL;
William Lallemand7efbaf12020-11-20 15:36:13 +01003480 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003481
3482 if ((ckchs = ckchs_lookup(path))) {
3483 /* we found the ckchs in the tree, we can use it directly */
William Lallemand7efbaf12020-11-20 15:36:13 +01003484 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3485 found++;
3486 } else if (stat(path, &buf) == 0) {
3487 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003488 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003489 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003490 if (!ckchs)
William Lallemand7efbaf12020-11-20 15:36:13 +01003491 cfgerr |= ERR_ALERT | ERR_FATAL;
3492 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003493 } else {
William Lallemand7efbaf12020-11-20 15:36:13 +01003494 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003495 }
3496 } else {
3497 /* stat failed, could be a bundle */
3498 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003499 char fp[MAXPATHLEN+1] = {0};
3500 int n = 0;
3501
3502 /* Load all possible certs and keys in separate ckch_store */
3503 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3504 struct stat buf;
3505 int ret;
3506
3507 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3508 if (ret > sizeof(fp))
3509 continue;
3510
3511 if ((ckchs = ckchs_lookup(fp))) {
3512 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand7efbaf12020-11-20 15:36:13 +01003513 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003514 } else {
3515 if (stat(fp, &buf) == 0) {
William Lallemand7efbaf12020-11-20 15:36:13 +01003516 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003517 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003518 if (!ckchs)
William Lallemand7efbaf12020-11-20 15:36:13 +01003519 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003520 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3521 }
3522 }
3523 }
William Lallemand00b831e2020-12-04 15:45:02 +01003524#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3525 if (found) {
3526 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3527 err && *err ? *err : "", path);
3528 cfgerr |= ERR_ALERT | ERR_FATAL;
3529 }
3530#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003531 }
3532 }
William Lallemand7efbaf12020-11-20 15:36:13 +01003533 if (!found) {
3534 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3535 err && *err ? *err : "", path, strerror(errno));
3536 cfgerr |= ERR_ALERT | ERR_FATAL;
3537 }
William Lallemand06b22a82020-03-16 14:45:55 +01003538
3539 return cfgerr;
3540}
3541
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003542/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003543static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003544ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003545{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003546 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003547 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003548 SSL_OP_ALL | /* all known workarounds for bugs */
3549 SSL_OP_NO_SSLv2 |
3550 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003551 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003552 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003553 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003554 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003555 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003556 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003557 SSL_MODE_ENABLE_PARTIAL_WRITE |
3558 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003559 SSL_MODE_RELEASE_BUFFERS |
3560 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003561 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003562 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003563 int flags = MC_SSL_O_ALL;
3564 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003565 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003566
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003567 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003568 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003569
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003570 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003571 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3572 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3573 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003574 else
3575 flags = conf_ssl_methods->flags;
3576
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003577 min = conf_ssl_methods->min;
3578 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003579
3580 /* default minimum is TLSV12, */
3581 if (!min) {
3582 if (!max || (max >= default_min_ver)) {
3583 min = default_min_ver;
3584 } else {
3585 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). "
3586 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3587 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3588 min = max;
3589 }
3590 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003591 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003592 if (min)
3593 flags |= (methodVersions[min].flag - 1);
3594 if (max)
3595 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003596 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003597 min = max = CONF_TLSV_NONE;
3598 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003599 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003600 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003601 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003602 if (min) {
3603 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003604 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3605 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3606 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3607 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003608 hole = 0;
3609 }
3610 max = i;
3611 }
3612 else {
3613 min = max = i;
3614 }
3615 }
3616 else {
3617 if (min)
3618 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003619 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003620 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003621 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3622 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003623 cfgerr += 1;
3624 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003625 /* save real min/max in bind_conf */
3626 conf_ssl_methods->min = min;
3627 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003628
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003629#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003630 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003631 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003632 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003633 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003634 else
William Lallemandd0712f32020-06-11 17:34:00 +02003635 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
3636 /* clear every version flags in case SSL_CTX_new()
3637 * returns an SSL_CTX with disabled versions */
3638 SSL_CTX_clear_options(ctx, methodVersions[i].option);
3639
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003640 if (flags & methodVersions[i].flag)
3641 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02003642
3643 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003644#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003645 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003646 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3647 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003648#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003649
3650 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3651 options |= SSL_OP_NO_TICKET;
3652 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3653 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003654
3655#ifdef SSL_OP_NO_RENEGOTIATION
3656 options |= SSL_OP_NO_RENEGOTIATION;
3657#endif
3658
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003659 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003660
Willy Tarreau5db847a2019-05-09 14:13:35 +02003661#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003662 if (global_ssl.async)
3663 mode |= SSL_MODE_ASYNC;
3664#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003665 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003666 if (global_ssl.life_time)
3667 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003668
3669#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3670#ifdef OPENSSL_IS_BORINGSSL
3671 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3672 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003673#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003674 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003675 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003676 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3677 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003678#else
3679 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003680#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003681 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003682#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003683 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003684}
3685
William Lallemand4f45bb92017-10-30 20:08:51 +01003686
3687static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3688{
3689 if (first == block) {
3690 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3691 if (first->len > 0)
3692 sh_ssl_sess_tree_delete(sh_ssl_sess);
3693 }
3694}
3695
3696/* return first block from sh_ssl_sess */
3697static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3698{
3699 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3700
3701}
3702
3703/* store a session into the cache
3704 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3705 * data: asn1 encoded session
3706 * data_len: asn1 encoded session length
3707 * Returns 1 id session was stored (else 0)
3708 */
3709static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3710{
3711 struct shared_block *first;
3712 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3713
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003714 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003715 if (!first) {
3716 /* Could not retrieve enough free blocks to store that session */
3717 return 0;
3718 }
3719
3720 /* STORE the key in the first elem */
3721 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3722 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3723 first->len = sizeof(struct sh_ssl_sess_hdr);
3724
3725 /* it returns the already existing node
3726 or current node if none, never returns null */
3727 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3728 if (oldsh_ssl_sess != sh_ssl_sess) {
3729 /* NOTE: Row couldn't be in use because we lock read & write function */
3730 /* release the reserved row */
3731 shctx_row_dec_hot(ssl_shctx, first);
3732 /* replace the previous session already in the tree */
3733 sh_ssl_sess = oldsh_ssl_sess;
3734 /* ignore the previous session data, only use the header */
3735 first = sh_ssl_sess_first_block(sh_ssl_sess);
3736 shctx_row_inc_hot(ssl_shctx, first);
3737 first->len = sizeof(struct sh_ssl_sess_hdr);
3738 }
3739
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003740 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01003741 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003742 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01003743 }
3744
3745 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003746
3747 return 1;
3748}
William Lallemanded0b5ad2017-10-30 19:36:36 +01003749
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003750/* SSL callback used when a new session is created while connecting to a server */
3751static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
3752{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02003753 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003754 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003755
Willy Tarreau07d94e42018-09-20 10:57:52 +02003756 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003757
Olivier Houcharde6060c52017-11-16 17:42:52 +01003758 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
3759 int len;
3760 unsigned char *ptr;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003761
Olivier Houcharde6060c52017-11-16 17:42:52 +01003762 len = i2d_SSL_SESSION(sess, NULL);
3763 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
3764 ptr = s->ssl_ctx.reused_sess[tid].ptr;
3765 } else {
3766 free(s->ssl_ctx.reused_sess[tid].ptr);
3767 ptr = s->ssl_ctx.reused_sess[tid].ptr = malloc(len);
3768 s->ssl_ctx.reused_sess[tid].allocated_size = len;
3769 }
3770 if (s->ssl_ctx.reused_sess[tid].ptr) {
3771 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
3772 &ptr);
3773 }
3774 } else {
3775 free(s->ssl_ctx.reused_sess[tid].ptr);
3776 s->ssl_ctx.reused_sess[tid].ptr = NULL;
3777 }
3778
3779 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003780}
3781
Olivier Houcharde6060c52017-11-16 17:42:52 +01003782
William Lallemanded0b5ad2017-10-30 19:36:36 +01003783/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01003784int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003785{
3786 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
3787 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
3788 unsigned char *p;
3789 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02003790 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003791 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003792
3793 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003794 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02003795 * note: SSL_SESSION_set1_id is using
3796 * a memcpy so we need to use a different pointer
3797 * than sid_data or sid_ctx_data to avoid valgrind
3798 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01003799 */
3800
3801 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02003802
3803 /* copy value in an other buffer */
3804 memcpy(encid, sid_data, sid_length);
3805
3806 /* pad with 0 */
3807 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
3808 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
3809
3810 /* force length to zero to avoid ASN1 encoding */
3811 SSL_SESSION_set1_id(sess, encid, 0);
3812
3813 /* force length to zero to avoid ASN1 encoding */
3814 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003815
3816 /* check if buffer is large enough for the ASN1 encoded session */
3817 data_len = i2d_SSL_SESSION(sess, NULL);
3818 if (data_len > SHSESS_MAX_DATA_LEN)
3819 goto err;
3820
3821 p = encsess;
3822
3823 /* process ASN1 session encoding before the lock */
3824 i2d_SSL_SESSION(sess, &p);
3825
William Lallemanded0b5ad2017-10-30 19:36:36 +01003826
William Lallemanda3c77cf2017-10-30 23:44:40 +01003827 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003828 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003829 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01003830 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003831err:
3832 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02003833 SSL_SESSION_set1_id(sess, encid, sid_length);
3834 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003835
3836 return 0; /* do not increment session reference count */
3837}
3838
3839/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003840SSL_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 +01003841{
William Lallemand4f45bb92017-10-30 20:08:51 +01003842 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003843 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
3844 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01003845 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01003846 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003847
Willy Tarreau0123d482021-06-15 16:39:22 +02003848 _HA_ATOMIC_ADD(&global.shctx_lookups, 1);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003849
3850 /* allow the session to be freed automatically by openssl */
3851 *do_copy = 0;
3852
3853 /* tree key is zeros padded sessionid */
3854 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3855 memcpy(tmpkey, key, key_len);
3856 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
3857 key = tmpkey;
3858 }
3859
3860 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003861 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003862
3863 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003864 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
3865 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003866 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003867 shctx_unlock(ssl_shctx);
Willy Tarreau0123d482021-06-15 16:39:22 +02003868 _HA_ATOMIC_ADD(&global.shctx_misses, 1);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003869 return NULL;
3870 }
3871
William Lallemand4f45bb92017-10-30 20:08:51 +01003872 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
3873 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003874
William Lallemand4f45bb92017-10-30 20:08:51 +01003875 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 +01003876
William Lallemanda3c77cf2017-10-30 23:44:40 +01003877 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003878
3879 /* decode ASN1 session */
3880 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01003881 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003882 /* Reset session id and session id contenxt */
3883 if (sess) {
3884 SSL_SESSION_set1_id(sess, key, key_len);
3885 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
3886 }
3887
3888 return sess;
3889}
3890
William Lallemand4f45bb92017-10-30 20:08:51 +01003891
William Lallemanded0b5ad2017-10-30 19:36:36 +01003892/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003893void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003894{
William Lallemand4f45bb92017-10-30 20:08:51 +01003895 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003896 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
3897 unsigned int sid_length;
3898 const unsigned char *sid_data;
3899 (void)ctx;
3900
3901 sid_data = SSL_SESSION_get_id(sess, &sid_length);
3902 /* tree key is zeros padded sessionid */
3903 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3904 memcpy(tmpkey, sid_data, sid_length);
3905 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
3906 sid_data = tmpkey;
3907 }
3908
William Lallemanda3c77cf2017-10-30 23:44:40 +01003909 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003910
3911 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003912 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
3913 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003914 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003915 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003916 }
3917
3918 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003919 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003920}
3921
3922/* Set session cache mode to server and disable openssl internal cache.
3923 * Set shared cache callbacks on an ssl context.
3924 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01003925void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003926{
3927 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
3928
3929 if (!ssl_shctx) {
3930 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
3931 return;
3932 }
3933
3934 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
3935 SSL_SESS_CACHE_NO_INTERNAL |
3936 SSL_SESS_CACHE_NO_AUTO_CLEAR);
3937
3938 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01003939 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
3940 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
3941 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003942}
William Lallemand7d42ef52020-07-06 11:41:30 +02003943
3944/*
3945 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
3946 *
3947 * The format is:
3948 * * <Label> <space> <ClientRandom> <space> <Secret>
3949 * We only need to copy the secret as there is a sample fetch for the ClientRandom
3950 */
3951
William Lallemandb3246942021-06-09 16:46:12 +02003952#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02003953void SSL_CTX_keylog(const SSL *ssl, const char *line)
3954{
3955 struct ssl_keylog *keylog;
3956 char *lastarg = NULL;
3957 char *dst = NULL;
3958
3959 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
3960 if (!keylog)
3961 return;
3962
3963 lastarg = strrchr(line, ' ');
3964 if (lastarg == NULL || ++lastarg == NULL)
3965 return;
3966
3967 dst = pool_alloc(pool_head_ssl_keylog_str);
3968 if (!dst)
3969 return;
3970
3971 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
3972 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
3973
3974 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
3975 if (keylog->client_random)
3976 goto error;
3977 keylog->client_random = dst;
3978
3979 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
3980 if (keylog->client_early_traffic_secret)
3981 goto error;
3982 keylog->client_early_traffic_secret = dst;
3983
3984 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
3985 if(keylog->client_handshake_traffic_secret)
3986 goto error;
3987 keylog->client_handshake_traffic_secret = dst;
3988
3989 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
3990 if (keylog->server_handshake_traffic_secret)
3991 goto error;
3992 keylog->server_handshake_traffic_secret = dst;
3993
3994 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
3995 if (keylog->client_traffic_secret_0)
3996 goto error;
3997 keylog->client_traffic_secret_0 = dst;
3998
3999 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4000 if (keylog->server_traffic_secret_0)
4001 goto error;
4002 keylog->server_traffic_secret_0 = dst;
4003
4004 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4005 if (keylog->early_exporter_secret)
4006 goto error;
4007 keylog->early_exporter_secret = dst;
4008
4009 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4010 if (keylog->exporter_secret)
4011 goto error;
4012 keylog->exporter_secret = dst;
4013 } else {
4014 goto error;
4015 }
4016
4017 return;
4018
4019error:
4020 pool_free(pool_head_ssl_keylog_str, dst);
4021
4022 return;
4023}
4024#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004025
William Lallemand8b453912019-11-21 15:48:10 +01004026/*
4027 * This function applies the SSL configuration on a SSL_CTX
4028 * It returns an error code and fills the <err> buffer
4029 */
4030int 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 +01004031{
4032 struct proxy *curproxy = bind_conf->frontend;
4033 int cfgerr = 0;
4034 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004035 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004036 const char *conf_ciphers;
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004037#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004038 const char *conf_ciphersuites;
4039#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004040 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004041
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004042 if (ssl_conf) {
4043 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4044 int i, min, max;
4045 int flags = MC_SSL_O_ALL;
4046
4047 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004048 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4049 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004050 if (min)
4051 flags |= (methodVersions[min].flag - 1);
4052 if (max)
4053 flags |= ~((methodVersions[max].flag << 1) - 1);
4054 min = max = CONF_TLSV_NONE;
4055 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4056 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4057 if (min)
4058 max = i;
4059 else
4060 min = max = i;
4061 }
4062 /* save real min/max */
4063 conf_ssl_methods->min = min;
4064 conf_ssl_methods->max = max;
4065 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004066 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4067 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004068 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004069 }
4070 }
4071
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004072 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004073 case SSL_SOCK_VERIFY_NONE:
4074 verify = SSL_VERIFY_NONE;
4075 break;
4076 case SSL_SOCK_VERIFY_OPTIONAL:
4077 verify = SSL_VERIFY_PEER;
4078 break;
4079 case SSL_SOCK_VERIFY_REQUIRED:
4080 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4081 break;
4082 }
4083 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4084 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004085 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 +01004086 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 +01004087 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 +01004088 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004089 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004090 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004091 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004092 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004093 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004094 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004095 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4096 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4097 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4098 cfgerr |= ERR_ALERT | ERR_FATAL;
4099 }
4100 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004101 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004102 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 +02004103 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004104 }
Emeric Brun850efd52014-01-29 12:24:34 +01004105 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004106 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4107 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004108 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004109 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004110#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004111 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004112 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4113
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004114 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004115 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4116 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004117 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004118 }
Emeric Brun561e5742012-10-02 15:20:55 +02004119 else {
4120 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4121 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004122 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004123#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004124 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004125 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004126#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004127 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004128 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004129 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4130 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004131 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004132 }
4133 }
4134#endif
4135
William Lallemand4f45bb92017-10-30 20:08:51 +01004136 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004137 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4138 if (conf_ciphers &&
4139 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004140 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4141 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004142 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004143 }
4144
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004145#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004146 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4147 if (conf_ciphersuites &&
4148 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004149 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4150 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004151 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004152 }
4153#endif
4154
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004155#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004156 /* If tune.ssl.default-dh-param has not been set,
4157 neither has ssl-default-dh-file and no static DH
4158 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004159 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004160 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004161 (ssl_dh_ptr_index == -1 ||
4162 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004163 /* default to dh-param 2048 */
4164 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004165 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004166
Willy Tarreauef934602016-12-22 23:12:01 +01004167 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004168 if (local_dh_1024 == NULL) {
4169 local_dh_1024 = ssl_get_dh_1024();
4170 }
Willy Tarreauef934602016-12-22 23:12:01 +01004171 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004172 if (local_dh_2048 == NULL) {
4173 local_dh_2048 = ssl_get_dh_2048();
4174 }
Willy Tarreauef934602016-12-22 23:12:01 +01004175 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004176 if (local_dh_4096 == NULL) {
4177 local_dh_4096 = ssl_get_dh_4096();
4178 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004179 }
4180 }
4181 }
4182#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004183
Emeric Brunfc0421f2012-09-07 17:30:07 +02004184 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsinbcc25602021-02-08 16:55:06 +05004185#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004186 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004187#endif
William Lallemandb3246942021-06-09 16:46:12 +02004188#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004189 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
4190#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004191
Bernard Spil13c53f82018-02-15 13:34:58 +01004192#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004193 ssl_conf_cur = NULL;
4194 if (ssl_conf && ssl_conf->npn_str)
4195 ssl_conf_cur = ssl_conf;
4196 else if (bind_conf->ssl_conf.npn_str)
4197 ssl_conf_cur = &bind_conf->ssl_conf;
4198 if (ssl_conf_cur)
4199 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004200#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004201#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004202 ssl_conf_cur = NULL;
4203 if (ssl_conf && ssl_conf->alpn_str)
4204 ssl_conf_cur = ssl_conf;
4205 else if (bind_conf->ssl_conf.alpn_str)
4206 ssl_conf_cur = &bind_conf->ssl_conf;
4207 if (ssl_conf_cur)
4208 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004209#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004210#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004211 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4212 if (conf_curves) {
4213 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004214 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4215 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004216 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004217 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004218 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004219 }
4220#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004221#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004222 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004223 int i;
4224 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004225#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004226 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004227 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4228 NULL);
4229
4230 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004231 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004232 return cfgerr;
4233 }
4234#else
4235 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4236 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4237 ECDHE_DEFAULT_CURVE);
4238#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004239
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004240 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004241 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004242 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4243 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004244 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004245 }
4246 else {
4247 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4248 EC_KEY_free(ecdh);
4249 }
4250 }
4251#endif
4252
Emeric Brunfc0421f2012-09-07 17:30:07 +02004253 return cfgerr;
4254}
4255
Evan Broderbe554312013-06-27 00:05:25 -07004256static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4257{
4258 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4259 size_t prefixlen, suffixlen;
4260
4261 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004262 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004263 return 1;
4264
Evan Broderbe554312013-06-27 00:05:25 -07004265 /* The rest of this logic is based on RFC 6125, section 6.4.3
4266 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4267
Emeric Bruna848dae2013-10-08 11:27:28 +02004268 pattern_wildcard = NULL;
4269 pattern_left_label_end = pattern;
4270 while (*pattern_left_label_end != '.') {
4271 switch (*pattern_left_label_end) {
4272 case 0:
4273 /* End of label not found */
4274 return 0;
4275 case '*':
4276 /* If there is more than one wildcards */
4277 if (pattern_wildcard)
4278 return 0;
4279 pattern_wildcard = pattern_left_label_end;
4280 break;
4281 }
4282 pattern_left_label_end++;
4283 }
4284
4285 /* If it's not trivial and there is no wildcard, it can't
4286 * match */
4287 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004288 return 0;
4289
4290 /* Make sure all labels match except the leftmost */
4291 hostname_left_label_end = strchr(hostname, '.');
4292 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004293 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004294 return 0;
4295
4296 /* Make sure the leftmost label of the hostname is long enough
4297 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004298 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004299 return 0;
4300
4301 /* Finally compare the string on either side of the
4302 * wildcard */
4303 prefixlen = pattern_wildcard - pattern;
4304 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004305 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4306 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004307 return 0;
4308
4309 return 1;
4310}
4311
4312static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4313{
4314 SSL *ssl;
4315 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004316 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004317 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004318 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004319
4320 int depth;
4321 X509 *cert;
4322 STACK_OF(GENERAL_NAME) *alt_names;
4323 int i;
4324 X509_NAME *cert_subject;
4325 char *str;
4326
4327 if (ok == 0)
4328 return ok;
4329
4330 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004331 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004332 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004333
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004334 /* We're checking if the provided hostnames match the desired one. The
4335 * desired hostname comes from the SNI we presented if any, or if not
4336 * provided then it may have been explicitly stated using a "verifyhost"
4337 * directive. If neither is set, we don't care about the name so the
4338 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004339 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004340 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004341 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004342 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004343 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004344 if (!servername)
4345 return ok;
4346 }
Evan Broderbe554312013-06-27 00:05:25 -07004347
4348 /* We only need to verify the CN on the actual server cert,
4349 * not the indirect CAs */
4350 depth = X509_STORE_CTX_get_error_depth(ctx);
4351 if (depth != 0)
4352 return ok;
4353
4354 /* At this point, the cert is *not* OK unless we can find a
4355 * hostname match */
4356 ok = 0;
4357
4358 cert = X509_STORE_CTX_get_current_cert(ctx);
4359 /* It seems like this might happen if verify peer isn't set */
4360 if (!cert)
4361 return ok;
4362
4363 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4364 if (alt_names) {
4365 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4366 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4367 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004368#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004369 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4370#else
Evan Broderbe554312013-06-27 00:05:25 -07004371 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004372#endif
Evan Broderbe554312013-06-27 00:05:25 -07004373 ok = ssl_sock_srv_hostcheck(str, servername);
4374 OPENSSL_free(str);
4375 }
4376 }
4377 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004378 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004379 }
4380
4381 cert_subject = X509_get_subject_name(cert);
4382 i = -1;
4383 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4384 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004385 ASN1_STRING *value;
4386 value = X509_NAME_ENTRY_get_data(entry);
4387 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004388 ok = ssl_sock_srv_hostcheck(str, servername);
4389 OPENSSL_free(str);
4390 }
4391 }
4392
Willy Tarreau71d058c2017-07-26 20:09:56 +02004393 /* report the mismatch and indicate if SNI was used or not */
4394 if (!ok && !conn->err_code)
4395 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004396 return ok;
4397}
4398
Emeric Brun94324a42012-10-11 14:00:19 +02004399/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004400int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004401{
Willy Tarreau03209342016-12-22 17:08:28 +01004402 struct proxy *curproxy = srv->proxy;
Emeric Brun94324a42012-10-11 14:00:19 +02004403 int cfgerr = 0;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004404 long options =
Emeric Brun94324a42012-10-11 14:00:19 +02004405 SSL_OP_ALL | /* all known workarounds for bugs */
4406 SSL_OP_NO_SSLv2 |
4407 SSL_OP_NO_COMPRESSION;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004408 long mode =
Emeric Brun94324a42012-10-11 14:00:19 +02004409 SSL_MODE_ENABLE_PARTIAL_WRITE |
4410 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004411 SSL_MODE_RELEASE_BUFFERS |
4412 SSL_MODE_SMALL_BUFFERS;
Emeric Brun850efd52014-01-29 12:24:34 +01004413 int verify = SSL_VERIFY_NONE;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004414 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004415 struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004416 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004417 int flags = MC_SSL_O_ALL;
Emeric Brun94324a42012-10-11 14:00:19 +02004418
Thierry Fournier383085f2013-01-24 14:15:43 +01004419 /* Make sure openssl opens /dev/urandom before the chroot */
4420 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004421 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004422 cfgerr++;
4423 }
4424
Willy Tarreaufce03112015-01-15 21:32:40 +01004425 /* Automatic memory computations need to know we use SSL there */
4426 global.ssl_used_backend = 1;
4427
4428 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004429 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004430 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004431 ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4432 curproxy->id, srv->id,
4433 srv->conf.file, srv->conf.line);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004434 cfgerr++;
4435 return cfgerr;
4436 }
4437 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004438 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004439 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004440
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004441 ctx = SSL_CTX_new(SSLv23_client_method());
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004442 if (!ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004443 ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4444 proxy_type_str(curproxy), curproxy->id,
4445 srv->id);
Emeric Brun94324a42012-10-11 14:00:19 +02004446 cfgerr++;
4447 return cfgerr;
4448 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004449
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004450 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004451 ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4452 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4453 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004454 else
4455 flags = conf_ssl_methods->flags;
4456
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004457 /* Real min and max should be determinate with configuration and openssl's capabilities */
4458 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004459 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004460 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004461 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004462
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004463 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004464 min = max = CONF_TLSV_NONE;
4465 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004466 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004467 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004468 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004469 if (min) {
4470 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004471 ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4472 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4473 proxy_type_str(curproxy), curproxy->id, srv->id,
4474 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004475 hole = 0;
4476 }
4477 max = i;
4478 }
4479 else {
4480 min = max = i;
4481 }
4482 }
4483 else {
4484 if (min)
4485 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004486 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004487 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004488 ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4489 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004490 cfgerr += 1;
4491 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004492
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004493#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004494 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004495 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004496 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004497 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004498 else
4499 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4500 if (flags & methodVersions[i].flag)
4501 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004502#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004503 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004504 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4505 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004506#endif
4507
4508 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4509 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004510 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004511
Willy Tarreau5db847a2019-05-09 14:13:35 +02004512#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004513 if (global_ssl.async)
4514 mode |= SSL_MODE_ASYNC;
4515#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004516 SSL_CTX_set_mode(ctx, mode);
4517 srv->ssl_ctx.ctx = ctx;
4518
Emeric Bruna7aa3092012-10-26 12:58:00 +02004519 if (srv->ssl_ctx.client_crt) {
4520 if (SSL_CTX_use_PrivateKey_file(srv->ssl_ctx.ctx, srv->ssl_ctx.client_crt, SSL_FILETYPE_PEM) <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004521 ha_alert("config : %s '%s', server '%s': unable to load SSL private key from PEM file '%s'.\n",
4522 proxy_type_str(curproxy), curproxy->id,
4523 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004524 cfgerr++;
4525 }
4526 else if (SSL_CTX_use_certificate_chain_file(srv->ssl_ctx.ctx, srv->ssl_ctx.client_crt) <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004527 ha_alert("config : %s '%s', server '%s': unable to load ssl certificate from PEM file '%s'.\n",
4528 proxy_type_str(curproxy), curproxy->id,
4529 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004530 cfgerr++;
4531 }
4532 else if (SSL_CTX_check_private_key(srv->ssl_ctx.ctx) <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004533 ha_alert("config : %s '%s', server '%s': inconsistencies between private key and certificate loaded from PEM file '%s'.\n",
4534 proxy_type_str(curproxy), curproxy->id,
4535 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004536 cfgerr++;
4537 }
4538 }
Emeric Brun94324a42012-10-11 14:00:19 +02004539
Emeric Brun850efd52014-01-29 12:24:34 +01004540 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4541 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004542 switch (srv->ssl_ctx.verify) {
4543 case SSL_SOCK_VERIFY_NONE:
4544 verify = SSL_VERIFY_NONE;
4545 break;
4546 case SSL_SOCK_VERIFY_REQUIRED:
4547 verify = SSL_VERIFY_PEER;
4548 break;
4549 }
Evan Broderbe554312013-06-27 00:05:25 -07004550 SSL_CTX_set_verify(srv->ssl_ctx.ctx,
Emeric Brun850efd52014-01-29 12:24:34 +01004551 verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004552 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004553 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004554 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004555 /* set CAfile to verify */
4556 if (!ssl_set_verify_locations_file(srv->ssl_ctx.ctx, srv->ssl_ctx.ca_file)) {
4557 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to set CA file '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004558 curproxy->id, srv->id,
4559 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004560 cfgerr++;
4561 }
4562 }
Emeric Brun850efd52014-01-29 12:24:34 +01004563 else {
4564 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Christopher Faulet767a84b2017-11-24 16:50:31 +01004565 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",
4566 curproxy->id, srv->id,
4567 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004568 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01004569 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4570 curproxy->id, srv->id,
4571 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004572 cfgerr++;
4573 }
Emeric Brunef42d922012-10-11 16:11:36 +02004574#ifdef X509_V_FLAG_CRL_CHECK
4575 if (srv->ssl_ctx.crl_file) {
4576 X509_STORE *store = SSL_CTX_get_cert_store(srv->ssl_ctx.ctx);
4577
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004578 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004579 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4580 curproxy->id, srv->id,
4581 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004582 cfgerr++;
4583 }
4584 else {
4585 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4586 }
4587 }
4588#endif
4589 }
4590
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004591 SSL_CTX_set_session_cache_mode(srv->ssl_ctx.ctx, SSL_SESS_CACHE_CLIENT |
4592 SSL_SESS_CACHE_NO_INTERNAL_STORE);
4593 SSL_CTX_sess_set_new_cb(srv->ssl_ctx.ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004594 if (srv->ssl_ctx.ciphers &&
4595 !SSL_CTX_set_cipher_list(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphers)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004596 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4597 curproxy->id, srv->id,
4598 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004599 cfgerr++;
4600 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004601
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004602#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004603 if (srv->ssl_ctx.ciphersuites &&
Pierre Cheynierbc34cd12019-03-21 16:15:47 +00004604 !SSL_CTX_set_ciphersuites(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphersuites)) {
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004605 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4606 curproxy->id, srv->id,
4607 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4608 cfgerr++;
4609 }
4610#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004611#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4612 if (srv->ssl_ctx.npn_str)
4613 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, srv);
4614#endif
4615#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4616 if (srv->ssl_ctx.alpn_str)
4617 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4618#endif
4619
Emeric Brun94324a42012-10-11 14:00:19 +02004620
4621 return cfgerr;
4622}
4623
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004624/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004625 * be NULL, in which case nothing is done. Returns the number of errors
4626 * encountered.
4627 */
Willy Tarreau03209342016-12-22 17:08:28 +01004628int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004629{
4630 struct ebmb_node *node;
4631 struct sni_ctx *sni;
4632 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004633 int errcode = 0;
4634 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004635
Willy Tarreaufce03112015-01-15 21:32:40 +01004636 /* Automatic memory computations need to know we use SSL there */
4637 global.ssl_used_frontend = 1;
4638
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004639 /* Make sure openssl opens /dev/urandom before the chroot */
4640 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004641 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004642 err++;
4643 }
4644 /* Create initial_ctx used to start the ssl connection before do switchctx */
4645 if (!bind_conf->initial_ctx) {
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004646 err += ssl_sock_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004647 /* It should not be necessary to call this function, but it's
4648 necessary first to check and move all initialisation related
4649 to initial_ctx in ssl_sock_initial_ctx. */
William Lallemand8b453912019-11-21 15:48:10 +01004650 errcode |= ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004651 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004652 if (bind_conf->default_ctx)
William Lallemand8b453912019-11-21 15:48:10 +01004653 errcode |= ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, &errmsg);
Emeric Brun0bed9942014-10-30 19:25:24 +01004654
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004655 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004656 while (node) {
4657 sni = ebmb_entry(node, struct sni_ctx, name);
Emeric Brun0bed9942014-10-30 19:25:24 +01004658 if (!sni->order && sni->ctx != bind_conf->default_ctx)
4659 /* only initialize the CTX on its first occurrence and
4660 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004661 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004662 node = ebmb_next(node);
4663 }
4664
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004665 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004666 while (node) {
4667 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004668 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004669 /* only initialize the CTX on its first occurrence and
4670 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004671 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
4672 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004673 node = ebmb_next(node);
4674 }
William Lallemand8b453912019-11-21 15:48:10 +01004675
4676 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004677 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004678 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004679 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004680 err++;
4681 }
4682
4683 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004684 return err;
4685}
4686
Willy Tarreau55d37912016-12-21 23:38:39 +01004687/* Prepares all the contexts for a bind_conf and allocates the shared SSL
4688 * context if needed. Returns < 0 on error, 0 on success. The warnings and
4689 * alerts are directly emitted since the rest of the stack does it below.
4690 */
4691int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
4692{
4693 struct proxy *px = bind_conf->frontend;
4694 int alloc_ctx;
4695 int err;
4696
4697 if (!bind_conf->is_ssl) {
4698 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004699 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
4700 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01004701 }
4702 return 0;
4703 }
4704 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004705 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004706 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
4707 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004708 }
4709 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004710 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
4711 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004712 return -1;
4713 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004714 }
William Lallemandc61c0b32017-12-04 18:46:39 +01004715 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004716 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02004717 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01004718 sizeof(*sh_ssl_sess_tree),
4719 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02004720 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004721 if (alloc_ctx == SHCTX_E_INIT_LOCK)
4722 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");
4723 else
4724 ha_alert("Unable to allocate SSL session cache.\n");
4725 return -1;
4726 }
4727 /* free block callback */
4728 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
4729 /* init the root tree within the extra space */
4730 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
4731 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01004732 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004733 err = 0;
4734 /* initialize all certificate contexts */
4735 err += ssl_sock_prepare_all_ctx(bind_conf);
4736
4737 /* initialize CA variables if the certificates generation is enabled */
4738 err += ssl_sock_load_ca(bind_conf);
4739
4740 return -err;
4741}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004742
4743/* release ssl context allocated for servers. */
4744void ssl_sock_free_srv_ctx(struct server *srv)
4745{
Olivier Houchardc7566002018-11-20 23:33:50 +01004746#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4747 if (srv->ssl_ctx.alpn_str)
4748 free(srv->ssl_ctx.alpn_str);
4749#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01004750#ifdef OPENSSL_NPN_NEGOTIATED
Olivier Houchardc7566002018-11-20 23:33:50 +01004751 if (srv->ssl_ctx.npn_str)
4752 free(srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01004753#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02004754 if (srv->ssl_ctx.reused_sess) {
4755 int i;
4756
4757 for (i = 0; i < global.nbthread; i++)
4758 free(srv->ssl_ctx.reused_sess[i].ptr);
4759 free(srv->ssl_ctx.reused_sess);
4760 }
4761
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004762 if (srv->ssl_ctx.ctx)
4763 SSL_CTX_free(srv->ssl_ctx.ctx);
4764}
4765
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004766/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004767 * be NULL, in which case nothing is done. The default_ctx is nullified too.
4768 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004769void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004770{
4771 struct ebmb_node *node, *back;
4772 struct sni_ctx *sni;
4773
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004774 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004775 while (node) {
4776 sni = ebmb_entry(node, struct sni_ctx, name);
4777 back = ebmb_next(node);
4778 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004779 SSL_CTX_free(sni->ctx);
William Lallemandb2408692020-06-24 09:54:29 +02004780 LIST_DEL(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004781 free(sni);
4782 node = back;
4783 }
4784
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004785 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004786 while (node) {
4787 sni = ebmb_entry(node, struct sni_ctx, name);
4788 back = ebmb_next(node);
4789 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004790 SSL_CTX_free(sni->ctx);
William Lallemandb2408692020-06-24 09:54:29 +02004791 LIST_DEL(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004792 free(sni);
4793 node = back;
4794 }
William Lallemandb2408692020-06-24 09:54:29 +02004795
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004796 SSL_CTX_free(bind_conf->initial_ctx);
4797 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02004798 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004799 bind_conf->default_ctx = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004800 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02004801}
William Lallemandb2408692020-06-24 09:54:29 +02004802
4803
4804void ssl_sock_deinit()
4805{
4806 crtlist_deinit(); /* must be free'd before the ckchs */
4807 ckch_deinit();
4808}
4809REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02004810
Willy Tarreau795cdab2016-12-22 17:30:54 +01004811/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
4812void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
4813{
4814 ssl_sock_free_ca(bind_conf);
4815 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004816 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01004817 free(bind_conf->ca_sign_file);
4818 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02004819 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01004820 free(bind_conf->keys_ref->filename);
4821 free(bind_conf->keys_ref->tlskeys);
4822 LIST_DEL(&bind_conf->keys_ref->list);
4823 free(bind_conf->keys_ref);
4824 }
4825 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004826 bind_conf->ca_sign_pass = NULL;
4827 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004828}
4829
Christopher Faulet31af49d2015-06-09 17:29:50 +02004830/* Load CA cert file and private key used to generate certificates */
4831int
Willy Tarreau03209342016-12-22 17:08:28 +01004832ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02004833{
Willy Tarreau03209342016-12-22 17:08:28 +01004834 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03004835 struct cert_key_and_chain *ckch = NULL;
4836 int ret = 0;
4837 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004838
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02004839 if (!bind_conf->generate_certs)
Shimi Gersner5846c492020-08-23 13:58:12 +03004840 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004841
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01004842#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02004843 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01004844 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004845 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02004846 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004847 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02004848#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02004849
Christopher Faulet31af49d2015-06-09 17:29:50 +02004850 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004851 ha_alert("Proxy '%s': cannot enable certificate generation, "
4852 "no CA certificate File configured at [%s:%d].\n",
4853 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03004854 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004855 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004856
Shimi Gersner5846c492020-08-23 13:58:12 +03004857 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02004858 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03004859 if (!ckch) {
4860 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
4861 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
4862 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004863 }
Shimi Gersner5846c492020-08-23 13:58:12 +03004864
4865 /* Try to parse file */
4866 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
4867 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
4868 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
4869 if (err) free(err);
4870 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004871 }
Shimi Gersner5846c492020-08-23 13:58:12 +03004872
4873 /* Fail if missing cert or pkey */
4874 if ((!ckch->cert) || (!ckch->key)) {
4875 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
4876 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
4877 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004878 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004879
Shimi Gersner5846c492020-08-23 13:58:12 +03004880 /* Final assignment to bind */
4881 bind_conf->ca_sign_ckch = ckch;
4882 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004883
Shimi Gersner5846c492020-08-23 13:58:12 +03004884 failed:
4885 if (ckch) {
4886 ssl_sock_free_cert_key_and_chain_contents(ckch);
4887 free(ckch);
4888 }
4889
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004890 bind_conf->generate_certs = 0;
Shimi Gersner5846c492020-08-23 13:58:12 +03004891 ret++;
4892 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004893}
4894
4895/* Release CA cert and private key used to generate certificated */
4896void
4897ssl_sock_free_ca(struct bind_conf *bind_conf)
4898{
Shimi Gersner5846c492020-08-23 13:58:12 +03004899 if (bind_conf->ca_sign_ckch) {
4900 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
4901 free(bind_conf->ca_sign_ckch);
4902 bind_conf->ca_sign_ckch = NULL;
4903 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004904}
4905
Emeric Brun46591952012-05-18 15:47:34 +02004906/*
4907 * This function is called if SSL * context is not yet allocated. The function
4908 * is designed to be called before any other data-layer operation and sets the
4909 * handshake flag on the connection. It is safe to call it multiple times.
4910 * It returns 0 on success and -1 in error case.
4911 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004912static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004913{
Olivier Houchard66ab4982019-02-26 18:37:15 +01004914 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02004915 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004916 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004917 return 0;
4918
Willy Tarreau3c728722014-01-23 13:50:42 +01004919 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02004920 return 0;
4921
Olivier Houchard66ab4982019-02-26 18:37:15 +01004922 ctx = pool_alloc(ssl_sock_ctx_pool);
4923 if (!ctx) {
4924 conn->err_code = CO_ER_SSL_NO_MEM;
4925 return -1;
4926 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004927 ctx->wait_event.tasklet = tasklet_new();
4928 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004929 conn->err_code = CO_ER_SSL_NO_MEM;
4930 pool_free(ssl_sock_ctx_pool, ctx);
4931 return -1;
4932 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004933 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
4934 ctx->wait_event.tasklet->context = ctx;
Willy Tarreaub421f9d2021-02-25 15:31:00 +01004935 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02004936 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01004937 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01004938 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004939 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01004940 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02004941 ctx->xprt_st = 0;
4942 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004943
4944 /* Only work with sockets for now, this should be adapted when we'll
4945 * add QUIC support.
4946 */
4947 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02004948 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004949 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
4950 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02004951 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01004952
Willy Tarreau20879a02012-12-03 16:32:10 +01004953 if (global.maxsslconn && sslconns >= global.maxsslconn) {
4954 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004955 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004956 }
Willy Tarreau403edff2012-09-06 11:58:37 +02004957
Emeric Brun46591952012-05-18 15:47:34 +02004958 /* If it is in client mode initiate SSL session
4959 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01004960 if (objt_server(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004961 int may_retry = 1;
4962
4963 retry_connect:
Emeric Brun46591952012-05-18 15:47:34 +02004964 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004965 ctx->ssl = SSL_new(__objt_server(conn->target)->ssl_ctx.ctx);
4966 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004967 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004968 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004969 goto retry_connect;
4970 }
Willy Tarreau20879a02012-12-03 16:32:10 +01004971 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004972 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004973 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004974 ctx->bio = BIO_new(ha_meth);
4975 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01004976 SSL_free(ctx->ssl);
4977 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004978 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004979 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004980 goto retry_connect;
4981 }
Emeric Brun55476152014-11-12 17:35:37 +01004982 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004983 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004984 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004985 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02004986 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02004987
Evan Broderbe554312013-06-27 00:05:25 -07004988 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004989 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
4990 SSL_free(ctx->ssl);
4991 ctx->ssl = NULL;
Emeric Brun55476152014-11-12 17:35:37 +01004992 conn->xprt_ctx = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004993 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004994 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004995 goto retry_connect;
4996 }
Emeric Brun55476152014-11-12 17:35:37 +01004997 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004998 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004999 }
5000
Olivier Houchard66ab4982019-02-26 18:37:15 +01005001 SSL_set_connect_state(ctx->ssl);
Willy Tarreau07d94e42018-09-20 10:57:52 +02005002 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5003 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5004 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 +01005005 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005006 SSL_SESSION_free(sess);
Willy Tarreau07d94e42018-09-20 10:57:52 +02005007 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
5008 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Olivier Houcharde6060c52017-11-16 17:42:52 +01005009 } else if (sess) {
5010 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005011 }
5012 }
Evan Broderbe554312013-06-27 00:05:25 -07005013
Emeric Brun46591952012-05-18 15:47:34 +02005014 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005015 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005016
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005017 _HA_ATOMIC_ADD(&sslconns, 1);
5018 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005019 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005020 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005021 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005022 return 0;
5023 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005024 else if (objt_listener(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005025 int may_retry = 1;
5026
5027 retry_accept:
Emeric Brun46591952012-05-18 15:47:34 +02005028 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005029 ctx->ssl = SSL_new(__objt_listener(conn->target)->bind_conf->initial_ctx);
5030 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005031 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005032 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005033 goto retry_accept;
5034 }
Willy Tarreau20879a02012-12-03 16:32:10 +01005035 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005036 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005037 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005038 ctx->bio = BIO_new(ha_meth);
5039 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01005040 SSL_free(ctx->ssl);
5041 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005042 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005043 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005044 goto retry_accept;
5045 }
Emeric Brun55476152014-11-12 17:35:37 +01005046 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005047 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005048 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005049 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02005050 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02005051
Emeric Brune1f38db2012-09-03 20:36:47 +02005052 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005053 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
5054 SSL_free(ctx->ssl);
5055 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005056 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005057 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005058 goto retry_accept;
5059 }
Emeric Brun55476152014-11-12 17:35:37 +01005060 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005061 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005062 }
5063
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005064#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005065 if (__objt_listener(conn->target)->bind_conf->ssl_conf.early_data) {
5066 b_alloc(&ctx->early_buf);
5067 SSL_set_max_early_data(ctx->ssl,
5068 /* Only allow early data if we managed to allocate
5069 * a buffer.
5070 */
5071 (!b_is_null(&ctx->early_buf)) ?
5072 global.tune.bufsize - global.tune.maxrewrite : 0);
5073 }
5074#endif
5075
Olivier Houchard66ab4982019-02-26 18:37:15 +01005076 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005077
Emeric Brun46591952012-05-18 15:47:34 +02005078 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005079 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005080#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreau5c6176d2021-02-05 10:24:54 +01005081 if (__objt_listener(conn->target)->bind_conf->ssl_conf.early_data)
Willy Tarreau5930fb22021-02-03 11:21:38 +01005082 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005083#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005084
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005085 _HA_ATOMIC_ADD(&sslconns, 1);
5086 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005087 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005088 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005089 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005090 return 0;
5091 }
5092 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005093 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005094err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005095 if (ctx && ctx->wait_event.tasklet)
5096 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005097 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005098 return -1;
5099}
5100
5101
5102/* This is the callback which is used when an SSL handshake is pending. It
5103 * updates the FD status if it wants some polling before being called again.
5104 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5105 * otherwise it returns non-zero and removes itself from the connection's
5106 * flags (the bit is provided in <flag> by the caller).
5107 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005108static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005109{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005110 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005111 int ret;
Willy Tarreaud2871402021-02-02 15:42:25 +01005112 socklen_t lskerr;
5113 int skerr;
5114
Emeric Brun46591952012-05-18 15:47:34 +02005115
Willy Tarreau3c728722014-01-23 13:50:42 +01005116 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005117 return 0;
5118
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005119 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005120 goto out_error;
5121
Willy Tarreaud2871402021-02-02 15:42:25 +01005122 /* don't start calculating a handshake on a dead connection */
5123 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5124 goto out_error;
5125
5126 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5127 * status from the lower layers, so let's check the FD directly. Ideally
5128 * the xprt layers should provide some status indicating their knowledge
5129 * of shutdowns or error.
5130 */
5131 skerr = 0;
5132 lskerr = sizeof(skerr);
5133 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5134 skerr != 0)
5135 goto out_error;
5136
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005137#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005138 /*
5139 * Check if we have early data. If we do, we have to read them
5140 * before SSL_do_handshake() is called, And there's no way to
5141 * detect early data, except to try to read them
5142 */
5143 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005144 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005145
Olivier Houchard54907bb2019-12-19 15:02:39 +01005146 while (1) {
5147 ret = SSL_read_early_data(ctx->ssl,
5148 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5149 &read_data);
5150 if (ret == SSL_READ_EARLY_DATA_ERROR)
5151 goto check_error;
5152 if (read_data > 0) {
5153 conn->flags |= CO_FL_EARLY_DATA;
5154 b_add(&ctx->early_buf, read_data);
5155 }
5156 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5157 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5158 if (!b_data(&ctx->early_buf))
5159 b_free(&ctx->early_buf);
5160 break;
5161 }
5162 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005163 }
5164#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005165 /* If we use SSL_do_handshake to process a reneg initiated by
5166 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5167 * Usually SSL_write and SSL_read are used and process implicitly
5168 * the reneg handshake.
5169 * Here we use SSL_peek as a workaround for reneg.
5170 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005171 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005172 char c;
5173
Olivier Houchard66ab4982019-02-26 18:37:15 +01005174 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005175 if (ret <= 0) {
5176 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005177 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005178
Emeric Brun674b7432012-11-08 19:21:55 +01005179 if (ret == SSL_ERROR_WANT_WRITE) {
5180 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005181 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005182 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005183 return 0;
5184 }
5185 else if (ret == SSL_ERROR_WANT_READ) {
5186 /* handshake may have been completed but we have
5187 * no more data to read.
5188 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005189 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005190 ret = 1;
5191 goto reneg_ok;
5192 }
5193 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005194 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005195 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005196 return 0;
5197 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005198#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005199 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005200 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005201 return 0;
5202 }
5203#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005204 else if (ret == SSL_ERROR_SYSCALL) {
5205 /* if errno is null, then connection was successfully established */
5206 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5207 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005208 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005209#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5210 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005211 conn->err_code = CO_ER_SSL_HANDSHAKE;
5212#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005213 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005214#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005215 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005216 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005217 empty_handshake = state == TLS_ST_BEFORE;
5218#else
Lukas Tribus49799162019-07-08 14:29:15 +02005219 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5220 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005221#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005222 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005223 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005224 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005225 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5226 else
5227 conn->err_code = CO_ER_SSL_EMPTY;
5228 }
5229 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005230 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005231 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5232 else
5233 conn->err_code = CO_ER_SSL_ABORT;
5234 }
5235 }
5236 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005237 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005238 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005239 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005240 conn->err_code = CO_ER_SSL_HANDSHAKE;
5241 }
Lukas Tribus49799162019-07-08 14:29:15 +02005242#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005243 }
Emeric Brun674b7432012-11-08 19:21:55 +01005244 goto out_error;
5245 }
5246 else {
5247 /* Fail on all other handshake errors */
5248 /* Note: OpenSSL may leave unread bytes in the socket's
5249 * buffer, causing an RST to be emitted upon close() on
5250 * TCP sockets. We first try to drain possibly pending
5251 * data to avoid this as much as possible.
5252 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005253 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005254 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005255 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005256 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005257 goto out_error;
5258 }
5259 }
5260 /* read some data: consider handshake completed */
5261 goto reneg_ok;
5262 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005263 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005264check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005265 if (ret != 1) {
5266 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005267 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005268
5269 if (ret == SSL_ERROR_WANT_WRITE) {
5270 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005271 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005272 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005273 return 0;
5274 }
5275 else if (ret == SSL_ERROR_WANT_READ) {
5276 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005277 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005278 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5279 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005280 return 0;
5281 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005282#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005283 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005284 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005285 return 0;
5286 }
5287#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005288 else if (ret == SSL_ERROR_SYSCALL) {
5289 /* if errno is null, then connection was successfully established */
5290 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5291 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005292 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005293#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5294 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005295 conn->err_code = CO_ER_SSL_HANDSHAKE;
5296#else
5297 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005298#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005299 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005300 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005301 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005302#else
Lukas Tribus49799162019-07-08 14:29:15 +02005303 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5304 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005305#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005306 if (empty_handshake) {
5307 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005308 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005309 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5310 else
5311 conn->err_code = CO_ER_SSL_EMPTY;
5312 }
5313 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005314 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005315 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5316 else
5317 conn->err_code = CO_ER_SSL_ABORT;
5318 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005319 }
5320 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005321 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005322 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5323 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005324 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005325 }
Lukas Tribus49799162019-07-08 14:29:15 +02005326#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005327 }
Willy Tarreau89230192012-09-28 20:22:13 +02005328 goto out_error;
5329 }
Emeric Brun46591952012-05-18 15:47:34 +02005330 else {
5331 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005332 /* Note: OpenSSL may leave unread bytes in the socket's
5333 * buffer, causing an RST to be emitted upon close() on
5334 * TCP sockets. We first try to drain possibly pending
5335 * data to avoid this as much as possible.
5336 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005337 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005338 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005339 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005340 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005341 goto out_error;
5342 }
5343 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005344#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005345 else {
5346 /*
5347 * If the server refused the early data, we have to send a
5348 * 425 to the client, as we no longer have the data to sent
5349 * them again.
5350 */
5351 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005352 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005353 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5354 goto out_error;
5355 }
5356 }
5357 }
5358#endif
5359
Emeric Brun46591952012-05-18 15:47:34 +02005360
Emeric Brun674b7432012-11-08 19:21:55 +01005361reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005362
Willy Tarreau5db847a2019-05-09 14:13:35 +02005363#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005364 /* ASYNC engine API doesn't support moving read/write
5365 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005366 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005367 */
5368 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005369 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005370#endif
Emeric Brun46591952012-05-18 15:47:34 +02005371 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005372 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005373 if (objt_server(conn->target)) {
5374 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5375 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5376 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005377 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005378 else {
5379 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5380 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5381 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5382 }
Emeric Brun46591952012-05-18 15:47:34 +02005383 }
5384
5385 /* The connection is now established at both layers, it's time to leave */
5386 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5387 return 1;
5388
5389 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005390 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005391 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005392 ERR_clear_error();
5393
Emeric Brun9fa89732012-10-04 17:09:56 +02005394 /* free resumed session if exists */
Willy Tarreau07d94e42018-09-20 10:57:52 +02005395 if (objt_server(conn->target) && __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5396 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
5397 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Emeric Brun9fa89732012-10-04 17:09:56 +02005398 }
5399
Emeric Brun46591952012-05-18 15:47:34 +02005400 /* Fail on all other handshake errors */
5401 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005402 if (!conn->err_code)
5403 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005404 return 0;
5405}
5406
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005407/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5408 * event subscriber <es> is not allowed to change from a previous call as long
5409 * as at least one event is still subscribed. The <event_type> must only be a
5410 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5411 * unless the transport layer was already released.
5412 */
5413static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005414{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005415 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005416
Olivier Houchard0ff28652019-06-24 18:57:39 +02005417 if (!ctx)
5418 return -1;
5419
Willy Tarreau113d52b2020-01-10 09:20:26 +01005420 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005421 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005422
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005423 ctx->subs = es;
5424 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005425
5426 /* we may have to subscribe to lower layers for new events */
5427 event_type &= ~ctx->wait_event.events;
5428 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5429 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005430 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005431}
5432
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005433/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5434 * The <es> pointer is not allowed to differ from the one passed to the
5435 * subscribe() call. It always returns zero.
5436 */
5437static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005438{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005439 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005440
Willy Tarreau113d52b2020-01-10 09:20:26 +01005441 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005442 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005443
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005444 es->events &= ~event_type;
5445 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005446 ctx->subs = NULL;
5447
5448 /* If we subscribed, and we're not doing the handshake,
5449 * then we subscribed because the upper layer asked for it,
5450 * as the upper layer is no longer interested, we can
5451 * unsubscribe too.
5452 */
5453 event_type &= ctx->wait_event.events;
5454 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5455 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005456
5457 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005458}
5459
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005460/* The connection has been taken over, so destroy the old tasklet and create
5461 * a new one. The original thread ID must be passed into orig_tid
5462 * It should be called with the takeover lock for the old thread held.
5463 * Returns 0 on success, and -1 on failure
5464 */
5465static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
5466{
5467 struct ssl_sock_ctx *ctx = xprt_ctx;
5468 struct tasklet *tl = tasklet_new();
5469
5470 if (!tl)
5471 return -1;
5472
5473 ctx->wait_event.tasklet->context = NULL;
5474 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
5475 ctx->wait_event.tasklet = tl;
5476 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5477 ctx->wait_event.tasklet->context = ctx;
5478 return 0;
5479}
5480
Willy Tarreaub0d3a282021-03-02 17:29:56 +01005481/* notify the next xprt that the connection is about to become idle and that it
5482 * may be stolen at any time after the function returns and that any tasklet in
5483 * the chain must be careful before dereferencing its context.
5484 */
5485static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
5486{
5487 struct ssl_sock_ctx *ctx = xprt_ctx;
5488
5489 if (!ctx || !ctx->wait_event.tasklet)
5490 return;
5491
5492 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5493 if (ctx->xprt)
5494 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
5495}
5496
5497/* notify the next xprt that the connection is not idle anymore and that it may
5498 * not be stolen before the next xprt_set_idle().
5499 */
5500static void ssl_set_used(struct connection *conn, void *xprt_ctx)
5501{
5502 struct ssl_sock_ctx *ctx = xprt_ctx;
5503
5504 if (!ctx || !ctx->wait_event.tasklet)
5505 return;
5506
5507 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5508 if (ctx->xprt)
5509 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
5510}
5511
Olivier Houchard2e055482019-05-27 19:50:12 +02005512/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5513 * Returns 0 on success, and non-zero on failure.
5514 */
5515static 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)
5516{
5517 struct ssl_sock_ctx *ctx = xprt_ctx;
5518
5519 if (oldxprt_ops != NULL)
5520 *oldxprt_ops = ctx->xprt;
5521 if (oldxprt_ctx != NULL)
5522 *oldxprt_ctx = ctx->xprt_ctx;
5523 ctx->xprt = toadd_ops;
5524 ctx->xprt_ctx = toadd_ctx;
5525 return 0;
5526}
5527
Olivier Houchard5149b592019-05-23 17:47:36 +02005528/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5529 * return 0, otherwise just call the remove_xprt method from the underlying
5530 * XPRT.
5531 */
5532static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5533{
5534 struct ssl_sock_ctx *ctx = xprt_ctx;
5535
5536 if (ctx->xprt_ctx == toremove_ctx) {
5537 ctx->xprt_ctx = newctx;
5538 ctx->xprt = newops;
5539 return 0;
5540 }
5541 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5542}
5543
Willy Tarreau9a5a0e02021-01-20 14:55:01 +01005544struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned short state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02005545{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005546 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005547 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005548 struct connection *conn;
5549 int conn_in_list;
5550 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005551
Willy Tarreaub0d3a282021-03-02 17:29:56 +01005552 if (state & TASK_F_USR1) {
5553 /* the tasklet was idling on an idle connection, it might have
5554 * been stolen, let's be careful!
5555 */
5556 HA_SPIN_LOCK(OTHER_LOCK, &idle_conns[tid].takeover_lock);
5557 if (tl->context == NULL) {
5558 HA_SPIN_UNLOCK(OTHER_LOCK, &idle_conns[tid].takeover_lock);
5559 tasklet_free(tl);
5560 return NULL;
5561 }
5562 conn = ctx->conn;
5563 conn_in_list = conn->flags & CO_FL_LIST_MASK;
5564 if (conn_in_list)
5565 MT_LIST_DEL(&conn->list);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005566 HA_SPIN_UNLOCK(OTHER_LOCK, &idle_conns[tid].takeover_lock);
Willy Tarreaub0d3a282021-03-02 17:29:56 +01005567 } else {
5568 conn = ctx->conn;
5569 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005570 }
Willy Tarreaub0d3a282021-03-02 17:29:56 +01005571
Olivier Houchardea8dd942019-05-20 14:02:16 +02005572 /* First if we're doing an handshake, try that */
Willy Tarreaub421f9d2021-02-25 15:31:00 +01005573 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005574 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreaub421f9d2021-02-25 15:31:00 +01005575 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5576 /* handshake completed, leave the bulk queue */
Willy Tarreaua0c6da12021-03-09 17:58:02 +01005577 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreaub421f9d2021-02-25 15:31:00 +01005578 }
5579 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005580 /* If we had an error, or the handshake is done and I/O is available,
5581 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005582 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005583 * we can't be sure conn_fd_handler() will be called again.
5584 */
5585 if ((ctx->conn->flags & CO_FL_ERROR) ||
5586 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005587 int woke = 0;
5588
5589 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005590 if (ctx->subs) {
5591 tasklet_wakeup(ctx->subs->tasklet);
5592 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005593 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005594 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005595 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005596
Olivier Houchardea8dd942019-05-20 14:02:16 +02005597 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005598 * upper layers know. If we have no mux, create it,
5599 * and once we have a mux, call its wake method if we didn't
5600 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005601 */
5602 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005603 if (!ctx->conn->mux)
5604 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005605 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005606 ret = ctx->conn->mux->wake(ctx->conn);
5607 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005608 }
5609 }
Olivier Houchard54907bb2019-12-19 15:02:39 +01005610#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5611 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005612 else if (b_data(&ctx->early_buf) && ctx->subs &&
5613 ctx->subs->events & SUB_RETRY_RECV) {
5614 tasklet_wakeup(ctx->subs->tasklet);
5615 ctx->subs->events &= ~SUB_RETRY_RECV;
5616 if (!ctx->subs->events)
5617 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005618 }
5619#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005620leave:
5621 if (!ret && conn_in_list) {
5622 struct server *srv = objt_server(conn->target);
5623
5624 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreaua9d7b762020-07-10 08:28:20 +02005625 MT_LIST_ADDQ(&srv->safe_conns[tid], &conn->list);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005626 else
Willy Tarreaua9d7b762020-07-10 08:28:20 +02005627 MT_LIST_ADDQ(&srv->idle_conns[tid], &conn->list);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005628 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005629 return NULL;
5630}
5631
Emeric Brun46591952012-05-18 15:47:34 +02005632/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01005633 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02005634 * buffer wraps, in which case a second call may be performed. The connection's
5635 * flags are updated with whatever special event is detected (error, read0,
5636 * empty). The caller is responsible for taking care of those events and
5637 * avoiding the call if inappropriate. The function does not call the
5638 * connection's polling update function, so the caller is responsible for this.
5639 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005640static 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 +02005641{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005642 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02005643 ssize_t ret;
5644 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02005645
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005646 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005647 goto out_error;
5648
Olivier Houchard54907bb2019-12-19 15:02:39 +01005649#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5650 if (b_data(&ctx->early_buf)) {
5651 try = b_contig_space(buf);
5652 if (try > b_data(&ctx->early_buf))
5653 try = b_data(&ctx->early_buf);
5654 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
5655 b_add(buf, try);
5656 b_del(&ctx->early_buf, try);
5657 if (b_data(&ctx->early_buf) == 0)
5658 b_free(&ctx->early_buf);
5659 return try;
5660 }
5661#endif
5662
Willy Tarreau911db9b2020-01-23 16:27:54 +01005663 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005664 /* a handshake was requested */
5665 return 0;
5666
Emeric Brun46591952012-05-18 15:47:34 +02005667 /* read the largest possible block. For this, we perform only one call
5668 * to recv() unless the buffer wraps and we exactly fill the first hunk,
5669 * in which case we accept to do it once again. A new attempt is made on
5670 * EINTR too.
5671 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01005672 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005673
Willy Tarreau591d4452018-06-15 17:21:00 +02005674 try = b_contig_space(buf);
5675 if (!try)
5676 break;
5677
Willy Tarreauabf08d92014-01-14 11:31:27 +01005678 if (try > count)
5679 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02005680
Olivier Houchard66ab4982019-02-26 18:37:15 +01005681 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005682
Emeric Brune1f38db2012-09-03 20:36:47 +02005683 if (conn->flags & CO_FL_ERROR) {
5684 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005685 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005686 }
Emeric Brun46591952012-05-18 15:47:34 +02005687 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02005688 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005689 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005690 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005691 }
Emeric Brun46591952012-05-18 15:47:34 +02005692 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005693 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005694 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005695 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02005696 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005697 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005698#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005699 /* Async mode can be re-enabled, because we're leaving data state.*/
5700 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005701 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005702#endif
Emeric Brun46591952012-05-18 15:47:34 +02005703 break;
5704 }
5705 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005706 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005707 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5708 SUB_RETRY_RECV,
5709 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01005710 /* handshake is running, and it may need to re-enable read */
5711 conn->flags |= CO_FL_SSL_WAIT_HS;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005712#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005713 /* Async mode can be re-enabled, because we're leaving data state.*/
5714 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005715 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005716#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005717 break;
5718 }
Emeric Brun46591952012-05-18 15:47:34 +02005719 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005720 } else if (ret == SSL_ERROR_ZERO_RETURN)
5721 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005722 /* For SSL_ERROR_SYSCALL, make sure to clear the error
5723 * stack before shutting down the connection for
5724 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005725 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
5726 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02005727 /* otherwise it's a real error */
5728 goto out_error;
5729 }
5730 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005731 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005732 return done;
5733
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005734 clear_ssl_error:
5735 /* Clear openssl global errors stack */
5736 ssl_sock_dump_errors(conn);
5737 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02005738 read0:
5739 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005740 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005741
Emeric Brun46591952012-05-18 15:47:34 +02005742 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005743 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01005744 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005745 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005746 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005747 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005748}
5749
5750
Willy Tarreau787db9a2018-06-14 18:31:46 +02005751/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
5752 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
5753 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02005754 * Only one call to send() is performed, unless the buffer wraps, in which case
5755 * a second call may be performed. The connection's flags are updated with
5756 * whatever special event is detected (error, empty). The caller is responsible
5757 * for taking care of those events and avoiding the call if inappropriate. The
5758 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02005759 * is responsible for this. The buffer's output is not adjusted, it's up to the
5760 * caller to take care of this. It's up to the caller to update the buffer's
5761 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02005762 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005763static 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 +02005764{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005765 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005766 ssize_t ret;
5767 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02005768
5769 done = 0;
5770
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005771 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005772 goto out_error;
5773
Willy Tarreau911db9b2020-01-23 16:27:54 +01005774 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005775 /* a handshake was requested */
5776 return 0;
5777
5778 /* send the largest possible block. For this we perform only one call
5779 * to send() unless the buffer wraps and we exactly fill the first hunk,
5780 * in which case we accept to do it once again.
5781 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02005782 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005783#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005784 size_t written_data;
5785#endif
5786
Willy Tarreau787db9a2018-06-14 18:31:46 +02005787 try = b_contig_data(buf, done);
5788 if (try > count)
5789 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01005790
Willy Tarreau7bed9452014-02-02 02:00:24 +01005791 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005792 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01005793 global_ssl.max_record && try > global_ssl.max_record) {
5794 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005795 }
5796 else {
5797 /* we need to keep the information about the fact that
5798 * we're not limiting the upcoming send(), because if it
5799 * fails, we'll have to retry with at least as many data.
5800 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005801 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005802 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01005803
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005804#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02005805 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005806 unsigned int max_early;
5807
Olivier Houchard522eea72017-11-03 16:27:47 +01005808 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01005809 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01005810 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005811 if (SSL_get0_session(ctx->ssl))
5812 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01005813 else
5814 max_early = 0;
5815 }
5816
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005817 if (try + ctx->sent_early_data > max_early) {
5818 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01005819 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02005820 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005821 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005822 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01005823 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005824 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005825 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005826 if (ret == 1) {
5827 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005828 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005829 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005830 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005831 /* Initiate the handshake, now */
5832 tasklet_wakeup(ctx->wait_event.tasklet);
5833 }
Olivier Houchard522eea72017-11-03 16:27:47 +01005834
Olivier Houchardc2aae742017-09-22 18:26:28 +02005835 }
5836
5837 } else
5838#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005839 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01005840
Emeric Brune1f38db2012-09-03 20:36:47 +02005841 if (conn->flags & CO_FL_ERROR) {
5842 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005843 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005844 }
Emeric Brun46591952012-05-18 15:47:34 +02005845 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005846 /* A send succeeded, so we can consider ourself connected */
5847 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005848 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005849 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005850 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005851 }
5852 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005853 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005854
Emeric Brun46591952012-05-18 15:47:34 +02005855 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005856 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01005857 /* handshake is running, and it may need to re-enable write */
5858 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005859 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005860#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005861 /* Async mode can be re-enabled, because we're leaving data state.*/
5862 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005863 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005864#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005865 break;
5866 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005867
Emeric Brun46591952012-05-18 15:47:34 +02005868 break;
5869 }
5870 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005871 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02005872 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005873 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5874 SUB_RETRY_RECV,
5875 &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005876#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005877 /* Async mode can be re-enabled, because we're leaving data state.*/
5878 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005879 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005880#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005881 break;
5882 }
Emeric Brun46591952012-05-18 15:47:34 +02005883 goto out_error;
5884 }
5885 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005886 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005887 return done;
5888
5889 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005890 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005891 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005892 ERR_clear_error();
5893
Emeric Brun46591952012-05-18 15:47:34 +02005894 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005895 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005896}
5897
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005898static void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02005899
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005900 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005901
Olivier Houchardea8dd942019-05-20 14:02:16 +02005902
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005903 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005904 if (ctx->wait_event.events != 0)
5905 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
5906 ctx->wait_event.events,
5907 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01005908 if (ctx->subs) {
5909 ctx->subs->events = 0;
5910 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005911 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005912
Olivier Houchard692c1d02019-05-23 18:41:47 +02005913 if (ctx->xprt->close)
5914 ctx->xprt->close(conn, ctx->xprt_ctx);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005915#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +02005916 if (global_ssl.async) {
5917 OSSL_ASYNC_FD all_fd[32], afd;
5918 size_t num_all_fds = 0;
5919 int i;
5920
Olivier Houchard66ab4982019-02-26 18:37:15 +01005921 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005922 if (num_all_fds > 32) {
5923 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
5924 return;
5925 }
5926
Olivier Houchard66ab4982019-02-26 18:37:15 +01005927 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005928
5929 /* If an async job is pending, we must try to
5930 to catch the end using polling before calling
5931 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005932 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02005933 for (i=0 ; i < num_all_fds ; i++) {
5934 /* switch on an handler designed to
5935 * handle the SSL_free
5936 */
5937 afd = all_fd[i];
5938 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005939 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02005940 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00005941 /* To ensure that the fd cache won't be used
5942 * and we'll catch a real RD event.
5943 */
5944 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02005945 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005946 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005947 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005948 _HA_ATOMIC_ADD(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005949 return;
5950 }
Emeric Brun3854e012017-05-17 20:42:48 +02005951 /* Else we can remove the fds from the fdtab
5952 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02005953 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02005954 * because the fd is owned by the engine.
5955 * the engine is responsible to close
5956 */
5957 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +02005958 fd_stop_both(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005959 }
5960#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005961 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01005962 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005963 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005964 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005965 _HA_ATOMIC_SUB(&sslconns, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005966 }
Emeric Brun46591952012-05-18 15:47:34 +02005967}
5968
5969/* This function tries to perform a clean shutdown on an SSL connection, and in
5970 * any case, flags the connection as reusable if no handshake was in progress.
5971 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005972static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02005973{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005974 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005975
Willy Tarreau911db9b2020-01-23 16:27:54 +01005976 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005977 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01005978 if (!clean)
5979 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005980 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005981 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005982 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01005983 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005984 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005985 ERR_clear_error();
5986 }
Emeric Brun46591952012-05-18 15:47:34 +02005987}
5988
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01005989
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005990/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01005991int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
5992{
5993 struct ssl_sock_ctx *ctx;
5994 X509 *crt;
5995
5996 if (!ssl_sock_is_ssl(conn))
5997 return 0;
5998
5999 ctx = conn->xprt_ctx;
6000
6001 crt = SSL_get_certificate(ctx->ssl);
6002 if (!crt)
6003 return 0;
6004
6005 return cert_get_pkey_algo(crt, out);
6006}
6007
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006008/* used for ppv2 cert signature (can be used for logging) */
6009const char *ssl_sock_get_cert_sig(struct connection *conn)
6010{
Christopher Faulet82004142019-09-10 10:12:03 +02006011 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006012
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006013 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6014 X509 *crt;
6015
6016 if (!ssl_sock_is_ssl(conn))
6017 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006018 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006019 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006020 if (!crt)
6021 return NULL;
6022 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6023 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6024}
6025
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006026/* used for ppv2 authority */
6027const char *ssl_sock_get_sni(struct connection *conn)
6028{
6029#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006030 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006031
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006032 if (!ssl_sock_is_ssl(conn))
6033 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006034 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006035 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006036#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006037 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006038#endif
6039}
6040
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006041/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006042const char *ssl_sock_get_cipher_name(struct connection *conn)
6043{
Christopher Faulet82004142019-09-10 10:12:03 +02006044 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006045
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006046 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006047 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006048 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006049 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006050}
6051
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006052/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006053const char *ssl_sock_get_proto_version(struct connection *conn)
6054{
Christopher Faulet82004142019-09-10 10:12:03 +02006055 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006056
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006057 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006058 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006059 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006060 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006061}
6062
Olivier Houchardab28a322018-12-21 19:45:40 +01006063void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6064{
6065#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02006066 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006067
Olivier Houcharde488ea82019-06-28 14:10:33 +02006068 if (!ssl_sock_is_ssl(conn))
6069 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006070 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006071 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006072#endif
6073}
6074
Willy Tarreau119a4082016-12-22 21:58:38 +01006075/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6076 * to disable SNI.
6077 */
Willy Tarreau63076412015-07-10 11:33:32 +02006078void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6079{
6080#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006081 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006082
Willy Tarreau119a4082016-12-22 21:58:38 +01006083 char *prev_name;
6084
Willy Tarreau63076412015-07-10 11:33:32 +02006085 if (!ssl_sock_is_ssl(conn))
6086 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006087 ctx = conn->xprt_ctx;
Willy Tarreau63076412015-07-10 11:33:32 +02006088
Willy Tarreau119a4082016-12-22 21:58:38 +01006089 /* if the SNI changes, we must destroy the reusable context so that a
6090 * new connection will present a new SNI. As an optimization we could
6091 * later imagine having a small cache of ssl_ctx to hold a few SNI per
6092 * server.
6093 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006094 prev_name = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau119a4082016-12-22 21:58:38 +01006095 if ((!prev_name && hostname) ||
6096 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006097 SSL_set_session(ctx->ssl, NULL);
Willy Tarreau119a4082016-12-22 21:58:38 +01006098
Olivier Houchard66ab4982019-02-26 18:37:15 +01006099 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006100#endif
6101}
6102
Emeric Brun0abf8362014-06-24 18:26:41 +02006103/* Extract peer certificate's common name into the chunk dest
6104 * Returns
6105 * the len of the extracted common name
6106 * or 0 if no CN found in DN
6107 * or -1 on error case (i.e. no peer certificate)
6108 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006109int ssl_sock_get_remote_common_name(struct connection *conn,
6110 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006111{
Christopher Faulet82004142019-09-10 10:12:03 +02006112 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04006113 X509 *crt = NULL;
6114 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006115 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006116 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006117 .area = (char *)&find_cn,
6118 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006119 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006120 int result = -1;
David Safb76832014-05-08 23:42:08 -04006121
6122 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02006123 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02006124 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006125
6126 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006127 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006128 if (!crt)
6129 goto out;
6130
6131 name = X509_get_subject_name(crt);
6132 if (!name)
6133 goto out;
David Safb76832014-05-08 23:42:08 -04006134
Emeric Brun0abf8362014-06-24 18:26:41 +02006135 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6136out:
David Safb76832014-05-08 23:42:08 -04006137 if (crt)
6138 X509_free(crt);
6139
6140 return result;
6141}
6142
Dave McCowan328fb582014-07-30 10:39:13 -04006143/* returns 1 if client passed a certificate for this session, 0 if not */
6144int ssl_sock_get_cert_used_sess(struct connection *conn)
6145{
Christopher Faulet82004142019-09-10 10:12:03 +02006146 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006147 X509 *crt = NULL;
6148
6149 if (!ssl_sock_is_ssl(conn))
6150 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006151 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006152
6153 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006154 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006155 if (!crt)
6156 return 0;
6157
6158 X509_free(crt);
6159 return 1;
6160}
6161
6162/* returns 1 if client passed a certificate for this connection, 0 if not */
6163int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006164{
Christopher Faulet82004142019-09-10 10:12:03 +02006165 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006166
David Safb76832014-05-08 23:42:08 -04006167 if (!ssl_sock_is_ssl(conn))
6168 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006169 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006170 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006171}
6172
6173/* returns result from SSL verify */
6174unsigned int ssl_sock_get_verify_result(struct connection *conn)
6175{
Christopher Faulet82004142019-09-10 10:12:03 +02006176 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006177
David Safb76832014-05-08 23:42:08 -04006178 if (!ssl_sock_is_ssl(conn))
6179 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006180 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006181 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006182}
6183
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006184/* Returns the application layer protocol name in <str> and <len> when known.
6185 * Zero is returned if the protocol name was not found, otherwise non-zero is
6186 * returned. The string is allocated in the SSL context and doesn't have to be
6187 * freed by the caller. NPN is also checked if available since older versions
6188 * of openssl (1.0.1) which are more common in field only support this one.
6189 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006190static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006191{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006192#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6193 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006194 struct ssl_sock_ctx *ctx = xprt_ctx;
6195 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006196 return 0;
6197
6198 *str = NULL;
6199
6200#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006201 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006202 if (*str)
6203 return 1;
6204#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006205#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006206 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006207 if (*str)
6208 return 1;
6209#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006210#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006211 return 0;
6212}
6213
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006214/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006215int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006216{
6217 X509 *ca;
6218 X509_NAME *name = NULL;
6219 ASN1_OCTET_STRING *skid = NULL;
6220 STACK_OF(X509) *chain = NULL;
6221 struct issuer_chain *issuer;
6222 struct eb64_node *node;
6223 char *path;
6224 u64 key;
6225 int ret = 0;
6226
6227 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6228 if (chain == NULL) {
6229 chain = sk_X509_new_null();
6230 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6231 name = X509_get_subject_name(ca);
6232 }
6233 if (!sk_X509_push(chain, ca)) {
6234 X509_free(ca);
6235 goto end;
6236 }
6237 }
6238 if (!chain) {
6239 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6240 goto end;
6241 }
6242 if (!skid) {
6243 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6244 goto end;
6245 }
6246 if (!name) {
6247 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6248 goto end;
6249 }
6250 key = XXH64(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006251 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006252 issuer = container_of(node, typeof(*issuer), node);
6253 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6254 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6255 goto end;
6256 }
6257 }
6258 issuer = calloc(1, sizeof *issuer);
6259 path = strdup(fp);
6260 if (!issuer || !path) {
6261 free(issuer);
6262 free(path);
6263 goto end;
6264 }
6265 issuer->node.key = key;
6266 issuer->path = path;
6267 issuer->chain = chain;
6268 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006269 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006270 ret = 1;
6271 end:
6272 if (skid)
6273 ASN1_OCTET_STRING_free(skid);
6274 if (chain)
6275 sk_X509_pop_free(chain, X509_free);
6276 return ret;
6277}
6278
William Lallemandda8584c2020-05-14 10:14:37 +02006279 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006280{
6281 AUTHORITY_KEYID *akid;
6282 struct issuer_chain *issuer = NULL;
6283
6284 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemand829d0712020-11-19 16:24:13 +01006285 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006286 struct eb64_node *node;
6287 u64 hk;
6288 hk = XXH64(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
6289 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6290 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6291 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6292 issuer = ti;
6293 break;
6294 }
6295 }
6296 AUTHORITY_KEYID_free(akid);
6297 }
6298 return issuer;
6299}
6300
William Lallemanddad31052020-05-14 17:47:32 +02006301void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006302{
6303 struct eb64_node *node, *back;
6304 struct issuer_chain *issuer;
6305
William Lallemande0f3fd52020-02-25 14:53:06 +01006306 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006307 while (node) {
6308 issuer = container_of(node, typeof(*issuer), node);
6309 back = eb64_next(node);
6310 eb64_delete(node);
6311 free(issuer->path);
6312 sk_X509_pop_free(issuer->chain, X509_free);
6313 free(issuer);
6314 node = back;
6315 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006316}
6317
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006318#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006319static int ssl_check_async_engine_count(void) {
6320 int err_code = 0;
6321
Emeric Brun3854e012017-05-17 20:42:48 +02006322 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006323 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006324 err_code = ERR_ABORT;
6325 }
6326 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006327}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006328#endif
6329
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006330/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau767dedd2021-01-21 08:53:50 +01006331 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006332 */
Willy Tarreau6cb467e2021-01-21 08:26:06 +01006333static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006334{
6335 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau767dedd2021-01-21 08:53:50 +01006336 int ret = 0;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006337
6338 if (!sctx)
Willy Tarreau767dedd2021-01-21 08:53:50 +01006339 return ret;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006340
Willy Tarreau767dedd2021-01-21 08:53:50 +01006341 if (sctx->conn != conn) {
6342 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6343 ret = 1;
6344 }
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006345 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6346
6347 if (sctx->xprt) {
6348 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6349 if (sctx->xprt_ctx)
6350 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6351 }
6352
6353 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau767dedd2021-01-21 08:53:50 +01006354
6355 /* as soon as a shutdown is reported the lower layer unregisters its
6356 * subscriber, so the situations below are transient and rare enough to
6357 * be reported as suspicious. In any case they shouldn't last.
6358 */
6359 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
6360 ret = 1;
6361 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
6362 ret = 1;
6363
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006364 chunk_appendf(&trash, " .subs=%p", sctx->subs);
6365 if (sctx->subs) {
6366 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau767dedd2021-01-21 08:53:50 +01006367 if (sctx->subs->tasklet->calls >= 1000000)
6368 ret = 1;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006369 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
6370 sctx->subs->tasklet->calls,
6371 sctx->subs->tasklet->context);
6372 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
6373 chunk_appendf(&trash, ")");
6374 }
6375 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
6376 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau767dedd2021-01-21 08:53:50 +01006377 return ret;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006378}
6379
William Lallemand32af2032016-10-29 18:09:35 +02006380/* This function is used with TLS ticket keys management. It permits to browse
6381 * each reference. The variable <getnext> must contain the current node,
6382 * <end> point to the root node.
6383 */
6384#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6385static inline
6386struct tls_keys_ref *tlskeys_list_get_next(struct tls_keys_ref *getnext, struct list *end)
6387{
6388 struct tls_keys_ref *ref = getnext;
6389
6390 while (1) {
6391
6392 /* Get next list entry. */
6393 ref = LIST_NEXT(&ref->list, struct tls_keys_ref *, list);
6394
6395 /* If the entry is the last of the list, return NULL. */
6396 if (&ref->list == end)
6397 return NULL;
6398
6399 return ref;
6400 }
6401}
6402
6403static inline
6404struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6405{
6406 int id;
6407 char *error;
6408
6409 /* If the reference starts by a '#', this is numeric id. */
6410 if (reference[0] == '#') {
6411 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6412 id = strtol(reference + 1, &error, 10);
6413 if (*error != '\0')
6414 return NULL;
6415
6416 /* Perform the unique id lookup. */
6417 return tlskeys_ref_lookupid(id);
6418 }
6419
6420 /* Perform the string lookup. */
6421 return tlskeys_ref_lookup(reference);
6422}
6423#endif
6424
6425
6426#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6427
6428static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6429
6430static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6431 return cli_io_handler_tlskeys_files(appctx);
6432}
6433
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006434/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6435 * (next index to be dumped), and cli.p0 (next key reference).
6436 */
William Lallemand32af2032016-10-29 18:09:35 +02006437static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6438
6439 struct stream_interface *si = appctx->owner;
6440
6441 switch (appctx->st2) {
6442 case STAT_ST_INIT:
6443 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006444 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006445 * later and restart at the state "STAT_ST_INIT".
6446 */
6447 chunk_reset(&trash);
6448
6449 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6450 chunk_appendf(&trash, "# id secret\n");
6451 else
6452 chunk_appendf(&trash, "# id (file)\n");
6453
Willy Tarreau06d80a92017-10-19 14:32:15 +02006454 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006455 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006456 return 0;
6457 }
6458
William Lallemand32af2032016-10-29 18:09:35 +02006459 /* Now, we start the browsing of the references lists.
6460 * Note that the following call to LIST_ELEM return bad pointer. The only
6461 * available field of this pointer is <list>. It is used with the function
6462 * tlskeys_list_get_next() for retruning the first available entry
6463 */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006464 if (appctx->ctx.cli.p0 == NULL) {
6465 appctx->ctx.cli.p0 = LIST_ELEM(&tlskeys_reference, struct tls_keys_ref *, list);
6466 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006467 }
6468
6469 appctx->st2 = STAT_ST_LIST;
6470 /* fall through */
6471
6472 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006473 while (appctx->ctx.cli.p0) {
6474 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006475
6476 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006477 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006478 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006479
6480 if (appctx->ctx.cli.i1 == 0)
6481 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6482
William Lallemand32af2032016-10-29 18:09:35 +02006483 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006484 int head;
6485
6486 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6487 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006488 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006489 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006490
6491 chunk_reset(t2);
6492 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006493 if (ref->key_size_bits == 128) {
6494 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6495 sizeof(struct tls_sess_key_128),
6496 t2->area, t2->size);
6497 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6498 t2->area);
6499 }
6500 else if (ref->key_size_bits == 256) {
6501 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6502 sizeof(struct tls_sess_key_256),
6503 t2->area, t2->size);
6504 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6505 t2->area);
6506 }
6507 else {
6508 /* This case should never happen */
6509 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6510 }
William Lallemand32af2032016-10-29 18:09:35 +02006511
Willy Tarreau06d80a92017-10-19 14:32:15 +02006512 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006513 /* let's try again later from this stream. We add ourselves into
6514 * this stream's users so that it can remove us upon termination.
6515 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006516 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006517 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006518 return 0;
6519 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006520 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006521 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006522 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006523 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006524 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006525 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006526 /* let's try again later from this stream. We add ourselves into
6527 * this stream's users so that it can remove us upon termination.
6528 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006529 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006530 return 0;
6531 }
6532
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006533 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006534 break;
6535
6536 /* get next list entry and check the end of the list */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006537 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006538 }
6539
6540 appctx->st2 = STAT_ST_FIN;
6541 /* fall through */
6542
6543 default:
6544 appctx->st2 = STAT_ST_FIN;
6545 return 1;
6546 }
6547 return 0;
6548}
6549
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006550/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006551static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006552{
William Lallemand32af2032016-10-29 18:09:35 +02006553 /* no parameter, shows only file list */
6554 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006555 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006556 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006557 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006558 }
6559
6560 if (args[2][0] == '*') {
6561 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006562 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006563 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006564 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006565 if (!appctx->ctx.cli.p0)
6566 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006567 }
William Lallemand32af2032016-10-29 18:09:35 +02006568 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006569 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006570}
6571
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006572static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006573{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006574 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006575 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006576
William Lallemand32af2032016-10-29 18:09:35 +02006577 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006578 if (!*args[3] || !*args[4])
6579 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 +02006580
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006581 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006582 if (!ref)
6583 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006584
Willy Tarreau1c913e42018-08-22 05:26:57 +02006585 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006586 if (ret < 0)
6587 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006588
Willy Tarreau1c913e42018-08-22 05:26:57 +02006589 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006590 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6591 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006592
Willy Tarreau9d008692019-08-09 11:21:01 +02006593 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006594}
William Lallemandd4f946c2019-12-05 10:26:40 +01006595#endif
William Lallemand419e6342020-04-08 12:05:39 +02006596
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006597static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006598{
6599#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6600 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006601 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006602
6603 if (!payload)
6604 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006605
6606 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006607 if (!*payload)
6608 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006609
6610 /* remove \r and \n from the payload */
6611 for (i = 0, j = 0; payload[i]; i++) {
6612 if (payload[i] == '\r' || payload[i] == '\n')
6613 continue;
6614 payload[j++] = payload[i];
6615 }
6616 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006617
Willy Tarreau1c913e42018-08-22 05:26:57 +02006618 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006619 if (ret < 0)
6620 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006621
Willy Tarreau1c913e42018-08-22 05:26:57 +02006622 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02006623 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02006624 if (err)
6625 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
6626 else
6627 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006628 }
Willy Tarreau9d008692019-08-09 11:21:01 +02006629
6630 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006631#else
Willy Tarreau9d008692019-08-09 11:21:01 +02006632 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 +02006633#endif
6634
Elliot Otchet71f82972020-01-15 08:12:14 -05006635}
6636
William Lallemand32af2032016-10-29 18:09:35 +02006637/* register cli keywords */
6638static struct cli_kw_list cli_kws = {{ },{
6639#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6640 { { "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 },
Lukas Tribusf4bbc432017-10-24 12:26:31 +02006641 { { "set", "ssl", "tls-key", NULL }, "set ssl tls-key [id|keyfile] <tlskey>: set the next TLS key for the <id> or <keyfile> listener to <tlskey>", cli_parse_set_tlskeys, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02006642#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006643 { { "set", "ssl", "ocsp-response", NULL }, NULL, cli_parse_set_ocspresponse, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02006644 { { NULL }, NULL, NULL, NULL }
6645}};
6646
Willy Tarreau0108d902018-11-25 19:14:37 +01006647INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02006648
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02006649/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02006650struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02006651 .snd_buf = ssl_sock_from_buf,
6652 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01006653 .subscribe = ssl_subscribe,
6654 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02006655 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02006656 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02006657 .rcv_pipe = NULL,
6658 .snd_pipe = NULL,
6659 .shutr = NULL,
6660 .shutw = ssl_sock_shutw,
6661 .close = ssl_sock_close,
6662 .init = ssl_sock_init,
Willy Tarreau55d37912016-12-21 23:38:39 +01006663 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01006664 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01006665 .prepare_srv = ssl_sock_prepare_srv_ctx,
6666 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006667 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006668 .takeover = ssl_takeover,
Willy Tarreaub0d3a282021-03-02 17:29:56 +01006669 .set_idle = ssl_set_idle,
6670 .set_used = ssl_set_used,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01006671 .name = "SSL",
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006672 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02006673};
6674
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006675enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
6676 struct session *sess, struct stream *s, int flags)
6677{
6678 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006679 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006680
6681 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006682 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006683
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006684 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006685 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006686 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006687 s->req.flags |= CF_READ_NULL;
6688 return ACT_RET_YIELD;
6689 }
6690 }
6691 return (ACT_RET_CONT);
6692}
6693
6694static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
6695{
6696 rule->action_ptr = ssl_action_wait_for_hs;
6697
6698 return ACT_RET_PRS_OK;
6699}
6700
6701static struct action_kw_list http_req_actions = {ILH, {
6702 { "wait-for-handshake", ssl_parse_wait_for_hs },
6703 { /* END */ }
6704}};
6705
Willy Tarreau0108d902018-11-25 19:14:37 +01006706INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
6707
Ilya Shipitsin49bab752021-02-06 18:59:22 +05006708#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006709
6710static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6711{
6712 if (ptr) {
6713 chunk_destroy(ptr);
6714 free(ptr);
6715 }
6716}
6717
6718#endif
William Lallemand76b4a122020-08-04 17:41:39 +02006719
6720#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
6721static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6722{
6723 struct ocsp_cbk_arg *ocsp_arg;
6724
6725 if (ptr) {
6726 ocsp_arg = ptr;
6727
6728 if (ocsp_arg->is_single) {
6729 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
6730 ocsp_arg->s_ocsp = NULL;
6731 } else {
6732 int i;
6733
6734 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
6735 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
6736 ocsp_arg->m_ocsp[i] = NULL;
6737 }
6738 }
6739 free(ocsp_arg);
6740 }
6741}
6742#endif
6743
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006744static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6745{
Willy Tarreaubafbe012017-11-24 17:34:44 +01006746 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006747}
William Lallemand7d42ef52020-07-06 11:41:30 +02006748
William Lallemandb3246942021-06-09 16:46:12 +02006749#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02006750static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6751{
6752 struct ssl_keylog *keylog;
6753
6754 if (!ptr)
6755 return;
6756
6757 keylog = ptr;
6758
6759 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
6760 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
6761 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
6762 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
6763 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
6764 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
6765 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
6766 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
6767
6768 pool_free(pool_head_ssl_keylog, ptr);
6769}
6770#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006771
Emeric Brun46591952012-05-18 15:47:34 +02006772__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02006773static void __ssl_sock_init(void)
6774{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006775#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006776 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006777 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006778#endif
Emeric Brun46591952012-05-18 15:47:34 +02006779
Willy Tarreauef934602016-12-22 23:12:01 +01006780 if (global_ssl.listen_default_ciphers)
6781 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
6782 if (global_ssl.connect_default_ciphers)
6783 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Emmanuel Hocdet839af572019-05-14 16:27:35 +02006784#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02006785 if (global_ssl.listen_default_ciphersuites)
6786 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
6787 if (global_ssl.connect_default_ciphersuites)
6788 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
6789#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01006790
Willy Tarreau13e14102016-12-22 20:25:26 +01006791 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006792#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02006793 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08006794#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006795#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006796 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006797 n = sk_SSL_COMP_num(cm);
6798 while (n--) {
6799 (void) sk_SSL_COMP_pop(cm);
6800 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006801#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006802
Willy Tarreau5db847a2019-05-09 14:13:35 +02006803#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006804 ssl_locking_init();
6805#endif
Ilya Shipitsin49bab752021-02-06 18:59:22 +05006806#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006807 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
6808#endif
William Lallemand76b4a122020-08-04 17:41:39 +02006809
6810#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
6811 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
6812#endif
6813
Thierry FOURNIER28962c92018-06-17 21:37:05 +02006814 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02006815 ssl_capture_ptr_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_capture_free_func);
William Lallemandb3246942021-06-09 16:46:12 +02006816#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02006817 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
6818#endif
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006819#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006820 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006821 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006822#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01006823#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6824 hap_register_post_check(tlskeys_finalize_config);
6825#endif
Willy Tarreau80713382018-11-26 10:19:54 +01006826
6827 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
6828 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
6829
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006830 hap_register_post_deinit(ssl_free_global_issuers);
6831
Willy Tarreau80713382018-11-26 10:19:54 +01006832#ifndef OPENSSL_NO_DH
6833 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
6834 hap_register_post_deinit(ssl_free_dh);
6835#endif
6836#ifndef OPENSSL_NO_ENGINE
6837 hap_register_post_deinit(ssl_free_engines);
6838#endif
6839 /* Load SSL string for the verbose & debug mode. */
6840 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02006841 ha_meth = BIO_meth_new(0x666, "ha methods");
6842 BIO_meth_set_write(ha_meth, ha_ssl_write);
6843 BIO_meth_set_read(ha_meth, ha_ssl_read);
6844 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
6845 BIO_meth_set_create(ha_meth, ha_ssl_new);
6846 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
6847 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
6848 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02006849
6850 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006851
Dragan Dosen9ac98092020-05-11 15:51:45 +02006852 /* Try to register dedicated SSL/TLS protocol message callbacks for
6853 * heartbleed attack (CVE-2014-0160) and clienthello.
6854 */
6855 hap_register_post_check(ssl_sock_register_msg_callbacks);
6856
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006857 /* Try to free all callbacks that were registered by using
6858 * ssl_sock_register_msg_callback().
6859 */
6860 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01006861}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01006862
Willy Tarreau80713382018-11-26 10:19:54 +01006863/* Compute and register the version string */
6864static void ssl_register_build_options()
6865{
6866 char *ptr = NULL;
6867 int i;
6868
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006869 memprintf(&ptr, "Built with OpenSSL version : "
6870#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006871 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006872#else /* OPENSSL_IS_BORINGSSL */
6873 OPENSSL_VERSION_TEXT
6874 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08006875 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02006876 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006877#endif
6878 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006879#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006880 "no (library version too old)"
6881#elif defined(OPENSSL_NO_TLSEXT)
6882 "no (disabled via OPENSSL_NO_TLSEXT)"
6883#else
6884 "yes"
6885#endif
6886 "", ptr);
6887
6888 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
6889#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
6890 "yes"
6891#else
6892#ifdef OPENSSL_NO_TLSEXT
6893 "no (because of OPENSSL_NO_TLSEXT)"
6894#else
6895 "no (version might be too old, 0.9.8f min needed)"
6896#endif
6897#endif
6898 "", ptr);
6899
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02006900 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
6901 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
6902 if (methodVersions[i].option)
6903 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006904
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006905 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01006906}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006907
Willy Tarreau80713382018-11-26 10:19:54 +01006908INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02006909
Emeric Brun46591952012-05-18 15:47:34 +02006910
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006911#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006912void ssl_free_engines(void) {
6913 struct ssl_engine_list *wl, *wlb;
6914 /* free up engine list */
6915 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
6916 ENGINE_finish(wl->e);
6917 ENGINE_free(wl->e);
6918 LIST_DEL(&wl->list);
6919 free(wl);
6920 }
6921}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006922#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02006923
Remi Gacogned3a23c32015-05-28 16:39:47 +02006924#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00006925void ssl_free_dh(void) {
6926 if (local_dh_1024) {
6927 DH_free(local_dh_1024);
6928 local_dh_1024 = NULL;
6929 }
6930 if (local_dh_2048) {
6931 DH_free(local_dh_2048);
6932 local_dh_2048 = NULL;
6933 }
6934 if (local_dh_4096) {
6935 DH_free(local_dh_4096);
6936 local_dh_4096 = NULL;
6937 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02006938 if (global_dh) {
6939 DH_free(global_dh);
6940 global_dh = NULL;
6941 }
Grant Zhang872f9c22017-01-21 01:10:18 +00006942}
6943#endif
6944
6945__attribute__((destructor))
6946static void __ssl_sock_deinit(void)
6947{
6948#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006949 if (ssl_ctx_lru_tree) {
6950 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01006951 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02006952 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02006953#endif
6954
Willy Tarreau5db847a2019-05-09 14:13:35 +02006955#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006956 ERR_remove_state(0);
6957 ERR_free_strings();
6958
6959 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08006960#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02006961
Willy Tarreau5db847a2019-05-09 14:13:35 +02006962#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006963 CRYPTO_cleanup_all_ex_data();
6964#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02006965 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02006966}
6967
Emeric Brun46591952012-05-18 15:47:34 +02006968/*
6969 * Local variables:
6970 * c-indent-level: 8
6971 * c-basic-offset: 8
6972 * End:
6973 */