blob: 630aa5723c2b72aea7dc7cbae97115ed52cb8557 [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,
Ilya Shipitsin04a5a442020-11-03 14:15:38 +0500133#ifdef HAVE_OPENSSL_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
Ilya Shipitsin04a5a442020-11-03 14:15:38 +0500449#ifdef HAVE_OPENSSL_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
Ilya Shipitsin04a5a442020-11-03 14:15:38 +0500525#ifdef HAVE_OPENSSL_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 }
Ilya Shipitsin04a5a442020-11-03 14:15:38 +0500570#ifdef HAVE_OPENSSL_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));
648 el->e = engine;
649 LIST_ADD(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100650 nb_engines++;
651 if (global_ssl.async)
652 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000653 return 0;
654
655fail_set_method:
656 /* release the functional reference from ENGINE_init() */
657 ENGINE_finish(engine);
658
659fail_init:
660 /* release the structural reference from ENGINE_by_id() */
661 ENGINE_free(engine);
662
663fail_get:
664 return err_code;
665}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200666#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000667
Willy Tarreau5db847a2019-05-09 14:13:35 +0200668#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +0200669/*
670 * openssl async fd handler
671 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200672void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000673{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200674 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000675
Emeric Brun3854e012017-05-17 20:42:48 +0200676 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000677 * to poll this fd until it is requested
678 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000679 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000680 fd_cant_recv(fd);
681
682 /* crypto engine is available, let's notify the associated
683 * connection that it can pursue its processing.
684 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200685 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000686}
687
Emeric Brun3854e012017-05-17 20:42:48 +0200688/*
689 * openssl async delayed SSL_free handler
690 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200691void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000692{
693 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200694 OSSL_ASYNC_FD all_fd[32];
695 size_t num_all_fds = 0;
696 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000697
Emeric Brun3854e012017-05-17 20:42:48 +0200698 /* We suppose that the async job for a same SSL *
699 * are serialized. So if we are awake it is
700 * because the running job has just finished
701 * and we can remove all async fds safely
702 */
703 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
704 if (num_all_fds > 32) {
705 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
706 return;
707 }
708
709 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
710 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200711 fd_stop_both(all_fd[i]);
Emeric Brun3854e012017-05-17 20:42:48 +0200712
713 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000714 SSL_free(ssl);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +0100715 _HA_ATOMIC_SUB(&sslconns, 1);
716 _HA_ATOMIC_SUB(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000717}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000718/*
Emeric Brun3854e012017-05-17 20:42:48 +0200719 * function used to manage a returned SSL_ERROR_WANT_ASYNC
720 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000721 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200722static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000723{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100724 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200725 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200726 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000727 size_t num_add_fds = 0;
728 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200729 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000730
731 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
732 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200733 if (num_add_fds > 32 || num_del_fds > 32) {
734 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 +0000735 return;
736 }
737
Emeric Brun3854e012017-05-17 20:42:48 +0200738 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000739
Emeric Brun3854e012017-05-17 20:42:48 +0200740 /* We remove unused fds from the fdtab */
741 for (i=0 ; i < num_del_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200742 fd_stop_both(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000743
Emeric Brun3854e012017-05-17 20:42:48 +0200744 /* We add new fds to the fdtab */
745 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200746 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000747 }
748
Emeric Brun3854e012017-05-17 20:42:48 +0200749 num_add_fds = 0;
750 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
751 if (num_add_fds > 32) {
752 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
753 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000754 }
Emeric Brun3854e012017-05-17 20:42:48 +0200755
756 /* We activate the polling for all known async fds */
757 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000758 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200759 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000760 /* To ensure that the fd cache won't be used
761 * We'll prefer to catch a real RD event
762 * because handling an EAGAIN on this fd will
763 * result in a context switch and also
764 * some engines uses a fd in blocking mode.
765 */
766 fd_cant_recv(add_fd[i]);
767 }
Emeric Brun3854e012017-05-17 20:42:48 +0200768
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000769}
770#endif
771
William Lallemand104a7a62019-10-14 14:14:59 +0200772#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200773/*
774 * This function returns the number of seconds elapsed
775 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
776 * date presented un ASN1_GENERALIZEDTIME.
777 *
778 * In parsing error case, it returns -1.
779 */
780static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
781{
782 long epoch;
783 char *p, *end;
784 const unsigned short month_offset[12] = {
785 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
786 };
787 int year, month;
788
789 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
790
791 p = (char *)d->data;
792 end = p + d->length;
793
794 if (end - p < 4) return -1;
795 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
796 p += 4;
797 if (end - p < 2) return -1;
798 month = 10 * (p[0] - '0') + p[1] - '0';
799 if (month < 1 || month > 12) return -1;
800 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
801 We consider leap years and the current month (<marsh or not) */
802 epoch = ( ((year - 1970) * 365)
803 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
804 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
805 + month_offset[month-1]
806 ) * 24 * 60 * 60;
807 p += 2;
808 if (end - p < 2) return -1;
809 /* Add the number of seconds of completed days of current month */
810 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
811 p += 2;
812 if (end - p < 2) return -1;
813 /* Add the completed hours of the current day */
814 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
815 p += 2;
816 if (end - p < 2) return -1;
817 /* Add the completed minutes of the current hour */
818 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
819 p += 2;
820 if (p == end) return -1;
821 /* Test if there is available seconds */
822 if (p[0] < '0' || p[0] > '9')
823 goto nosec;
824 if (end - p < 2) return -1;
825 /* Add the seconds of the current minute */
826 epoch += 10 * (p[0] - '0') + p[1] - '0';
827 p += 2;
828 if (p == end) return -1;
829 /* Ignore seconds float part if present */
830 if (p[0] == '.') {
831 do {
832 if (++p == end) return -1;
833 } while (p[0] >= '0' && p[0] <= '9');
834 }
835
836nosec:
837 if (p[0] == 'Z') {
838 if (end - p != 1) return -1;
839 return epoch;
840 }
841 else if (p[0] == '+') {
842 if (end - p != 5) return -1;
843 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700844 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 +0200845 }
846 else if (p[0] == '-') {
847 if (end - p != 5) return -1;
848 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700849 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 +0200850 }
851
852 return -1;
853}
854
William Lallemand104a7a62019-10-14 14:14:59 +0200855/*
856 * struct alignment works here such that the key.key is the same as key_data
857 * Do not change the placement of key_data
858 */
859struct certificate_ocsp {
860 struct ebmb_node key;
861 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
862 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200863 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200864 long expire;
865};
866
867struct ocsp_cbk_arg {
868 int is_single;
869 int single_kt;
870 union {
871 struct certificate_ocsp *s_ocsp;
872 /*
873 * m_ocsp will have multiple entries dependent on key type
874 * Entry 0 - DSA
875 * Entry 1 - ECDSA
876 * Entry 2 - RSA
877 */
878 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
879 };
880};
881
Emeric Brun1d3865b2014-06-20 15:37:32 +0200882static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200883
884/* This function starts to check if the OCSP response (in DER format) contained
885 * in chunk 'ocsp_response' is valid (else exits on error).
886 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
887 * contained in the OCSP Response and exits on error if no match.
888 * If it's a valid OCSP Response:
889 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
890 * pointed by 'ocsp'.
891 * If 'ocsp' is NULL, the function looks up into the OCSP response's
892 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
893 * from the response) and exits on error if not found. Finally, If an OCSP response is
894 * already present in the container, it will be overwritten.
895 *
896 * Note: OCSP response containing more than one OCSP Single response is not
897 * considered valid.
898 *
899 * Returns 0 on success, 1 in error case.
900 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200901static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
902 struct certificate_ocsp *ocsp,
903 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200904{
905 OCSP_RESPONSE *resp;
906 OCSP_BASICRESP *bs = NULL;
907 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200908 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200909 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200910 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200911 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200912 int reason;
913 int ret = 1;
914
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200915 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
916 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200917 if (!resp) {
918 memprintf(err, "Unable to parse OCSP response");
919 goto out;
920 }
921
922 rc = OCSP_response_status(resp);
923 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
924 memprintf(err, "OCSP response status not successful");
925 goto out;
926 }
927
928 bs = OCSP_response_get1_basic(resp);
929 if (!bs) {
930 memprintf(err, "Failed to get basic response from OCSP Response");
931 goto out;
932 }
933
934 count_sr = OCSP_resp_count(bs);
935 if (count_sr > 1) {
936 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
937 goto out;
938 }
939
940 sr = OCSP_resp_get0(bs, 0);
941 if (!sr) {
942 memprintf(err, "Failed to get OCSP single response");
943 goto out;
944 }
945
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200946 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
947
Emeric Brun4147b2e2014-06-16 18:36:30 +0200948 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200949 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200950 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200951 goto out;
952 }
953
Emeric Brun13a6b482014-06-20 15:44:34 +0200954 if (!nextupd) {
955 memprintf(err, "OCSP single response: missing nextupdate");
956 goto out;
957 }
958
Emeric Brunc8b27b62014-06-19 14:16:17 +0200959 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200960 if (!rc) {
961 memprintf(err, "OCSP single response: no longer valid.");
962 goto out;
963 }
964
965 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200966 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +0200967 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
968 goto out;
969 }
970 }
971
972 if (!ocsp) {
973 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
974 unsigned char *p;
975
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200976 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200977 if (!rc) {
978 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
979 goto out;
980 }
981
982 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
983 memprintf(err, "OCSP single response: Certificate ID too long");
984 goto out;
985 }
986
987 p = key;
988 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200989 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200990 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
991 if (!ocsp) {
992 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
993 goto out;
994 }
995 }
996
997 /* According to comments on "chunk_dup", the
998 previous chunk buffer will be freed */
999 if (!chunk_dup(&ocsp->response, ocsp_response)) {
1000 memprintf(err, "OCSP response: Memory allocation error");
1001 goto out;
1002 }
1003
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001004 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
1005
Emeric Brun4147b2e2014-06-16 18:36:30 +02001006 ret = 0;
1007out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001008 ERR_clear_error();
1009
Emeric Brun4147b2e2014-06-16 18:36:30 +02001010 if (bs)
1011 OCSP_BASICRESP_free(bs);
1012
1013 if (resp)
1014 OCSP_RESPONSE_free(resp);
1015
1016 return ret;
1017}
1018/*
1019 * External function use to update the OCSP response in the OCSP response's
1020 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1021 * to update in DER format.
1022 *
1023 * Returns 0 on success, 1 in error case.
1024 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001025int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001026{
1027 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1028}
1029
William Lallemand4a660132019-10-14 14:51:41 +02001030#endif
1031
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001032#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1033static 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)
1034{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001035 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001036 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001037 struct connection *conn;
1038 int head;
1039 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001040 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001041
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001042 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001043 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001044 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1045
1046 keys = ref->tlskeys;
1047 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001048
1049 if (enc) {
1050 memcpy(key_name, keys[head].name, 16);
1051
1052 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001053 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001054
Emeric Brun9e754772019-01-10 17:51:55 +01001055 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001056
Emeric Brun9e754772019-01-10 17:51:55 +01001057 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1058 goto end;
1059
Willy Tarreau9356dac2019-05-10 09:22:53 +02001060 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001061 ret = 1;
1062 }
1063 else if (ref->key_size_bits == 256 ) {
1064
1065 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1066 goto end;
1067
Willy Tarreau9356dac2019-05-10 09:22:53 +02001068 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001069 ret = 1;
1070 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001071 } else {
1072 for (i = 0; i < TLS_TICKETS_NO; i++) {
1073 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1074 goto found;
1075 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001076 ret = 0;
1077 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001078
Christopher Faulet16f45c82018-02-16 11:23:49 +01001079 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001080 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001081 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 +01001082 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1083 goto end;
1084 /* 2 for key renewal, 1 if current key is still valid */
1085 ret = i ? 2 : 1;
1086 }
1087 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001088 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 +01001089 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1090 goto end;
1091 /* 2 for key renewal, 1 if current key is still valid */
1092 ret = i ? 2 : 1;
1093 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001094 }
Emeric Brun9e754772019-01-10 17:51:55 +01001095
Christopher Faulet16f45c82018-02-16 11:23:49 +01001096 end:
1097 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1098 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001099}
1100
1101struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1102{
1103 struct tls_keys_ref *ref;
1104
1105 list_for_each_entry(ref, &tlskeys_reference, list)
1106 if (ref->filename && strcmp(filename, ref->filename) == 0)
1107 return ref;
1108 return NULL;
1109}
1110
1111struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1112{
1113 struct tls_keys_ref *ref;
1114
1115 list_for_each_entry(ref, &tlskeys_reference, list)
1116 if (ref->unique_id == unique_id)
1117 return ref;
1118 return NULL;
1119}
1120
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001121/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001122 * match existing ones, this function returns -1
1123 * else it returns 0 on success.
1124 */
1125int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001126 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001127{
Emeric Brun9e754772019-01-10 17:51:55 +01001128 if (ref->key_size_bits == 128) {
1129 if (tlskey->data != sizeof(struct tls_sess_key_128))
1130 return -1;
1131 }
1132 else if (ref->key_size_bits == 256) {
1133 if (tlskey->data != sizeof(struct tls_sess_key_256))
1134 return -1;
1135 }
1136 else
1137 return -1;
1138
Christopher Faulet16f45c82018-02-16 11:23:49 +01001139 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001140 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1141 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001142 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1143 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001144
1145 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001146}
1147
Willy Tarreau83061a82018-07-13 11:56:34 +02001148int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001149{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001150 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1151
1152 if(!ref) {
1153 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1154 return 1;
1155 }
Emeric Brun9e754772019-01-10 17:51:55 +01001156 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1157 memprintf(err, "Invalid key size");
1158 return 1;
1159 }
1160
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001161 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001162}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001163
1164/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001165 * automatic ids. It's called just after the basic checks. It returns
1166 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001167 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001168static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001169{
1170 int i = 0;
1171 struct tls_keys_ref *ref, *ref2, *ref3;
1172 struct list tkr = LIST_HEAD_INIT(tkr);
1173
1174 list_for_each_entry(ref, &tlskeys_reference, list) {
1175 if (ref->unique_id == -1) {
1176 /* Look for the first free id. */
1177 while (1) {
1178 list_for_each_entry(ref2, &tlskeys_reference, list) {
1179 if (ref2->unique_id == i) {
1180 i++;
1181 break;
1182 }
1183 }
1184 if (&ref2->list == &tlskeys_reference)
1185 break;
1186 }
1187
1188 /* Uses the unique id and increment it for the next entry. */
1189 ref->unique_id = i;
1190 i++;
1191 }
1192 }
1193
1194 /* This sort the reference list by id. */
1195 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
1196 LIST_DEL(&ref->list);
1197 list_for_each_entry(ref3, &tkr, list) {
1198 if (ref->unique_id < ref3->unique_id) {
1199 LIST_ADDQ(&ref3->list, &ref->list);
1200 break;
1201 }
1202 }
1203 if (&ref3->list == &tkr)
1204 LIST_ADDQ(&tkr, &ref->list);
1205 }
1206
1207 /* swap root */
1208 LIST_ADD(&tkr, &tlskeys_reference);
1209 LIST_DEL(&tkr);
Willy Tarreaud1c57502016-12-22 22:46:15 +01001210 return 0;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001211}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001212#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1213
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001214#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001215int ocsp_ex_index = -1;
1216
yanbzhube2774d2015-12-10 15:07:30 -05001217int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1218{
1219 switch (evp_keytype) {
1220 case EVP_PKEY_RSA:
1221 return 2;
1222 case EVP_PKEY_DSA:
1223 return 0;
1224 case EVP_PKEY_EC:
1225 return 1;
1226 }
1227
1228 return -1;
1229}
1230
Emeric Brun4147b2e2014-06-16 18:36:30 +02001231/*
1232 * Callback used to set OCSP status extension content in server hello.
1233 */
1234int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1235{
yanbzhube2774d2015-12-10 15:07:30 -05001236 struct certificate_ocsp *ocsp;
1237 struct ocsp_cbk_arg *ocsp_arg;
1238 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001239 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001240 EVP_PKEY *ssl_pkey;
1241 int key_type;
1242 int index;
1243
William Lallemand76b4a122020-08-04 17:41:39 +02001244 ctx = SSL_get_SSL_CTX(ssl);
1245 if (!ctx)
1246 return SSL_TLSEXT_ERR_NOACK;
1247
1248 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1249 if (!ocsp_arg)
1250 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001251
1252 ssl_pkey = SSL_get_privatekey(ssl);
1253 if (!ssl_pkey)
1254 return SSL_TLSEXT_ERR_NOACK;
1255
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001256 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001257
1258 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1259 ocsp = ocsp_arg->s_ocsp;
1260 else {
1261 /* For multiple certs per context, we have to find the correct OCSP response based on
1262 * the certificate type
1263 */
1264 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1265
1266 if (index < 0)
1267 return SSL_TLSEXT_ERR_NOACK;
1268
1269 ocsp = ocsp_arg->m_ocsp[index];
1270
1271 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001272
1273 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001274 !ocsp->response.area ||
1275 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001276 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001277 return SSL_TLSEXT_ERR_NOACK;
1278
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001279 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001280 if (!ssl_buf)
1281 return SSL_TLSEXT_ERR_NOACK;
1282
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001283 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1284 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001285
1286 return SSL_TLSEXT_ERR_OK;
1287}
1288
William Lallemand4a660132019-10-14 14:51:41 +02001289#endif
1290
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001291#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001292
1293
1294/*
1295 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1296 * used anymore. Also removes it from the tree if free'd.
1297 */
1298static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1299{
1300 if (!ocsp)
1301 return;
1302
1303 ocsp->refcount--;
1304 if (ocsp->refcount <= 0) {
1305 ebmb_delete(&ocsp->key);
1306 chunk_destroy(&ocsp->response);
1307 free(ocsp);
1308 }
1309}
1310
1311
Emeric Brun4147b2e2014-06-16 18:36:30 +02001312/*
1313 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001314 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1315 * status extension, the issuer's certificate is mandatory. It should be
1316 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001317 *
William Lallemand246c0242019-10-11 08:59:13 +02001318 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1319 * OCSP response. If file is empty or content is not a valid OCSP response,
1320 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1321 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001322 *
1323 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001324 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001325 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001326static 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 +02001327{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001328 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001329 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001330 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001331 struct certificate_ocsp *ocsp = NULL, *iocsp;
1332 char *warn = NULL;
1333 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001334 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001335
Emeric Brun4147b2e2014-06-16 18:36:30 +02001336
William Lallemand246c0242019-10-11 08:59:13 +02001337 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001338 if (!x)
1339 goto out;
1340
William Lallemand246c0242019-10-11 08:59:13 +02001341 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001342 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1343 if (chain) {
1344 /* check if one of the certificate of the chain is the issuer */
1345 for (i = 0; i < sk_X509_num(chain); i++) {
1346 X509 *ti = sk_X509_value(chain, i);
1347 if (X509_check_issued(ti, x) == X509_V_OK) {
1348 issuer = ti;
1349 break;
1350 }
1351 }
1352 }
William Lallemand246c0242019-10-11 08:59:13 +02001353 if (!issuer)
1354 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001355
1356 cid = OCSP_cert_to_id(0, x, issuer);
1357 if (!cid)
1358 goto out;
1359
1360 i = i2d_OCSP_CERTID(cid, NULL);
1361 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1362 goto out;
1363
Vincent Bernat02779b62016-04-03 13:48:43 +02001364 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001365 if (!ocsp)
1366 goto out;
1367
1368 p = ocsp->key_data;
1369 i2d_OCSP_CERTID(cid, &p);
1370
1371 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1372 if (iocsp == ocsp)
1373 ocsp = NULL;
1374
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001375#ifndef SSL_CTX_get_tlsext_status_cb
1376# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1377 *cb = (void (*) (void))ctx->tlsext_status_cb;
1378#endif
1379 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1380
1381 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001382 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001383 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001384
William Lallemanda560c062020-07-31 11:43:20 +02001385 cb_arg = calloc(1, sizeof(*cb_arg));
1386 if (!cb_arg)
1387 goto out;
1388
yanbzhube2774d2015-12-10 15:07:30 -05001389 cb_arg->is_single = 1;
1390 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001391 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001392
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001393 pkey = X509_get_pubkey(x);
1394 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1395 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001396
1397 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001398 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 */
1399
yanbzhube2774d2015-12-10 15:07:30 -05001400 } else {
1401 /*
1402 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1403 * Update that cb_arg with the new cert's staple
1404 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001405 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001406 struct certificate_ocsp *tmp_ocsp;
1407 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001408 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001409 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001410
William Lallemand76b4a122020-08-04 17:41:39 +02001411 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001412
1413 /*
1414 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1415 * the order of operations below matter, take care when changing it
1416 */
1417 tmp_ocsp = cb_arg->s_ocsp;
1418 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1419 cb_arg->s_ocsp = NULL;
1420 cb_arg->m_ocsp[index] = tmp_ocsp;
1421 cb_arg->is_single = 0;
1422 cb_arg->single_kt = 0;
1423
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001424 pkey = X509_get_pubkey(x);
1425 key_type = EVP_PKEY_base_id(pkey);
1426 EVP_PKEY_free(pkey);
1427
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001428 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001429 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001430 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001431 iocsp->refcount++;
1432 }
yanbzhube2774d2015-12-10 15:07:30 -05001433 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001434
1435 ret = 0;
1436
1437 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001438 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001439 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001440 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001441 }
1442
1443out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001444 if (cid)
1445 OCSP_CERTID_free(cid);
1446
1447 if (ocsp)
1448 free(ocsp);
1449
1450 if (warn)
1451 free(warn);
1452
Emeric Brun4147b2e2014-06-16 18:36:30 +02001453 return ret;
1454}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001455#endif
1456
1457#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001458static 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 +02001459{
William Lallemand4a660132019-10-14 14:51:41 +02001460 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 +02001461}
1462#endif
1463
William Lallemand4a660132019-10-14 14:51:41 +02001464
Ilya Shipitsine4f38f92021-02-06 18:55:27 +05001465#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001466
1467#define CT_EXTENSION_TYPE 18
1468
William Lallemand03c331c2020-05-13 10:10:01 +02001469int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001470
1471int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1472{
Willy Tarreau83061a82018-07-13 11:56:34 +02001473 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001474
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001475 *out = (unsigned char *) sctl->area;
1476 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001477
1478 return 1;
1479}
1480
1481int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1482{
1483 return 1;
1484}
1485
William Lallemanda17f4112019-10-10 15:16:44 +02001486static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001487{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001488 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001489
William Lallemanda17f4112019-10-10 15:16:44 +02001490 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 +01001491 goto out;
1492
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001493 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1494
1495 ret = 0;
1496
1497out:
1498 return ret;
1499}
1500
1501#endif
1502
Emeric Brune1f38db2012-09-03 20:36:47 +02001503void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1504{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001505 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001506 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001507 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001508 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001509
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001510#ifndef SSL_OP_NO_RENEGOTIATION
1511 /* Please note that BoringSSL defines this macro to zero so don't
1512 * change this to #if and do not assign a default value to this macro!
1513 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001514 if (where & SSL_CB_HANDSHAKE_START) {
1515 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001516 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 +02001517 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001518 conn->err_code = CO_ER_SSL_RENEG;
1519 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001520 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001521#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001522
1523 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001524 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001525 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001526 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001527 consider that the buffering was activated,
1528 so we rise the output buffer size from 4k
1529 to 16k */
1530 write_bio = SSL_get_wbio(ssl);
1531 if (write_bio != SSL_get_rbio(ssl)) {
1532 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001533 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001534 }
1535 }
1536 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001537}
1538
Emeric Brune64aef12012-09-21 13:15:06 +02001539/* Callback is called for each certificate of the chain during a verify
1540 ok is set to 1 if preverify detect no error on current certificate.
1541 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001542int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001543{
1544 SSL *ssl;
1545 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001546 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001547 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001548
1549 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001550 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001551
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001552 ctx = conn->xprt_ctx;
1553
1554 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001555
Emeric Brun81c00f02012-09-21 14:31:21 +02001556 if (ok) /* no errors */
1557 return ok;
1558
1559 depth = X509_STORE_CTX_get_error_depth(x_store);
1560 err = X509_STORE_CTX_get_error(x_store);
1561
1562 /* check if CA error needs to be ignored */
1563 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001564 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1565 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1566 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001567 }
1568
Willy Tarreau731248f2020-02-04 14:02:02 +01001569 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001570 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001571 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001572 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001573 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001574
Willy Tarreau20879a02012-12-03 16:32:10 +01001575 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001576 return 0;
1577 }
1578
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001579 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1580 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001581
Emeric Brun81c00f02012-09-21 14:31:21 +02001582 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001583 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001584 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001585 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001586 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001587 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001588
Willy Tarreau20879a02012-12-03 16:32:10 +01001589 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001590 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001591}
1592
Dragan Dosen9ac98092020-05-11 15:51:45 +02001593#ifdef TLS1_RT_HEARTBEAT
1594static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1595 int content_type, const void *buf, size_t len,
1596 SSL *ssl)
1597{
1598 /* test heartbeat received (write_p is set to 0
1599 for a received record) */
1600 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1601 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1602 const unsigned char *p = buf;
1603 unsigned int payload;
1604
1605 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1606
1607 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1608 if (*p != TLS1_HB_REQUEST)
1609 return;
1610
1611 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1612 goto kill_it;
1613
1614 payload = (p[1] * 256) + p[2];
1615 if (3 + payload + 16 <= len)
1616 return; /* OK no problem */
1617 kill_it:
1618 /* We have a clear heartbleed attack (CVE-2014-0160), the
1619 * advertised payload is larger than the advertised packet
1620 * length, so we have garbage in the buffer between the
1621 * payload and the end of the buffer (p+len). We can't know
1622 * if the SSL stack is patched, and we don't know if we can
1623 * safely wipe out the area between p+3+len and payload.
1624 * So instead, we prevent the response from being sent by
1625 * setting the max_send_fragment to 0 and we report an SSL
1626 * error, which will kill this connection. It will be reported
1627 * above as SSL_ERROR_SSL while an other handshake failure with
1628 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1629 */
1630 ssl->max_send_fragment = 0;
1631 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1632 }
1633}
1634#endif
1635
1636static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1637 int content_type, const void *buf, size_t len,
1638 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001639{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001640 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001641 unsigned char *msg;
1642 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001643 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001644
1645 /* This function is called for "from client" and "to server"
1646 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001647 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001648 */
1649
1650 /* "write_p" is set to 0 is the bytes are received messages,
1651 * otherwise it is set to 1.
1652 */
1653 if (write_p != 0)
1654 return;
1655
1656 /* content_type contains the type of message received or sent
1657 * according with the SSL/TLS protocol spec. This message is
1658 * encoded with one byte. The value 256 (two bytes) is used
1659 * for designing the SSL/TLS record layer. According with the
1660 * rfc6101, the expected message (other than 256) are:
1661 * - change_cipher_spec(20)
1662 * - alert(21)
1663 * - handshake(22)
1664 * - application_data(23)
1665 * - (255)
1666 * We are interessed by the handshake and specially the client
1667 * hello.
1668 */
1669 if (content_type != 22)
1670 return;
1671
1672 /* The message length is at least 4 bytes, containing the
1673 * message type and the message length.
1674 */
1675 if (len < 4)
1676 return;
1677
1678 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001679 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001680 * - hello_request(0)
1681 * - client_hello(1)
1682 * - server_hello(2)
1683 * - certificate(11)
1684 * - server_key_exchange (12)
1685 * - certificate_request(13)
1686 * - server_hello_done(14)
1687 * We are interested by the client hello.
1688 */
1689 msg = (unsigned char *)buf;
1690 if (msg[0] != 1)
1691 return;
1692
1693 /* Next three bytes are the length of the message. The total length
1694 * must be this decoded length + 4. If the length given as argument
1695 * is not the same, we abort the protocol dissector.
1696 */
1697 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1698 if (len < rec_len + 4)
1699 return;
1700 msg += 4;
1701 end = msg + rec_len;
1702 if (end < msg)
1703 return;
1704
1705 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1706 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001707 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1708 */
1709 msg += 1 + 1 + 4 + 28;
1710 if (msg > end)
1711 return;
1712
1713 /* Next, is session id:
1714 * if present, we have to jump by length + 1 for the size information
1715 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001716 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001717 if (msg[0] > 0)
1718 msg += msg[0];
1719 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001720 if (msg > end)
1721 return;
1722
1723 /* Next two bytes are the ciphersuite length. */
1724 if (msg + 2 > end)
1725 return;
1726 rec_len = (msg[0] << 8) + msg[1];
1727 msg += 2;
1728 if (msg + rec_len > end || msg + rec_len < msg)
1729 return;
1730
Willy Tarreaubafbe012017-11-24 17:34:44 +01001731 capture = pool_alloc_dirty(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001732 if (!capture)
1733 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001734 /* Compute the xxh64 of the ciphersuite. */
1735 capture->xxh64 = XXH64(msg, rec_len, 0);
1736
1737 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001738 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1739 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001740 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001741
1742 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001743}
William Lallemand7d42ef52020-07-06 11:41:30 +02001744
1745
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05001746#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001747static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1748 int content_type, const void *buf, size_t len,
1749 SSL *ssl)
1750{
1751 struct ssl_keylog *keylog;
1752
1753 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1754 return;
1755
1756 keylog = pool_alloc(pool_head_ssl_keylog);
1757 if (!keylog)
1758 return;
1759
1760 memset(keylog, 0, sizeof(*keylog));
1761
1762 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1763 pool_free(pool_head_ssl_keylog, keylog);
1764 return;
1765 }
1766}
1767#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001768
Emeric Brun29f037d2014-04-25 19:05:36 +02001769/* Callback is called for ssl protocol analyse */
1770void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1771{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001772 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1773 struct ssl_sock_msg_callback *cbk;
1774
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001775 /* Try to call all callback functions that were registered by using
1776 * ssl_sock_register_msg_callback().
1777 */
1778 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1779 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1780 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001781}
1782
Bernard Spil13c53f82018-02-15 13:34:58 +01001783#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001784static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1785 const unsigned char *in, unsigned int inlen,
1786 void *arg)
1787{
1788 struct server *srv = arg;
1789
1790 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1791 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1792 return SSL_TLSEXT_ERR_OK;
1793 return SSL_TLSEXT_ERR_NOACK;
1794}
1795#endif
1796
1797#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001798/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001799 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001800 */
1801static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1802 unsigned int *len, void *arg)
1803{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001804 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001805
1806 *data = (const unsigned char *)conf->npn_str;
1807 *len = conf->npn_len;
1808 return SSL_TLSEXT_ERR_OK;
1809}
1810#endif
1811
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001812#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001813/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001814 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001815 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001816static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1817 unsigned char *outlen,
1818 const unsigned char *server,
1819 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001820{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001821 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001822
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001823 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1824 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1825 return SSL_TLSEXT_ERR_NOACK;
1826 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001827 return SSL_TLSEXT_ERR_OK;
1828}
1829#endif
1830
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001831#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001832#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001833
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001834/* Configure a DNS SAN extenion on a certificate. */
1835int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1836 int failure = 0;
1837 X509_EXTENSION *san_ext = NULL;
1838 CONF *conf = NULL;
1839 struct buffer *san_name = get_trash_chunk();
1840
1841 conf = NCONF_new(NULL);
1842 if (!conf) {
1843 failure = 1;
1844 goto cleanup;
1845 }
1846
1847 /* Build an extension based on the DNS entry above */
1848 chunk_appendf(san_name, "DNS:%s", servername);
1849 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1850 if (!san_ext) {
1851 failure = 1;
1852 goto cleanup;
1853 }
1854
1855 /* Add the extension */
1856 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1857 failure = 1;
1858 goto cleanup;
1859 }
1860
1861 /* Success */
1862 failure = 0;
1863
1864cleanup:
1865 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1866 if (NULL != conf) NCONF_free(conf);
1867
1868 return failure;
1869}
1870
Christopher Faulet30548802015-06-11 13:39:32 +02001871/* Create a X509 certificate with the specified servername and serial. This
1872 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001873static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001874ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001875{
Shimi Gersner5846c492020-08-23 13:58:12 +03001876 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1877 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001878 SSL_CTX *ssl_ctx = NULL;
1879 X509 *newcrt = NULL;
1880 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001881 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001882 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001883 X509_NAME *name;
1884 const EVP_MD *digest;
1885 X509V3_CTX ctx;
1886 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001887 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001888
Christopher Faulet48a83322017-07-28 16:56:09 +02001889 /* Get the private key of the default certificate and use it */
Ilya Shipitsin842976d2020-12-19 03:12:12 +05001890#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001891 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1892#else
1893 tmp_ssl = SSL_new(bind_conf->default_ctx);
1894 if (tmp_ssl)
1895 pkey = SSL_get_privatekey(tmp_ssl);
1896#endif
1897 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001898 goto mkcert_error;
1899
1900 /* Create the certificate */
1901 if (!(newcrt = X509_new()))
1902 goto mkcert_error;
1903
1904 /* Set version number for the certificate (X509v3) and the serial
1905 * number */
1906 if (X509_set_version(newcrt, 2L) != 1)
1907 goto mkcert_error;
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01001908 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001909
1910 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001911 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1912 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001913 goto mkcert_error;
1914
1915 /* set public key in the certificate */
1916 if (X509_set_pubkey(newcrt, pkey) != 1)
1917 goto mkcert_error;
1918
1919 /* Set issuer name from the CA */
1920 if (!(name = X509_get_subject_name(cacert)))
1921 goto mkcert_error;
1922 if (X509_set_issuer_name(newcrt, name) != 1)
1923 goto mkcert_error;
1924
1925 /* Set the subject name using the same, but the CN */
1926 name = X509_NAME_dup(name);
1927 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1928 (const unsigned char *)servername,
1929 -1, -1, 0) != 1) {
1930 X509_NAME_free(name);
1931 goto mkcert_error;
1932 }
1933 if (X509_set_subject_name(newcrt, name) != 1) {
1934 X509_NAME_free(name);
1935 goto mkcert_error;
1936 }
1937 X509_NAME_free(name);
1938
1939 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001940 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001941 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1942 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1943 X509_EXTENSION *ext;
1944
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001945 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001946 goto mkcert_error;
1947 if (!X509_add_ext(newcrt, ext, -1)) {
1948 X509_EXTENSION_free(ext);
1949 goto mkcert_error;
1950 }
1951 X509_EXTENSION_free(ext);
1952 }
1953
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001954 /* Add SAN extension */
1955 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
1956 goto mkcert_error;
1957 }
1958
Christopher Faulet31af49d2015-06-09 17:29:50 +02001959 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001960
1961 key_type = EVP_PKEY_base_id(capkey);
1962
1963 if (key_type == EVP_PKEY_DSA)
1964 digest = EVP_sha1();
1965 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001966 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001967 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001968 digest = EVP_sha256();
1969 else {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02001970#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000000fL) && !defined(OPENSSL_IS_BORINGSSL)
Christopher Faulet7969a332015-10-09 11:15:03 +02001971 int nid;
1972
1973 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1974 goto mkcert_error;
1975 if (!(digest = EVP_get_digestbynid(nid)))
1976 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02001977#else
1978 goto mkcert_error;
1979#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02001980 }
1981
Christopher Faulet31af49d2015-06-09 17:29:50 +02001982 if (!(X509_sign(newcrt, capkey, digest)))
1983 goto mkcert_error;
1984
1985 /* Create and set the new SSL_CTX */
1986 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
1987 goto mkcert_error;
1988 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1989 goto mkcert_error;
1990 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
1991 goto mkcert_error;
1992 if (!SSL_CTX_check_private_key(ssl_ctx))
1993 goto mkcert_error;
1994
Shimi Gersner5846c492020-08-23 13:58:12 +03001995 /* Build chaining the CA cert and the rest of the chain, keep these order */
1996#if defined(SSL_CTX_add1_chain_cert)
1997 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
1998 goto mkcert_error;
1999 }
2000
2001 if (bind_conf->ca_sign_ckch->chain) {
2002 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2003 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2004 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2005 goto mkcert_error;
2006 }
2007 }
2008 }
2009#endif
2010
Christopher Faulet31af49d2015-06-09 17:29:50 +02002011 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002012
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002013#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002014 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002015#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002016#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2017 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002018 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002019 EC_KEY *ecc;
2020 int nid;
2021
2022 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2023 goto end;
2024 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2025 goto end;
2026 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2027 EC_KEY_free(ecc);
2028 }
2029#endif
2030 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002031 return ssl_ctx;
2032
2033 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002034 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002035 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002036 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2037 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002038 return NULL;
2039}
2040
Christopher Faulet7969a332015-10-09 11:15:03 +02002041SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002042ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02002043{
Willy Tarreau07d94e42018-09-20 10:57:52 +02002044 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01002045 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002046
Olivier Houchard66ab4982019-02-26 18:37:15 +01002047 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02002048}
2049
Christopher Faulet30548802015-06-11 13:39:32 +02002050/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002051 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002052SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002053ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002054{
2055 struct lru64 *lru = NULL;
2056
2057 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002058 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002059 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002060 if (lru && lru->domain) {
2061 if (ssl)
2062 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002063 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002064 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002065 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002066 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002067 }
2068 return NULL;
2069}
2070
Emeric Brun821bb9b2017-06-15 16:37:39 +02002071/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2072 * function is not thread-safe, it should only be used to check if a certificate
2073 * exists in the lru cache (with no warranty it will not be removed by another
2074 * thread). It is kept for backward compatibility. */
2075SSL_CTX *
2076ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2077{
2078 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2079}
2080
Christopher Fauletd2cab922015-07-28 16:03:47 +02002081/* Set a certificate int the LRU cache used to store generated
2082 * certificate. Return 0 on success, otherwise -1 */
2083int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002084ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002085{
2086 struct lru64 *lru = NULL;
2087
2088 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002089 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002090 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002091 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002092 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002093 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002094 }
Christopher Faulet30548802015-06-11 13:39:32 +02002095 if (lru->domain && lru->data)
2096 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002097 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002098 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002099 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002100 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002101 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002102}
2103
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002104/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002105unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002106ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002107{
2108 return XXH32(data, len, ssl_ctx_lru_seed);
2109}
2110
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002111/* Generate a cert and immediately assign it to the SSL session so that the cert's
2112 * refcount is maintained regardless of the cert's presence in the LRU cache.
2113 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002114static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002115ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002116{
Shimi Gersner5846c492020-08-23 13:58:12 +03002117 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002118 SSL_CTX *ssl_ctx = NULL;
2119 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002120 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002121
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002122 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002123 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002124 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002125 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002126 if (lru && lru->domain)
2127 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002128 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002129 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002130 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002131 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002132 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002133 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002134 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002135 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002136 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002137 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002138 SSL_set_SSL_CTX(ssl, ssl_ctx);
2139 /* No LRU cache, this CTX will be released as soon as the session dies */
2140 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002141 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002142 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002143 return 0;
2144}
2145static int
2146ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2147{
2148 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002149 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002150
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002151 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002152 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002153 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002154 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002155 }
2156 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002157}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002158#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002159
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002160#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002161
2162static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002163{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002164#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002165 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002166 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2167#endif
2168}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002169static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2170 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002171 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2172}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002173static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002174#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002175 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002176 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2177#endif
2178}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002179static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002180#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002181 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002182 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2183#endif
2184}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002185/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002186static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2187/* Unusable in this context. */
2188static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2189static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2190static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2191static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2192static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002193#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002194
2195static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2196 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002197 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2198}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002199static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2200 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2201 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2202}
2203static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2204 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002205 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2206}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002207static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2208 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2209 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2210}
2211static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2212 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002213 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2214}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002215static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2216 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2217 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2218}
2219static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2220 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002221 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2222}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002223static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2224 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2225 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2226}
2227static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002228#if SSL_OP_NO_TLSv1_3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002229 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002230 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2231#endif
2232}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002233static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
2234#if SSL_OP_NO_TLSv1_3
2235 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2236 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002237#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002238}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002239#endif
2240static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2241static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002242
William Lallemand7fd8b452020-05-07 15:20:43 +02002243struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002244 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2245 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2246 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2247 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2248 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2249 {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 +02002250};
2251
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002252static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2253{
2254 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2255 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2256 SSL_set_SSL_CTX(ssl, ctx);
2257}
2258
Willy Tarreau5db847a2019-05-09 14:13:35 +02002259#if ((HA_OPENSSL_VERSION_NUMBER >= 0x10101000L) || defined(OPENSSL_IS_BORINGSSL))
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002260
2261static int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
2262{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002263 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002264 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002265
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002266 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2267 return SSL_TLSEXT_ERR_OK;
2268 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002269}
2270
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002271#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002272static int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
2273{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002274 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002275#else
2276static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
2277{
2278#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002279 struct connection *conn;
2280 struct bind_conf *s;
2281 const uint8_t *extension_data;
2282 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002283 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002284
2285 char *wildp = NULL;
2286 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002287 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002288 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002289 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002290 int i;
2291
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002292 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002293 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002294
Olivier Houchard9679ac92017-10-27 14:58:08 +02002295 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002296 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002297#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002298 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2299 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002300#else
2301 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2302#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002303 /*
2304 * The server_name extension was given too much extensibility when it
2305 * was written, so parsing the normal case is a bit complex.
2306 */
2307 size_t len;
2308 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002309 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002310 /* Extract the length of the supplied list of names. */
2311 len = (*extension_data++) << 8;
2312 len |= *extension_data++;
2313 if (len + 2 != extension_len)
2314 goto abort;
2315 /*
2316 * The list in practice only has a single element, so we only consider
2317 * the first one.
2318 */
2319 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2320 goto abort;
2321 extension_len = len - 1;
2322 /* Now we can finally pull out the byte array with the actual hostname. */
2323 if (extension_len <= 2)
2324 goto abort;
2325 len = (*extension_data++) << 8;
2326 len |= *extension_data++;
2327 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2328 || memchr(extension_data, 0, len) != NULL)
2329 goto abort;
2330 servername = extension_data;
2331 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002332 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002333#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2334 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002335 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002336 }
2337#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002338 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002339 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002340 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002341 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002342 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002343 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002344 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002345 goto abort;
2346 }
2347
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002348 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002349#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002350 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002351#else
2352 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2353#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002354 uint8_t sign;
2355 size_t len;
2356 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002357 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002358 len = (*extension_data++) << 8;
2359 len |= *extension_data++;
2360 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002361 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002362 if (len % 2 != 0)
2363 goto abort;
2364 for (; len > 0; len -= 2) {
2365 extension_data++; /* hash */
2366 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002367 switch (sign) {
2368 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002369 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002370 break;
2371 case TLSEXT_signature_ecdsa:
2372 has_ecdsa_sig = 1;
2373 break;
2374 default:
2375 continue;
2376 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002377 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002378 break;
2379 }
2380 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002381 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002382 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002383 }
2384 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002385 const SSL_CIPHER *cipher;
2386 size_t len;
2387 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002388 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002389#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002390 len = ctx->cipher_suites_len;
2391 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002392#else
2393 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2394#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002395 if (len % 2 != 0)
2396 goto abort;
2397 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002398#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002399 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002400 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002401#else
2402 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2403#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002404 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002405 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002406 break;
2407 }
2408 }
2409 }
2410
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002411 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002412 trash.area[i] = tolower(servername[i]);
2413 if (!wildp && (trash.area[i] == '.'))
2414 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002415 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002416 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002417
William Lallemand150bfa82019-09-19 17:12:49 +02002418 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002419
William Lallemand94bd3192020-08-14 14:43:35 +02002420 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2421 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002422 for (i = 0; i < 2; i++) {
2423 if (i == 0) /* lookup in full qualified names */
2424 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002425 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002426 node = ebst_lookup(&s->sni_w_ctx, wildp);
2427 else
2428 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002429
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002430 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002431
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002432 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002433 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002434 struct sni_ctx *sni, *sni_tmp;
2435 int skip = 0;
2436
2437 if (i == 1 && wildp) { /* wildcard */
2438 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2439 sni = container_of(n, struct sni_ctx, name);
2440 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
2441 if (sni_tmp->neg && (!strcmp((const char *)sni_tmp->name.key, trash.area))) {
2442 skip = 1;
2443 break;
2444 }
2445 }
2446 if (skip)
2447 continue;
2448 }
2449
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002450 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002451 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002452 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002453 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002454 break;
2455 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002456 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002457 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002458 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002459 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002460 if (!node_anonymous)
2461 node_anonymous = n;
2462 break;
2463 }
2464 }
2465 }
William Lallemand94bd3192020-08-14 14:43:35 +02002466 }
2467 /* Once the certificates are found, select them depending on what is
2468 * supported in the client and by key_signature priority order: EDSA >
2469 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002470 if (has_ecdsa_sig && node_ecdsa)
2471 node = node_ecdsa;
2472 else if (has_rsa_sig && node_rsa)
2473 node = node_rsa;
2474 else if (node_anonymous)
2475 node = node_anonymous;
2476 else if (node_ecdsa)
2477 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2478 else
2479 node = node_rsa; /* no rsa signature case (far far away) */
2480
William Lallemand94bd3192020-08-14 14:43:35 +02002481 if (node) {
2482 /* switch ctx */
2483 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2484 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2485 if (conf) {
2486 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2487 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2488 if (conf->early_data)
2489 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002490 }
William Lallemand94bd3192020-08-14 14:43:35 +02002491 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2492 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002493 }
William Lallemand150bfa82019-09-19 17:12:49 +02002494
William Lallemand02010472019-10-18 11:02:19 +02002495 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002496#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002497 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002498 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002499 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002500 }
2501#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002502 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002503 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002504 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002505 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002506 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002507 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02002508allow_early:
2509#ifdef OPENSSL_IS_BORINGSSL
2510 if (allow_early)
2511 SSL_set_early_data_enabled(ssl, 1);
2512#else
2513 if (!allow_early)
2514 SSL_set_max_early_data(ssl, 0);
2515#endif
2516 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002517 abort:
2518 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2519 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002520#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002521 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002522#else
2523 *al = SSL_AD_UNRECOGNIZED_NAME;
2524 return 0;
2525#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002526}
2527
2528#else /* OPENSSL_IS_BORINGSSL */
2529
Emeric Brunfc0421f2012-09-07 17:30:07 +02002530/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2531 * warning when no match is found, which implies the default (first) cert
2532 * will keep being used.
2533 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002534static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002535{
2536 const char *servername;
2537 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002538 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002539 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002540 int i;
2541 (void)al; /* shut gcc stupid warning */
2542
2543 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002544 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002545#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002546 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2547 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002548#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002549 if (s->strict_sni)
2550 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002551 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002552 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002553 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002554 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002555 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002556
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002557 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002558 if (!servername[i])
2559 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002560 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002561 if (!wildp && (trash.area[i] == '.'))
2562 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002563 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002564 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002565
William Lallemand150bfa82019-09-19 17:12:49 +02002566 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002567 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002568 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002569 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2570 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002571 if (!container_of(n, struct sni_ctx, name)->neg) {
2572 node = n;
2573 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002574 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002575 }
2576 if (!node && wildp) {
2577 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002578 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2579 /* lookup a not neg filter */
2580 if (!container_of(n, struct sni_ctx, name)->neg) {
2581 node = n;
2582 break;
2583 }
2584 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002585 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002586 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002587#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002588 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2589 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002590 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002591 return SSL_TLSEXT_ERR_OK;
2592 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002593#endif
William Lallemand21724f02019-11-04 17:56:13 +01002594 if (s->strict_sni) {
2595 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002596 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002597 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002598 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002599 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002600 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002601 }
2602
2603 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002604 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002605 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002606 return SSL_TLSEXT_ERR_OK;
2607}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002608#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002609#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2610
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002611#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002612
2613static DH * ssl_get_dh_1024(void)
2614{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002615 static unsigned char dh1024_p[]={
2616 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2617 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2618 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2619 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2620 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2621 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2622 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2623 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2624 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2625 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2626 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2627 };
2628 static unsigned char dh1024_g[]={
2629 0x02,
2630 };
2631
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002632 BIGNUM *p;
2633 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002634 DH *dh = DH_new();
2635 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002636 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2637 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002638
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002639 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002640 DH_free(dh);
2641 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002642 } else {
2643 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002644 }
2645 }
2646 return dh;
2647}
2648
2649static DH *ssl_get_dh_2048(void)
2650{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002651 static unsigned char dh2048_p[]={
2652 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2653 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2654 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2655 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2656 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2657 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2658 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2659 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2660 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2661 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2662 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2663 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2664 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2665 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2666 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2667 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2668 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2669 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2670 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2671 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2672 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2673 0xB7,0x1F,0x77,0xF3,
2674 };
2675 static unsigned char dh2048_g[]={
2676 0x02,
2677 };
2678
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002679 BIGNUM *p;
2680 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002681 DH *dh = DH_new();
2682 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002683 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2684 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002685
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002686 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002687 DH_free(dh);
2688 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002689 } else {
2690 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002691 }
2692 }
2693 return dh;
2694}
2695
2696static DH *ssl_get_dh_4096(void)
2697{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002698 static unsigned char dh4096_p[]={
2699 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2700 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2701 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2702 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2703 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2704 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2705 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2706 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2707 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2708 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2709 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2710 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2711 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2712 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2713 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2714 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2715 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2716 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2717 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2718 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2719 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2720 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2721 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2722 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2723 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2724 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2725 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2726 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2727 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2728 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2729 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2730 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2731 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2732 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2733 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2734 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2735 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2736 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2737 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2738 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2739 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2740 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2741 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002742 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002743 static unsigned char dh4096_g[]={
2744 0x02,
2745 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002746
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002747 BIGNUM *p;
2748 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002749 DH *dh = DH_new();
2750 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002751 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2752 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002753
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002754 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002755 DH_free(dh);
2756 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002757 } else {
2758 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002759 }
2760 }
2761 return dh;
2762}
2763
2764/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002765 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002766static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2767{
2768 DH *dh = NULL;
2769 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002770 int type;
2771
2772 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002773
2774 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2775 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2776 */
2777 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2778 keylen = EVP_PKEY_bits(pkey);
2779 }
2780
Willy Tarreauef934602016-12-22 23:12:01 +01002781 if (keylen > global_ssl.default_dh_param) {
2782 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002783 }
2784
Remi Gacogned3a341a2015-05-29 16:26:17 +02002785 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002786 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002787 }
2788 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002789 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002790 }
2791 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002792 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002793 }
2794
2795 return dh;
2796}
2797
Remi Gacogne47783ef2015-05-29 15:53:22 +02002798static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002799{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002800 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002801 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002802
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002803 if (in == NULL)
2804 goto end;
2805
Remi Gacogne47783ef2015-05-29 15:53:22 +02002806 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002807 goto end;
2808
Remi Gacogne47783ef2015-05-29 15:53:22 +02002809 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2810
2811end:
2812 if (in)
2813 BIO_free(in);
2814
Emeric Brune1b4ed42018-08-16 15:14:12 +02002815 ERR_clear_error();
2816
Remi Gacogne47783ef2015-05-29 15:53:22 +02002817 return dh;
2818}
2819
2820int ssl_sock_load_global_dh_param_from_file(const char *filename)
2821{
2822 global_dh = ssl_sock_get_dh_from_file(filename);
2823
2824 if (global_dh) {
2825 return 0;
2826 }
2827
2828 return -1;
2829}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002830#endif
2831
William Lallemand9117de92019-10-04 00:29:42 +02002832/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002833static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002834 struct bind_conf *s, struct ssl_bind_conf *conf,
2835 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002836{
2837 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002838 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002839
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002840 if (*name == '!') {
2841 neg = 1;
2842 name++;
2843 }
2844 if (*name == '*') {
2845 wild = 1;
2846 name++;
2847 }
2848 /* !* filter is a nop */
2849 if (neg && wild)
2850 return order;
2851 if (*name) {
2852 int j, len;
2853 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002854 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02002855 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002856 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002857 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002858 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002859
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002860 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002861 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002862 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002863 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002864 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002865 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002866 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002867 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002868 sc->order = order++;
2869 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002870 sc->wild = wild;
2871 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002872 sc->ckch_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02002873 LIST_ADDQ(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002874 }
2875 return order;
2876}
2877
William Lallemand6af03992019-07-23 15:00:54 +02002878/*
William Lallemand1d29c742019-10-04 00:53:29 +02002879 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2880 * This function can't return an error.
2881 *
2882 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2883 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002884void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002885{
2886
2887 struct sni_ctx *sc0, *sc0b, *sc1;
2888 struct ebmb_node *node;
2889
2890 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2891
2892 /* ignore if sc0 was already inserted in a tree */
2893 if (sc0->name.node.leaf_p)
2894 continue;
2895
2896 /* Check for duplicates. */
2897 if (sc0->wild)
2898 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2899 else
2900 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2901
2902 for (; node; node = ebmb_next_dup(node)) {
2903 sc1 = ebmb_entry(node, struct sni_ctx, name);
2904 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2905 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2906 /* it's a duplicate, we should remove and free it */
2907 LIST_DEL(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002908 SSL_CTX_free(sc0->ctx);
William Lallemand1d29c742019-10-04 00:53:29 +02002909 free(sc0);
2910 sc0 = NULL;
William Lallemande15029b2019-10-14 10:46:58 +02002911 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002912 }
2913 }
2914
2915 /* if duplicate, ignore the insertion */
2916 if (!sc0)
2917 continue;
2918
2919 if (sc0->wild)
2920 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
2921 else
2922 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton358a8222021-03-17 14:56:54 +01002923 }
William Lallemand21724f02019-11-04 17:56:13 +01002924
Remi Tricot-Le Breton358a8222021-03-17 14:56:54 +01002925 /* replace the default_ctx if required with the instance's ctx. */
2926 if (ckch_inst->is_default) {
2927 SSL_CTX_free(bind_conf->default_ctx);
2928 SSL_CTX_up_ref(ckch_inst->ctx);
2929 bind_conf->default_ctx = ckch_inst->ctx;
William Lallemand1d29c742019-10-04 00:53:29 +02002930 }
2931}
2932
2933/*
William Lallemande3af8fb2019-10-08 11:36:53 +02002934 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02002935 */
William Lallemande3af8fb2019-10-08 11:36:53 +02002936struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02002937
William Lallemand2954c472020-03-06 21:54:13 +01002938/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02002939struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02002940
Emeric Brun7a883362019-10-17 13:27:40 +02002941/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002942 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02002943 * DH parameter is loaded into the SSL_CTX and if there is no
2944 * DH parameter available in ckchs nor in global, the default
2945 * DH parameters are applied on the SSL_CTX.
2946 * Returns a bitfield containing the flags:
2947 * ERR_FATAL in any fatal error case
2948 * ERR_ALERT if a reason of the error is availabine in err
2949 * ERR_WARN if a warning is available into err
2950 * The value 0 means there is no error nor warning and
2951 * the operation succeed.
2952 */
William Lallemandfa892222019-07-23 16:06:08 +02002953#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02002954static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
2955 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02002956{
Emeric Brun7a883362019-10-17 13:27:40 +02002957 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02002958 DH *dh = NULL;
2959
William Lallemanda8c73742019-07-31 18:31:34 +02002960 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02002961 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02002962 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
2963 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
2964 err && *err ? *err : "", path);
2965#if defined(SSL_CTX_set_dh_auto)
2966 SSL_CTX_set_dh_auto(ctx, 1);
2967 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2968 err && *err ? *err : "");
2969#else
2970 memprintf(err, "%s, DH ciphers won't be available.\n",
2971 err && *err ? *err : "");
2972#endif
2973 ret |= ERR_WARN;
2974 goto end;
2975 }
William Lallemandfa892222019-07-23 16:06:08 +02002976
2977 if (ssl_dh_ptr_index >= 0) {
2978 /* store a pointer to the DH params to avoid complaining about
2979 ssl-default-dh-param not being set for this SSL_CTX */
2980 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
2981 }
2982 }
2983 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02002984 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
2985 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
2986 err && *err ? *err : "", path);
2987#if defined(SSL_CTX_set_dh_auto)
2988 SSL_CTX_set_dh_auto(ctx, 1);
2989 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2990 err && *err ? *err : "");
2991#else
2992 memprintf(err, "%s, DH ciphers won't be available.\n",
2993 err && *err ? *err : "");
2994#endif
2995 ret |= ERR_WARN;
2996 goto end;
2997 }
William Lallemandfa892222019-07-23 16:06:08 +02002998 }
2999 else {
3000 /* Clear openssl global errors stack */
3001 ERR_clear_error();
3002
Willy Tarreau58ee2312020-11-05 19:38:05 +01003003 if (global_ssl.default_dh_param && global_ssl.default_dh_param <= 1024) {
William Lallemandfa892222019-07-23 16:06:08 +02003004 /* we are limited to DH parameter of 1024 bits anyway */
3005 if (local_dh_1024 == NULL)
3006 local_dh_1024 = ssl_get_dh_1024();
3007
Emeric Brun7a883362019-10-17 13:27:40 +02003008 if (local_dh_1024 == NULL) {
3009 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3010 err && *err ? *err : "", path);
3011 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02003012 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02003013 }
William Lallemandfa892222019-07-23 16:06:08 +02003014
Emeric Bruna9363eb2019-10-17 14:53:03 +02003015 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
3016 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3017 err && *err ? *err : "", path);
3018#if defined(SSL_CTX_set_dh_auto)
3019 SSL_CTX_set_dh_auto(ctx, 1);
3020 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3021 err && *err ? *err : "");
3022#else
3023 memprintf(err, "%s, DH ciphers won't be available.\n",
3024 err && *err ? *err : "");
3025#endif
3026 ret |= ERR_WARN;
3027 goto end;
3028 }
William Lallemandfa892222019-07-23 16:06:08 +02003029 }
3030 else {
3031 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
3032 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003033 }
3034
William Lallemandf9568fc2019-10-16 18:27:58 +02003035end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003036 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003037 return ret;
3038}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003039#endif
William Lallemandfa892222019-07-23 16:06:08 +02003040
yanbzhu488a4d22015-12-01 15:16:07 -05003041/* Loads the info in ckch into ctx
Emeric Bruna96b5822019-10-17 13:25:14 +02003042 * Returns a bitfield containing the flags:
3043 * ERR_FATAL in any fatal error case
3044 * ERR_ALERT if the reason of the error is available in err
3045 * ERR_WARN if a warning is available into err
3046 * The value 0 means there is no error nor warning and
3047 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003048 */
3049static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3050{
Emeric Bruna96b5822019-10-17 13:25:14 +02003051 int errcode = 0;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003052 STACK_OF(X509) *find_chain = NULL;
Emeric Bruna96b5822019-10-17 13:25:14 +02003053
yanbzhu488a4d22015-12-01 15:16:07 -05003054 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3055 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3056 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003057 errcode |= ERR_ALERT | ERR_FATAL;
3058 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003059 }
3060
3061 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3062 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3063 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003064 errcode |= ERR_ALERT | ERR_FATAL;
3065 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003066 }
3067
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003068 if (ckch->chain) {
3069 find_chain = ckch->chain;
3070 } else {
3071 /* Find Certificate Chain in global */
3072 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003073 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003074 if (issuer)
3075 find_chain = issuer->chain;
3076 }
William Lallemand85888572020-02-27 14:48:35 +01003077
William Lallemand935d8292020-08-12 20:02:10 +02003078 if (!find_chain) {
3079 /* always put a null chain stack in the SSL_CTX so it does not
3080 * try to build the chain from the verify store */
3081 find_chain = sk_X509_new_null();
3082 }
3083
William Lallemandf187ce62020-06-02 18:27:20 +02003084 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003085#ifdef SSL_CTX_set1_chain
William Lallemand935d8292020-08-12 20:02:10 +02003086 if (!SSL_CTX_set1_chain(ctx, find_chain)) {
3087 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3088 err && *err ? *err : "", path);
3089 errcode |= ERR_ALERT | ERR_FATAL;
3090 goto end;
3091 }
William Lallemandf187ce62020-06-02 18:27:20 +02003092#else
3093 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003094 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02003095 STACK_OF(X509) *chain;
3096 chain = X509_chain_up_ref(find_chain);
3097 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003098 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003099 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3100 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003101 X509_free(ca);
3102 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003103 errcode |= ERR_ALERT | ERR_FATAL;
3104 goto end;
3105 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003106 }
William Lallemandf187ce62020-06-02 18:27:20 +02003107#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003108
William Lallemand9a1d8392020-08-10 17:28:23 +02003109#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003110 /* remove the Root CA from the SSL_CTX if the option is activated */
3111 if (global_ssl.skip_self_issued_ca) {
3112 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3113 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3114 err && *err ? *err : "", path);
3115 errcode |= ERR_ALERT | ERR_FATAL;
3116 goto end;
3117 }
3118 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003119#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003120
William Lallemandfa892222019-07-23 16:06:08 +02003121#ifndef OPENSSL_NO_DH
3122 /* store a NULL pointer to indicate we have not yet loaded
3123 a custom DH param file */
3124 if (ssl_dh_ptr_index >= 0) {
3125 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3126 }
3127
Emeric Brun7a883362019-10-17 13:27:40 +02003128 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3129 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003130 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3131 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003132 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003133 }
3134#endif
3135
Ilya Shipitsine4f38f92021-02-06 18:55:27 +05003136#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003137 if (sctl_ex_index >= 0 && ckch->sctl) {
3138 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3139 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003140 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003141 errcode |= ERR_ALERT | ERR_FATAL;
3142 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003143 }
3144 }
3145#endif
3146
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003147#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003148 /* Load OCSP Info into context */
3149 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003150 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003151 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",
3152 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003153 errcode |= ERR_ALERT | ERR_FATAL;
3154 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003155 }
3156 }
William Lallemand246c0242019-10-11 08:59:13 +02003157#endif
3158
Emeric Bruna96b5822019-10-17 13:25:14 +02003159 end:
3160 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003161}
3162
William Lallemand614ca0d2019-10-07 13:52:11 +02003163/*
3164 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003165 *
3166 * Returns a bitfield containing the flags:
3167 * ERR_FATAL in any fatal error case
3168 * ERR_ALERT if the reason of the error is available in err
3169 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003170 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003171int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003172 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003173{
William Lallemandc9402072019-05-15 15:33:54 +02003174 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003175 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003176 int order = 0;
3177 X509_NAME *xname;
3178 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003179 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003180 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003181#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3182 STACK_OF(GENERAL_NAME) *names;
3183#endif
William Lallemand36b84632019-07-18 19:28:17 +02003184 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003185 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003186 int errcode = 0;
3187
3188 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003189
William Lallemande3af8fb2019-10-08 11:36:53 +02003190 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003191 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003192
William Lallemande3af8fb2019-10-08 11:36:53 +02003193 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003194
William Lallemandc9402072019-05-15 15:33:54 +02003195 ctx = SSL_CTX_new(SSLv23_server_method());
3196 if (!ctx) {
3197 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3198 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003199 errcode |= ERR_ALERT | ERR_FATAL;
3200 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003201 }
3202
Emeric Bruna96b5822019-10-17 13:25:14 +02003203 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3204 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003205 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003206
3207 ckch_inst = ckch_inst_new();
3208 if (!ckch_inst) {
3209 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3210 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003211 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003212 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003213 }
3214
William Lallemand36b84632019-07-18 19:28:17 +02003215 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003216 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003217 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003218 switch(EVP_PKEY_base_id(pkey)) {
3219 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003220 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003221 break;
3222 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003223 kinfo.sig = TLSEXT_signature_ecdsa;
3224 break;
3225 case EVP_PKEY_DSA:
3226 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003227 break;
3228 }
3229 EVP_PKEY_free(pkey);
3230 }
3231
Emeric Brun50bcecc2013-04-22 13:05:23 +02003232 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003233 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003234 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 +02003235 if (order < 0) {
3236 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003237 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003238 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003239 }
3240 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003241 }
3242 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003243#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003244 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003245 if (names) {
3246 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3247 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3248 if (name->type == GEN_DNS) {
3249 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003250 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003251 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003252 if (order < 0) {
3253 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003254 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003255 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003256 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003257 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003258 }
3259 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003260 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003261 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003262#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003263 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003264 i = -1;
3265 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3266 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003267 ASN1_STRING *value;
3268
3269 value = X509_NAME_ENTRY_get_data(entry);
3270 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003271 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003272 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003273 if (order < 0) {
3274 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003275 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003276 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003277 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003278 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003279 }
3280 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003281 /* we must not free the SSL_CTX anymore below, since it's already in
3282 * the tree, so it will be discovered and cleaned in time.
3283 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003284
Emeric Brunfc0421f2012-09-07 17:30:07 +02003285#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003286 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003287 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3288 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003289 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003290 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003291 }
3292#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003293 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003294 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003295 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003296 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003297 SSL_CTX_up_ref(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003298 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003299
Remi Tricot-Le Breton358a8222021-03-17 14:56:54 +01003300 /* Always keep a reference to the newly constructed SSL_CTX in the
3301 * instance. This way if the instance has no SNIs, the SSL_CTX will
3302 * still be linked. */
3303 SSL_CTX_up_ref(ctx);
3304 ckch_inst->ctx = ctx;
3305
William Lallemand9117de92019-10-04 00:29:42 +02003306 /* everything succeed, the ckch instance can be used */
3307 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003308 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003309 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003310
William Lallemand02e19a52020-04-08 16:11:26 +02003311 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3312
Emeric Brun054563d2019-10-17 13:16:58 +02003313 *ckchi = ckch_inst;
3314 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003315
3316error:
3317 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003318 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003319 if (ckch_inst->is_default)
3320 SSL_CTX_free(ctx);
3321
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003322 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003323 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003324 }
William Lallemandd9199372019-10-04 15:37:05 +02003325 SSL_CTX_free(ctx);
3326
Emeric Brun054563d2019-10-17 13:16:58 +02003327 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003328}
3329
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003330/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003331static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3332 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003333 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003334{
Emeric Brun054563d2019-10-17 13:16:58 +02003335 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003336
3337 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003338 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 +02003339
Emeric Brun054563d2019-10-17 13:16:58 +02003340 if (errcode & ERR_CODE)
3341 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003342
William Lallemand24bde432020-03-09 16:48:43 +01003343 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003344
3345 /* succeed, add the instance to the ckch_store's list of instance */
William Lallemand24bde432020-03-09 16:48:43 +01003346 LIST_ADDQ(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003347 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003348}
3349
William Lallemand6be66ec2020-03-06 22:26:32 +01003350
William Lallemand4c68bba2020-03-30 18:45:10 +02003351
3352
3353/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3354 * done once. Zero is returned if the operation fails. No error is returned
3355 * if the random is said as not implemented, because we expect that openssl
3356 * will use another method once needed.
3357 */
3358static int ssl_initialize_random()
3359{
3360 unsigned char random;
3361 static int random_initialized = 0;
3362
3363 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3364 random_initialized = 1;
3365
3366 return random_initialized;
3367}
3368
William Lallemand2954c472020-03-06 21:54:13 +01003369/* Load a crt-list file, this is done in 2 parts:
3370 * - store the content of the file in a crtlist structure with crtlist_entry structures
3371 * - generate the instances by iterating on entries in the crtlist struct
3372 *
3373 * Nothing is locked there, this function is used in the configuration parser.
3374 *
3375 * Returns a set of ERR_* flags possibly with an error in <err>.
3376 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003377int 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 +01003378{
3379 struct crtlist *crtlist = NULL;
3380 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003381 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003382 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003383 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003384 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003385
William Lallemand79d31ec2020-03-25 15:10:49 +01003386 bind_conf_node = malloc(sizeof(*bind_conf_node));
3387 if (!bind_conf_node) {
3388 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3389 cfgerr |= ERR_FATAL | ERR_ALERT;
3390 goto error;
3391 }
3392 bind_conf_node->next = NULL;
3393 bind_conf_node->bind_conf = bind_conf;
3394
William Lallemand41ca9302020-04-08 13:15:18 +02003395 /* strip trailing slashes, including first one */
3396 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3397 *end = 0;
3398
William Lallemand2954c472020-03-06 21:54:13 +01003399 /* look for an existing crtlist or create one */
3400 eb = ebst_lookup(&crtlists_tree, file);
3401 if (eb) {
3402 crtlist = ebmb_entry(eb, struct crtlist, node);
3403 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003404 /* load a crt-list OR a directory */
3405 if (dir)
3406 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3407 else
3408 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3409
William Lallemand2954c472020-03-06 21:54:13 +01003410 if (!(cfgerr & ERR_CODE))
3411 ebst_insert(&crtlists_tree, &crtlist->node);
3412 }
3413
3414 if (cfgerr & ERR_CODE) {
3415 cfgerr |= ERR_FATAL | ERR_ALERT;
3416 goto error;
3417 }
3418
3419 /* generates ckch instance from the crtlist_entry */
3420 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3421 struct ckch_store *store;
3422 struct ckch_inst *ckch_inst = NULL;
3423
3424 store = entry->node.key;
3425 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3426 if (cfgerr & ERR_CODE) {
3427 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3428 goto error;
3429 }
William Lallemand49398312020-03-30 17:01:33 +02003430 LIST_ADDQ(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003431 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003432 }
William Lallemand2954c472020-03-06 21:54:13 +01003433
William Lallemand79d31ec2020-03-25 15:10:49 +01003434 /* add the bind_conf to the list */
3435 bind_conf_node->next = crtlist->bind_conf;
3436 crtlist->bind_conf = bind_conf_node;
3437
William Lallemand2954c472020-03-06 21:54:13 +01003438 return cfgerr;
3439error:
3440 {
William Lallemand49398312020-03-30 17:01:33 +02003441 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003442 struct ckch_inst *inst, *s_inst;
3443
William Lallemand49398312020-03-30 17:01:33 +02003444 lastentry = entry; /* which entry we tried to generate last */
3445 if (lastentry) {
3446 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3447 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3448 break;
3449
3450 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003451
William Lallemand49398312020-03-30 17:01:33 +02003452 /* this was not generated for this bind_conf, skip */
3453 if (inst->bind_conf != bind_conf)
3454 continue;
3455
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003456 /* free the sni_ctx and instance */
3457 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003458 }
William Lallemand2954c472020-03-06 21:54:13 +01003459 }
William Lallemand2954c472020-03-06 21:54:13 +01003460 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003461 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003462 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003463 return cfgerr;
3464}
3465
William Lallemand06b22a82020-03-16 14:45:55 +01003466/* Returns a set of ERR_* flags possibly with an error in <err>. */
3467int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3468{
3469 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003470 int cfgerr = 0;
3471 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003472 struct ckch_inst *ckch_inst = NULL;
William Lallemand7efbaf12020-11-20 15:36:13 +01003473 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003474
3475 if ((ckchs = ckchs_lookup(path))) {
3476 /* we found the ckchs in the tree, we can use it directly */
William Lallemand7efbaf12020-11-20 15:36:13 +01003477 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3478 found++;
3479 } else if (stat(path, &buf) == 0) {
3480 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003481 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003482 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003483 if (!ckchs)
William Lallemand7efbaf12020-11-20 15:36:13 +01003484 cfgerr |= ERR_ALERT | ERR_FATAL;
3485 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003486 } else {
William Lallemand7efbaf12020-11-20 15:36:13 +01003487 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003488 }
3489 } else {
3490 /* stat failed, could be a bundle */
3491 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003492 char fp[MAXPATHLEN+1] = {0};
3493 int n = 0;
3494
3495 /* Load all possible certs and keys in separate ckch_store */
3496 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3497 struct stat buf;
3498 int ret;
3499
3500 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3501 if (ret > sizeof(fp))
3502 continue;
3503
3504 if ((ckchs = ckchs_lookup(fp))) {
3505 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand7efbaf12020-11-20 15:36:13 +01003506 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003507 } else {
3508 if (stat(fp, &buf) == 0) {
William Lallemand7efbaf12020-11-20 15:36:13 +01003509 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003510 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003511 if (!ckchs)
William Lallemand7efbaf12020-11-20 15:36:13 +01003512 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003513 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3514 }
3515 }
3516 }
William Lallemand00b831e2020-12-04 15:45:02 +01003517#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3518 if (found) {
3519 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3520 err && *err ? *err : "", path);
3521 cfgerr |= ERR_ALERT | ERR_FATAL;
3522 }
3523#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003524 }
3525 }
William Lallemand7efbaf12020-11-20 15:36:13 +01003526 if (!found) {
3527 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3528 err && *err ? *err : "", path, strerror(errno));
3529 cfgerr |= ERR_ALERT | ERR_FATAL;
3530 }
William Lallemand06b22a82020-03-16 14:45:55 +01003531
3532 return cfgerr;
3533}
3534
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003535/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003536static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003537ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003538{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003539 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003540 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003541 SSL_OP_ALL | /* all known workarounds for bugs */
3542 SSL_OP_NO_SSLv2 |
3543 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003544 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003545 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003546 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003547 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003548 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003549 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003550 SSL_MODE_ENABLE_PARTIAL_WRITE |
3551 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003552 SSL_MODE_RELEASE_BUFFERS |
3553 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003554 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003555 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003556 int flags = MC_SSL_O_ALL;
3557 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003558 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003559
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003560 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003561 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003562
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003563 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003564 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3565 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3566 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003567 else
3568 flags = conf_ssl_methods->flags;
3569
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003570 min = conf_ssl_methods->min;
3571 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003572
3573 /* default minimum is TLSV12, */
3574 if (!min) {
3575 if (!max || (max >= default_min_ver)) {
3576 min = default_min_ver;
3577 } else {
3578 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). "
3579 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3580 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3581 min = max;
3582 }
3583 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003584 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003585 if (min)
3586 flags |= (methodVersions[min].flag - 1);
3587 if (max)
3588 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003589 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003590 min = max = CONF_TLSV_NONE;
3591 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003592 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003593 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003594 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003595 if (min) {
3596 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003597 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3598 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3599 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3600 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003601 hole = 0;
3602 }
3603 max = i;
3604 }
3605 else {
3606 min = max = i;
3607 }
3608 }
3609 else {
3610 if (min)
3611 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003612 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003613 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003614 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3615 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003616 cfgerr += 1;
3617 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003618 /* save real min/max in bind_conf */
3619 conf_ssl_methods->min = min;
3620 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003621
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003622#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003623 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003624 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003625 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003626 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003627 else
William Lallemandd0712f32020-06-11 17:34:00 +02003628 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
3629 /* clear every version flags in case SSL_CTX_new()
3630 * returns an SSL_CTX with disabled versions */
3631 SSL_CTX_clear_options(ctx, methodVersions[i].option);
3632
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003633 if (flags & methodVersions[i].flag)
3634 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02003635
3636 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003637#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003638 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003639 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3640 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003641#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003642
3643 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3644 options |= SSL_OP_NO_TICKET;
3645 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3646 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003647
3648#ifdef SSL_OP_NO_RENEGOTIATION
3649 options |= SSL_OP_NO_RENEGOTIATION;
3650#endif
3651
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003652 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003653
Willy Tarreau5db847a2019-05-09 14:13:35 +02003654#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003655 if (global_ssl.async)
3656 mode |= SSL_MODE_ASYNC;
3657#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003658 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003659 if (global_ssl.life_time)
3660 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003661
3662#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3663#ifdef OPENSSL_IS_BORINGSSL
3664 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3665 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003666#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003667 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003668 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003669 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3670 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003671#else
3672 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003673#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003674 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003675#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003676 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003677}
3678
William Lallemand4f45bb92017-10-30 20:08:51 +01003679
3680static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3681{
3682 if (first == block) {
3683 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3684 if (first->len > 0)
3685 sh_ssl_sess_tree_delete(sh_ssl_sess);
3686 }
3687}
3688
3689/* return first block from sh_ssl_sess */
3690static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3691{
3692 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3693
3694}
3695
3696/* store a session into the cache
3697 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3698 * data: asn1 encoded session
3699 * data_len: asn1 encoded session length
3700 * Returns 1 id session was stored (else 0)
3701 */
3702static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3703{
3704 struct shared_block *first;
3705 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3706
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003707 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003708 if (!first) {
3709 /* Could not retrieve enough free blocks to store that session */
3710 return 0;
3711 }
3712
3713 /* STORE the key in the first elem */
3714 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3715 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3716 first->len = sizeof(struct sh_ssl_sess_hdr);
3717
3718 /* it returns the already existing node
3719 or current node if none, never returns null */
3720 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3721 if (oldsh_ssl_sess != sh_ssl_sess) {
3722 /* NOTE: Row couldn't be in use because we lock read & write function */
3723 /* release the reserved row */
3724 shctx_row_dec_hot(ssl_shctx, first);
3725 /* replace the previous session already in the tree */
3726 sh_ssl_sess = oldsh_ssl_sess;
3727 /* ignore the previous session data, only use the header */
3728 first = sh_ssl_sess_first_block(sh_ssl_sess);
3729 shctx_row_inc_hot(ssl_shctx, first);
3730 first->len = sizeof(struct sh_ssl_sess_hdr);
3731 }
3732
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003733 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01003734 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003735 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01003736 }
3737
3738 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003739
3740 return 1;
3741}
William Lallemanded0b5ad2017-10-30 19:36:36 +01003742
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003743/* SSL callback used when a new session is created while connecting to a server */
3744static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
3745{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02003746 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003747 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003748
Willy Tarreau07d94e42018-09-20 10:57:52 +02003749 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003750
Olivier Houcharde6060c52017-11-16 17:42:52 +01003751 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
3752 int len;
3753 unsigned char *ptr;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003754
Olivier Houcharde6060c52017-11-16 17:42:52 +01003755 len = i2d_SSL_SESSION(sess, NULL);
3756 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
3757 ptr = s->ssl_ctx.reused_sess[tid].ptr;
3758 } else {
3759 free(s->ssl_ctx.reused_sess[tid].ptr);
3760 ptr = s->ssl_ctx.reused_sess[tid].ptr = malloc(len);
3761 s->ssl_ctx.reused_sess[tid].allocated_size = len;
3762 }
3763 if (s->ssl_ctx.reused_sess[tid].ptr) {
3764 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
3765 &ptr);
3766 }
3767 } else {
3768 free(s->ssl_ctx.reused_sess[tid].ptr);
3769 s->ssl_ctx.reused_sess[tid].ptr = NULL;
3770 }
3771
3772 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003773}
3774
Olivier Houcharde6060c52017-11-16 17:42:52 +01003775
William Lallemanded0b5ad2017-10-30 19:36:36 +01003776/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01003777int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003778{
3779 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
3780 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
3781 unsigned char *p;
3782 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02003783 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003784 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003785
3786 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003787 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02003788 * note: SSL_SESSION_set1_id is using
3789 * a memcpy so we need to use a different pointer
3790 * than sid_data or sid_ctx_data to avoid valgrind
3791 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01003792 */
3793
3794 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02003795
3796 /* copy value in an other buffer */
3797 memcpy(encid, sid_data, sid_length);
3798
3799 /* pad with 0 */
3800 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
3801 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
3802
3803 /* force length to zero to avoid ASN1 encoding */
3804 SSL_SESSION_set1_id(sess, encid, 0);
3805
3806 /* force length to zero to avoid ASN1 encoding */
3807 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003808
3809 /* check if buffer is large enough for the ASN1 encoded session */
3810 data_len = i2d_SSL_SESSION(sess, NULL);
3811 if (data_len > SHSESS_MAX_DATA_LEN)
3812 goto err;
3813
3814 p = encsess;
3815
3816 /* process ASN1 session encoding before the lock */
3817 i2d_SSL_SESSION(sess, &p);
3818
William Lallemanded0b5ad2017-10-30 19:36:36 +01003819
William Lallemanda3c77cf2017-10-30 23:44:40 +01003820 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003821 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003822 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01003823 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003824err:
3825 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02003826 SSL_SESSION_set1_id(sess, encid, sid_length);
3827 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003828
3829 return 0; /* do not increment session reference count */
3830}
3831
3832/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003833SSL_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 +01003834{
William Lallemand4f45bb92017-10-30 20:08:51 +01003835 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003836 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
3837 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01003838 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01003839 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003840
3841 global.shctx_lookups++;
3842
3843 /* allow the session to be freed automatically by openssl */
3844 *do_copy = 0;
3845
3846 /* tree key is zeros padded sessionid */
3847 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3848 memcpy(tmpkey, key, key_len);
3849 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
3850 key = tmpkey;
3851 }
3852
3853 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003854 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003855
3856 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003857 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
3858 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003859 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003860 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003861 global.shctx_misses++;
3862 return NULL;
3863 }
3864
William Lallemand4f45bb92017-10-30 20:08:51 +01003865 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
3866 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003867
William Lallemand4f45bb92017-10-30 20:08:51 +01003868 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 +01003869
William Lallemanda3c77cf2017-10-30 23:44:40 +01003870 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003871
3872 /* decode ASN1 session */
3873 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01003874 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003875 /* Reset session id and session id contenxt */
3876 if (sess) {
3877 SSL_SESSION_set1_id(sess, key, key_len);
3878 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
3879 }
3880
3881 return sess;
3882}
3883
William Lallemand4f45bb92017-10-30 20:08:51 +01003884
William Lallemanded0b5ad2017-10-30 19:36:36 +01003885/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003886void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003887{
William Lallemand4f45bb92017-10-30 20:08:51 +01003888 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003889 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
3890 unsigned int sid_length;
3891 const unsigned char *sid_data;
3892 (void)ctx;
3893
3894 sid_data = SSL_SESSION_get_id(sess, &sid_length);
3895 /* tree key is zeros padded sessionid */
3896 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3897 memcpy(tmpkey, sid_data, sid_length);
3898 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
3899 sid_data = tmpkey;
3900 }
3901
William Lallemanda3c77cf2017-10-30 23:44:40 +01003902 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003903
3904 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003905 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
3906 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003907 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003908 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003909 }
3910
3911 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003912 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003913}
3914
3915/* Set session cache mode to server and disable openssl internal cache.
3916 * Set shared cache callbacks on an ssl context.
3917 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01003918void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003919{
3920 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
3921
3922 if (!ssl_shctx) {
3923 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
3924 return;
3925 }
3926
3927 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
3928 SSL_SESS_CACHE_NO_INTERNAL |
3929 SSL_SESS_CACHE_NO_AUTO_CLEAR);
3930
3931 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01003932 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
3933 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
3934 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003935}
William Lallemand7d42ef52020-07-06 11:41:30 +02003936
3937/*
3938 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
3939 *
3940 * The format is:
3941 * * <Label> <space> <ClientRandom> <space> <Secret>
3942 * We only need to copy the secret as there is a sample fetch for the ClientRandom
3943 */
3944
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05003945#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02003946void SSL_CTX_keylog(const SSL *ssl, const char *line)
3947{
3948 struct ssl_keylog *keylog;
3949 char *lastarg = NULL;
3950 char *dst = NULL;
3951
3952 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
3953 if (!keylog)
3954 return;
3955
3956 lastarg = strrchr(line, ' ');
3957 if (lastarg == NULL || ++lastarg == NULL)
3958 return;
3959
3960 dst = pool_alloc(pool_head_ssl_keylog_str);
3961 if (!dst)
3962 return;
3963
3964 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
3965 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
3966
3967 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
3968 if (keylog->client_random)
3969 goto error;
3970 keylog->client_random = dst;
3971
3972 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
3973 if (keylog->client_early_traffic_secret)
3974 goto error;
3975 keylog->client_early_traffic_secret = dst;
3976
3977 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
3978 if(keylog->client_handshake_traffic_secret)
3979 goto error;
3980 keylog->client_handshake_traffic_secret = dst;
3981
3982 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
3983 if (keylog->server_handshake_traffic_secret)
3984 goto error;
3985 keylog->server_handshake_traffic_secret = dst;
3986
3987 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
3988 if (keylog->client_traffic_secret_0)
3989 goto error;
3990 keylog->client_traffic_secret_0 = dst;
3991
3992 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
3993 if (keylog->server_traffic_secret_0)
3994 goto error;
3995 keylog->server_traffic_secret_0 = dst;
3996
3997 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
3998 if (keylog->early_exporter_secret)
3999 goto error;
4000 keylog->early_exporter_secret = dst;
4001
4002 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4003 if (keylog->exporter_secret)
4004 goto error;
4005 keylog->exporter_secret = dst;
4006 } else {
4007 goto error;
4008 }
4009
4010 return;
4011
4012error:
4013 pool_free(pool_head_ssl_keylog_str, dst);
4014
4015 return;
4016}
4017#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004018
William Lallemand8b453912019-11-21 15:48:10 +01004019/*
4020 * This function applies the SSL configuration on a SSL_CTX
4021 * It returns an error code and fills the <err> buffer
4022 */
4023int 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 +01004024{
4025 struct proxy *curproxy = bind_conf->frontend;
4026 int cfgerr = 0;
4027 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004028 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004029 const char *conf_ciphers;
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004030#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004031 const char *conf_ciphersuites;
4032#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004033 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004034
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004035 if (ssl_conf) {
4036 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4037 int i, min, max;
4038 int flags = MC_SSL_O_ALL;
4039
4040 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004041 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4042 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004043 if (min)
4044 flags |= (methodVersions[min].flag - 1);
4045 if (max)
4046 flags |= ~((methodVersions[max].flag << 1) - 1);
4047 min = max = CONF_TLSV_NONE;
4048 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4049 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4050 if (min)
4051 max = i;
4052 else
4053 min = max = i;
4054 }
4055 /* save real min/max */
4056 conf_ssl_methods->min = min;
4057 conf_ssl_methods->max = max;
4058 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004059 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4060 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004061 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004062 }
4063 }
4064
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004065 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004066 case SSL_SOCK_VERIFY_NONE:
4067 verify = SSL_VERIFY_NONE;
4068 break;
4069 case SSL_SOCK_VERIFY_OPTIONAL:
4070 verify = SSL_VERIFY_PEER;
4071 break;
4072 case SSL_SOCK_VERIFY_REQUIRED:
4073 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4074 break;
4075 }
4076 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4077 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004078 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 +01004079 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 +01004080 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 +01004081 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004082 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004083 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004084 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004085 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004086 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004087 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004088 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4089 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4090 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4091 cfgerr |= ERR_ALERT | ERR_FATAL;
4092 }
4093 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004094 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004095 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 +02004096 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004097 }
Emeric Brun850efd52014-01-29 12:24:34 +01004098 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004099 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4100 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004101 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004102 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004103#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004104 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004105 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4106
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004107 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004108 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4109 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004110 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004111 }
Emeric Brun561e5742012-10-02 15:20:55 +02004112 else {
4113 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4114 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004115 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004116#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004117 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004118 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004119#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004120 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004121 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004122 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4123 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004124 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004125 }
4126 }
4127#endif
4128
William Lallemand4f45bb92017-10-30 20:08:51 +01004129 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004130 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4131 if (conf_ciphers &&
4132 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004133 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4134 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004135 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004136 }
4137
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004138#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004139 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4140 if (conf_ciphersuites &&
4141 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004142 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4143 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004144 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004145 }
4146#endif
4147
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004148#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004149 /* If tune.ssl.default-dh-param has not been set,
4150 neither has ssl-default-dh-file and no static DH
4151 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004152 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004153 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004154 (ssl_dh_ptr_index == -1 ||
4155 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004156 /* default to dh-param 2048 */
4157 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004158 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004159
Willy Tarreauef934602016-12-22 23:12:01 +01004160 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004161 if (local_dh_1024 == NULL) {
4162 local_dh_1024 = ssl_get_dh_1024();
4163 }
Willy Tarreauef934602016-12-22 23:12:01 +01004164 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004165 if (local_dh_2048 == NULL) {
4166 local_dh_2048 = ssl_get_dh_2048();
4167 }
Willy Tarreauef934602016-12-22 23:12:01 +01004168 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004169 if (local_dh_4096 == NULL) {
4170 local_dh_4096 = ssl_get_dh_4096();
4171 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004172 }
4173 }
4174 }
4175#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004176
Emeric Brunfc0421f2012-09-07 17:30:07 +02004177 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsinbcc25602021-02-08 16:55:06 +05004178#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004179 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004180#endif
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05004181#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004182 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
4183#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004184
Bernard Spil13c53f82018-02-15 13:34:58 +01004185#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004186 ssl_conf_cur = NULL;
4187 if (ssl_conf && ssl_conf->npn_str)
4188 ssl_conf_cur = ssl_conf;
4189 else if (bind_conf->ssl_conf.npn_str)
4190 ssl_conf_cur = &bind_conf->ssl_conf;
4191 if (ssl_conf_cur)
4192 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004193#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004194#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004195 ssl_conf_cur = NULL;
4196 if (ssl_conf && ssl_conf->alpn_str)
4197 ssl_conf_cur = ssl_conf;
4198 else if (bind_conf->ssl_conf.alpn_str)
4199 ssl_conf_cur = &bind_conf->ssl_conf;
4200 if (ssl_conf_cur)
4201 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004202#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004203#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004204 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4205 if (conf_curves) {
4206 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004207 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4208 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004209 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004210 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004211 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004212 }
4213#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004214#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004215 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004216 int i;
4217 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004218#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004219 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004220 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4221 NULL);
4222
4223 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004224 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004225 return cfgerr;
4226 }
4227#else
4228 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4229 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4230 ECDHE_DEFAULT_CURVE);
4231#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004232
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004233 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004234 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004235 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4236 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004237 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004238 }
4239 else {
4240 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4241 EC_KEY_free(ecdh);
4242 }
4243 }
4244#endif
4245
Emeric Brunfc0421f2012-09-07 17:30:07 +02004246 return cfgerr;
4247}
4248
Evan Broderbe554312013-06-27 00:05:25 -07004249static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4250{
4251 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4252 size_t prefixlen, suffixlen;
4253
4254 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004255 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004256 return 1;
4257
Evan Broderbe554312013-06-27 00:05:25 -07004258 /* The rest of this logic is based on RFC 6125, section 6.4.3
4259 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4260
Emeric Bruna848dae2013-10-08 11:27:28 +02004261 pattern_wildcard = NULL;
4262 pattern_left_label_end = pattern;
4263 while (*pattern_left_label_end != '.') {
4264 switch (*pattern_left_label_end) {
4265 case 0:
4266 /* End of label not found */
4267 return 0;
4268 case '*':
4269 /* If there is more than one wildcards */
4270 if (pattern_wildcard)
4271 return 0;
4272 pattern_wildcard = pattern_left_label_end;
4273 break;
4274 }
4275 pattern_left_label_end++;
4276 }
4277
4278 /* If it's not trivial and there is no wildcard, it can't
4279 * match */
4280 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004281 return 0;
4282
4283 /* Make sure all labels match except the leftmost */
4284 hostname_left_label_end = strchr(hostname, '.');
4285 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004286 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004287 return 0;
4288
4289 /* Make sure the leftmost label of the hostname is long enough
4290 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004291 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004292 return 0;
4293
4294 /* Finally compare the string on either side of the
4295 * wildcard */
4296 prefixlen = pattern_wildcard - pattern;
4297 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004298 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4299 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004300 return 0;
4301
4302 return 1;
4303}
4304
4305static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4306{
4307 SSL *ssl;
4308 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004309 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004310 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004311 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004312
4313 int depth;
4314 X509 *cert;
4315 STACK_OF(GENERAL_NAME) *alt_names;
4316 int i;
4317 X509_NAME *cert_subject;
4318 char *str;
4319
4320 if (ok == 0)
4321 return ok;
4322
4323 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004324 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004325 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004326
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004327 /* We're checking if the provided hostnames match the desired one. The
4328 * desired hostname comes from the SNI we presented if any, or if not
4329 * provided then it may have been explicitly stated using a "verifyhost"
4330 * directive. If neither is set, we don't care about the name so the
4331 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004332 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004333 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004334 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004335 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004336 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004337 if (!servername)
4338 return ok;
4339 }
Evan Broderbe554312013-06-27 00:05:25 -07004340
4341 /* We only need to verify the CN on the actual server cert,
4342 * not the indirect CAs */
4343 depth = X509_STORE_CTX_get_error_depth(ctx);
4344 if (depth != 0)
4345 return ok;
4346
4347 /* At this point, the cert is *not* OK unless we can find a
4348 * hostname match */
4349 ok = 0;
4350
4351 cert = X509_STORE_CTX_get_current_cert(ctx);
4352 /* It seems like this might happen if verify peer isn't set */
4353 if (!cert)
4354 return ok;
4355
4356 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4357 if (alt_names) {
4358 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4359 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4360 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004361#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004362 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4363#else
Evan Broderbe554312013-06-27 00:05:25 -07004364 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004365#endif
Evan Broderbe554312013-06-27 00:05:25 -07004366 ok = ssl_sock_srv_hostcheck(str, servername);
4367 OPENSSL_free(str);
4368 }
4369 }
4370 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004371 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004372 }
4373
4374 cert_subject = X509_get_subject_name(cert);
4375 i = -1;
4376 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4377 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004378 ASN1_STRING *value;
4379 value = X509_NAME_ENTRY_get_data(entry);
4380 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004381 ok = ssl_sock_srv_hostcheck(str, servername);
4382 OPENSSL_free(str);
4383 }
4384 }
4385
Willy Tarreau71d058c2017-07-26 20:09:56 +02004386 /* report the mismatch and indicate if SNI was used or not */
4387 if (!ok && !conn->err_code)
4388 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004389 return ok;
4390}
4391
Emeric Brun94324a42012-10-11 14:00:19 +02004392/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004393int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004394{
Willy Tarreau03209342016-12-22 17:08:28 +01004395 struct proxy *curproxy = srv->proxy;
Emeric Brun94324a42012-10-11 14:00:19 +02004396 int cfgerr = 0;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004397 long options =
Emeric Brun94324a42012-10-11 14:00:19 +02004398 SSL_OP_ALL | /* all known workarounds for bugs */
4399 SSL_OP_NO_SSLv2 |
4400 SSL_OP_NO_COMPRESSION;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004401 long mode =
Emeric Brun94324a42012-10-11 14:00:19 +02004402 SSL_MODE_ENABLE_PARTIAL_WRITE |
4403 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004404 SSL_MODE_RELEASE_BUFFERS |
4405 SSL_MODE_SMALL_BUFFERS;
Emeric Brun850efd52014-01-29 12:24:34 +01004406 int verify = SSL_VERIFY_NONE;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004407 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004408 struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004409 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004410 int flags = MC_SSL_O_ALL;
Emeric Brun94324a42012-10-11 14:00:19 +02004411
Thierry Fournier383085f2013-01-24 14:15:43 +01004412 /* Make sure openssl opens /dev/urandom before the chroot */
4413 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004414 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004415 cfgerr++;
4416 }
4417
Willy Tarreaufce03112015-01-15 21:32:40 +01004418 /* Automatic memory computations need to know we use SSL there */
4419 global.ssl_used_backend = 1;
4420
4421 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004422 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004423 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004424 ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4425 curproxy->id, srv->id,
4426 srv->conf.file, srv->conf.line);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004427 cfgerr++;
4428 return cfgerr;
4429 }
4430 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004431 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004432 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004433
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004434 ctx = SSL_CTX_new(SSLv23_client_method());
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004435 if (!ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004436 ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4437 proxy_type_str(curproxy), curproxy->id,
4438 srv->id);
Emeric Brun94324a42012-10-11 14:00:19 +02004439 cfgerr++;
4440 return cfgerr;
4441 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004442
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004443 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004444 ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4445 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4446 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004447 else
4448 flags = conf_ssl_methods->flags;
4449
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004450 /* Real min and max should be determinate with configuration and openssl's capabilities */
4451 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004452 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004453 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004454 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004455
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004456 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004457 min = max = CONF_TLSV_NONE;
4458 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004459 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004460 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004461 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004462 if (min) {
4463 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004464 ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4465 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4466 proxy_type_str(curproxy), curproxy->id, srv->id,
4467 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004468 hole = 0;
4469 }
4470 max = i;
4471 }
4472 else {
4473 min = max = i;
4474 }
4475 }
4476 else {
4477 if (min)
4478 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004479 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004480 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004481 ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4482 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004483 cfgerr += 1;
4484 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004485
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004486#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004487 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004488 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004489 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004490 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004491 else
4492 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4493 if (flags & methodVersions[i].flag)
4494 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004495#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004496 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004497 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4498 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004499#endif
4500
4501 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4502 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004503 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004504
Willy Tarreau5db847a2019-05-09 14:13:35 +02004505#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004506 if (global_ssl.async)
4507 mode |= SSL_MODE_ASYNC;
4508#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004509 SSL_CTX_set_mode(ctx, mode);
4510 srv->ssl_ctx.ctx = ctx;
4511
Emeric Bruna7aa3092012-10-26 12:58:00 +02004512 if (srv->ssl_ctx.client_crt) {
4513 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 +01004514 ha_alert("config : %s '%s', server '%s': unable to load SSL private key from PEM file '%s'.\n",
4515 proxy_type_str(curproxy), curproxy->id,
4516 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004517 cfgerr++;
4518 }
4519 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 +01004520 ha_alert("config : %s '%s', server '%s': unable to load ssl certificate from PEM file '%s'.\n",
4521 proxy_type_str(curproxy), curproxy->id,
4522 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004523 cfgerr++;
4524 }
4525 else if (SSL_CTX_check_private_key(srv->ssl_ctx.ctx) <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004526 ha_alert("config : %s '%s', server '%s': inconsistencies between private key and certificate loaded from PEM file '%s'.\n",
4527 proxy_type_str(curproxy), curproxy->id,
4528 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004529 cfgerr++;
4530 }
4531 }
Emeric Brun94324a42012-10-11 14:00:19 +02004532
Emeric Brun850efd52014-01-29 12:24:34 +01004533 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4534 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004535 switch (srv->ssl_ctx.verify) {
4536 case SSL_SOCK_VERIFY_NONE:
4537 verify = SSL_VERIFY_NONE;
4538 break;
4539 case SSL_SOCK_VERIFY_REQUIRED:
4540 verify = SSL_VERIFY_PEER;
4541 break;
4542 }
Evan Broderbe554312013-06-27 00:05:25 -07004543 SSL_CTX_set_verify(srv->ssl_ctx.ctx,
Emeric Brun850efd52014-01-29 12:24:34 +01004544 verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004545 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004546 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004547 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004548 /* set CAfile to verify */
4549 if (!ssl_set_verify_locations_file(srv->ssl_ctx.ctx, srv->ssl_ctx.ca_file)) {
4550 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to set CA file '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004551 curproxy->id, srv->id,
4552 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004553 cfgerr++;
4554 }
4555 }
Emeric Brun850efd52014-01-29 12:24:34 +01004556 else {
4557 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Christopher Faulet767a84b2017-11-24 16:50:31 +01004558 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",
4559 curproxy->id, srv->id,
4560 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004561 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01004562 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4563 curproxy->id, srv->id,
4564 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004565 cfgerr++;
4566 }
Emeric Brunef42d922012-10-11 16:11:36 +02004567#ifdef X509_V_FLAG_CRL_CHECK
4568 if (srv->ssl_ctx.crl_file) {
4569 X509_STORE *store = SSL_CTX_get_cert_store(srv->ssl_ctx.ctx);
4570
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004571 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004572 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4573 curproxy->id, srv->id,
4574 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004575 cfgerr++;
4576 }
4577 else {
4578 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4579 }
4580 }
4581#endif
4582 }
4583
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004584 SSL_CTX_set_session_cache_mode(srv->ssl_ctx.ctx, SSL_SESS_CACHE_CLIENT |
4585 SSL_SESS_CACHE_NO_INTERNAL_STORE);
4586 SSL_CTX_sess_set_new_cb(srv->ssl_ctx.ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004587 if (srv->ssl_ctx.ciphers &&
4588 !SSL_CTX_set_cipher_list(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphers)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004589 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4590 curproxy->id, srv->id,
4591 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004592 cfgerr++;
4593 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004594
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004595#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004596 if (srv->ssl_ctx.ciphersuites &&
Pierre Cheynierbc34cd12019-03-21 16:15:47 +00004597 !SSL_CTX_set_ciphersuites(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphersuites)) {
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004598 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4599 curproxy->id, srv->id,
4600 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4601 cfgerr++;
4602 }
4603#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004604#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4605 if (srv->ssl_ctx.npn_str)
4606 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, srv);
4607#endif
4608#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4609 if (srv->ssl_ctx.alpn_str)
4610 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4611#endif
4612
Emeric Brun94324a42012-10-11 14:00:19 +02004613
4614 return cfgerr;
4615}
4616
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004617/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004618 * be NULL, in which case nothing is done. Returns the number of errors
4619 * encountered.
4620 */
Willy Tarreau03209342016-12-22 17:08:28 +01004621int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004622{
4623 struct ebmb_node *node;
4624 struct sni_ctx *sni;
4625 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004626 int errcode = 0;
4627 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004628
Willy Tarreaufce03112015-01-15 21:32:40 +01004629 /* Automatic memory computations need to know we use SSL there */
4630 global.ssl_used_frontend = 1;
4631
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004632 /* Make sure openssl opens /dev/urandom before the chroot */
4633 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004634 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004635 err++;
4636 }
4637 /* Create initial_ctx used to start the ssl connection before do switchctx */
4638 if (!bind_conf->initial_ctx) {
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004639 err += ssl_sock_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004640 /* It should not be necessary to call this function, but it's
4641 necessary first to check and move all initialisation related
4642 to initial_ctx in ssl_sock_initial_ctx. */
William Lallemand8b453912019-11-21 15:48:10 +01004643 errcode |= ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004644 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004645 if (bind_conf->default_ctx)
William Lallemand8b453912019-11-21 15:48:10 +01004646 errcode |= ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, &errmsg);
Emeric Brun0bed9942014-10-30 19:25:24 +01004647
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004648 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004649 while (node) {
4650 sni = ebmb_entry(node, struct sni_ctx, name);
Emeric Brun0bed9942014-10-30 19:25:24 +01004651 if (!sni->order && sni->ctx != bind_conf->default_ctx)
4652 /* only initialize the CTX on its first occurrence and
4653 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004654 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004655 node = ebmb_next(node);
4656 }
4657
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004658 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004659 while (node) {
4660 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004661 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004662 /* only initialize the CTX on its first occurrence and
4663 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004664 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
4665 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004666 node = ebmb_next(node);
4667 }
William Lallemand8b453912019-11-21 15:48:10 +01004668
4669 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004670 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004671 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004672 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004673 err++;
4674 }
4675
4676 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004677 return err;
4678}
4679
Willy Tarreau55d37912016-12-21 23:38:39 +01004680/* Prepares all the contexts for a bind_conf and allocates the shared SSL
4681 * context if needed. Returns < 0 on error, 0 on success. The warnings and
4682 * alerts are directly emitted since the rest of the stack does it below.
4683 */
4684int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
4685{
4686 struct proxy *px = bind_conf->frontend;
4687 int alloc_ctx;
4688 int err;
4689
4690 if (!bind_conf->is_ssl) {
4691 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004692 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
4693 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01004694 }
4695 return 0;
4696 }
4697 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004698 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004699 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
4700 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004701 }
4702 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004703 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
4704 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004705 return -1;
4706 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004707 }
William Lallemandc61c0b32017-12-04 18:46:39 +01004708 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004709 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02004710 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01004711 sizeof(*sh_ssl_sess_tree),
4712 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02004713 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004714 if (alloc_ctx == SHCTX_E_INIT_LOCK)
4715 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");
4716 else
4717 ha_alert("Unable to allocate SSL session cache.\n");
4718 return -1;
4719 }
4720 /* free block callback */
4721 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
4722 /* init the root tree within the extra space */
4723 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
4724 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01004725 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004726 err = 0;
4727 /* initialize all certificate contexts */
4728 err += ssl_sock_prepare_all_ctx(bind_conf);
4729
4730 /* initialize CA variables if the certificates generation is enabled */
4731 err += ssl_sock_load_ca(bind_conf);
4732
4733 return -err;
4734}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004735
4736/* release ssl context allocated for servers. */
4737void ssl_sock_free_srv_ctx(struct server *srv)
4738{
Olivier Houchardc7566002018-11-20 23:33:50 +01004739#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4740 if (srv->ssl_ctx.alpn_str)
4741 free(srv->ssl_ctx.alpn_str);
4742#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01004743#ifdef OPENSSL_NPN_NEGOTIATED
Olivier Houchardc7566002018-11-20 23:33:50 +01004744 if (srv->ssl_ctx.npn_str)
4745 free(srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01004746#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02004747 if (srv->ssl_ctx.reused_sess) {
4748 int i;
4749
4750 for (i = 0; i < global.nbthread; i++)
4751 free(srv->ssl_ctx.reused_sess[i].ptr);
4752 free(srv->ssl_ctx.reused_sess);
4753 }
4754
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004755 if (srv->ssl_ctx.ctx)
4756 SSL_CTX_free(srv->ssl_ctx.ctx);
4757}
4758
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004759/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004760 * be NULL, in which case nothing is done. The default_ctx is nullified too.
4761 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004762void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004763{
4764 struct ebmb_node *node, *back;
4765 struct sni_ctx *sni;
4766
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004767 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004768 while (node) {
4769 sni = ebmb_entry(node, struct sni_ctx, name);
4770 back = ebmb_next(node);
4771 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004772 SSL_CTX_free(sni->ctx);
William Lallemandb2408692020-06-24 09:54:29 +02004773 LIST_DEL(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004774 free(sni);
4775 node = back;
4776 }
4777
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004778 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004779 while (node) {
4780 sni = ebmb_entry(node, struct sni_ctx, name);
4781 back = ebmb_next(node);
4782 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004783 SSL_CTX_free(sni->ctx);
William Lallemandb2408692020-06-24 09:54:29 +02004784 LIST_DEL(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004785 free(sni);
4786 node = back;
4787 }
William Lallemandb2408692020-06-24 09:54:29 +02004788
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004789 SSL_CTX_free(bind_conf->initial_ctx);
4790 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02004791 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004792 bind_conf->default_ctx = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004793 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02004794}
William Lallemandb2408692020-06-24 09:54:29 +02004795
4796
4797void ssl_sock_deinit()
4798{
4799 crtlist_deinit(); /* must be free'd before the ckchs */
4800 ckch_deinit();
4801}
4802REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02004803
Willy Tarreau795cdab2016-12-22 17:30:54 +01004804/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
4805void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
4806{
4807 ssl_sock_free_ca(bind_conf);
4808 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004809 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01004810 free(bind_conf->ca_sign_file);
4811 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02004812 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01004813 free(bind_conf->keys_ref->filename);
4814 free(bind_conf->keys_ref->tlskeys);
4815 LIST_DEL(&bind_conf->keys_ref->list);
4816 free(bind_conf->keys_ref);
4817 }
4818 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004819 bind_conf->ca_sign_pass = NULL;
4820 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004821}
4822
Christopher Faulet31af49d2015-06-09 17:29:50 +02004823/* Load CA cert file and private key used to generate certificates */
4824int
Willy Tarreau03209342016-12-22 17:08:28 +01004825ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02004826{
Willy Tarreau03209342016-12-22 17:08:28 +01004827 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03004828 struct cert_key_and_chain *ckch = NULL;
4829 int ret = 0;
4830 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004831
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02004832 if (!bind_conf->generate_certs)
Shimi Gersner5846c492020-08-23 13:58:12 +03004833 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004834
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01004835#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02004836 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01004837 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004838 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02004839 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004840 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02004841#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02004842
Christopher Faulet31af49d2015-06-09 17:29:50 +02004843 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004844 ha_alert("Proxy '%s': cannot enable certificate generation, "
4845 "no CA certificate File configured at [%s:%d].\n",
4846 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03004847 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004848 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004849
Shimi Gersner5846c492020-08-23 13:58:12 +03004850 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02004851 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03004852 if (!ckch) {
4853 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
4854 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
4855 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004856 }
Shimi Gersner5846c492020-08-23 13:58:12 +03004857
4858 /* Try to parse file */
4859 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
4860 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
4861 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
4862 if (err) free(err);
4863 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004864 }
Shimi Gersner5846c492020-08-23 13:58:12 +03004865
4866 /* Fail if missing cert or pkey */
4867 if ((!ckch->cert) || (!ckch->key)) {
4868 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
4869 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
4870 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004871 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004872
Shimi Gersner5846c492020-08-23 13:58:12 +03004873 /* Final assignment to bind */
4874 bind_conf->ca_sign_ckch = ckch;
4875 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004876
Shimi Gersner5846c492020-08-23 13:58:12 +03004877 failed:
4878 if (ckch) {
4879 ssl_sock_free_cert_key_and_chain_contents(ckch);
4880 free(ckch);
4881 }
4882
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004883 bind_conf->generate_certs = 0;
Shimi Gersner5846c492020-08-23 13:58:12 +03004884 ret++;
4885 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004886}
4887
4888/* Release CA cert and private key used to generate certificated */
4889void
4890ssl_sock_free_ca(struct bind_conf *bind_conf)
4891{
Shimi Gersner5846c492020-08-23 13:58:12 +03004892 if (bind_conf->ca_sign_ckch) {
4893 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
4894 free(bind_conf->ca_sign_ckch);
4895 bind_conf->ca_sign_ckch = NULL;
4896 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004897}
4898
Emeric Brun46591952012-05-18 15:47:34 +02004899/*
4900 * This function is called if SSL * context is not yet allocated. The function
4901 * is designed to be called before any other data-layer operation and sets the
4902 * handshake flag on the connection. It is safe to call it multiple times.
4903 * It returns 0 on success and -1 in error case.
4904 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004905static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004906{
Olivier Houchard66ab4982019-02-26 18:37:15 +01004907 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02004908 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004909 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004910 return 0;
4911
Willy Tarreau3c728722014-01-23 13:50:42 +01004912 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02004913 return 0;
4914
Olivier Houchard66ab4982019-02-26 18:37:15 +01004915 ctx = pool_alloc(ssl_sock_ctx_pool);
4916 if (!ctx) {
4917 conn->err_code = CO_ER_SSL_NO_MEM;
4918 return -1;
4919 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004920 ctx->wait_event.tasklet = tasklet_new();
4921 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004922 conn->err_code = CO_ER_SSL_NO_MEM;
4923 pool_free(ssl_sock_ctx_pool, ctx);
4924 return -1;
4925 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004926 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
4927 ctx->wait_event.tasklet->context = ctx;
Willy Tarreaub421f9d2021-02-25 15:31:00 +01004928 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02004929 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01004930 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01004931 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004932 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01004933 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02004934 ctx->xprt_st = 0;
4935 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004936
4937 /* Only work with sockets for now, this should be adapted when we'll
4938 * add QUIC support.
4939 */
4940 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02004941 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004942 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
4943 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02004944 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01004945
Willy Tarreau20879a02012-12-03 16:32:10 +01004946 if (global.maxsslconn && sslconns >= global.maxsslconn) {
4947 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004948 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004949 }
Willy Tarreau403edff2012-09-06 11:58:37 +02004950
Emeric Brun46591952012-05-18 15:47:34 +02004951 /* If it is in client mode initiate SSL session
4952 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01004953 if (objt_server(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004954 int may_retry = 1;
4955
4956 retry_connect:
Emeric Brun46591952012-05-18 15:47:34 +02004957 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004958 ctx->ssl = SSL_new(__objt_server(conn->target)->ssl_ctx.ctx);
4959 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004960 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004961 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004962 goto retry_connect;
4963 }
Willy Tarreau20879a02012-12-03 16:32:10 +01004964 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004965 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004966 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004967 ctx->bio = BIO_new(ha_meth);
4968 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01004969 SSL_free(ctx->ssl);
4970 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004971 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004972 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004973 goto retry_connect;
4974 }
Emeric Brun55476152014-11-12 17:35:37 +01004975 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004976 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004977 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004978 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02004979 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02004980
Evan Broderbe554312013-06-27 00:05:25 -07004981 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004982 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
4983 SSL_free(ctx->ssl);
4984 ctx->ssl = NULL;
Emeric Brun55476152014-11-12 17:35:37 +01004985 conn->xprt_ctx = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004986 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004987 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004988 goto retry_connect;
4989 }
Emeric Brun55476152014-11-12 17:35:37 +01004990 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004991 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004992 }
4993
Olivier Houchard66ab4982019-02-26 18:37:15 +01004994 SSL_set_connect_state(ctx->ssl);
Willy Tarreau07d94e42018-09-20 10:57:52 +02004995 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
4996 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
4997 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 +01004998 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004999 SSL_SESSION_free(sess);
Willy Tarreau07d94e42018-09-20 10:57:52 +02005000 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
5001 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Olivier Houcharde6060c52017-11-16 17:42:52 +01005002 } else if (sess) {
5003 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005004 }
5005 }
Evan Broderbe554312013-06-27 00:05:25 -07005006
Emeric Brun46591952012-05-18 15:47:34 +02005007 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005008 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005009
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005010 _HA_ATOMIC_ADD(&sslconns, 1);
5011 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005012 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005013 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005014 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005015 return 0;
5016 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005017 else if (objt_listener(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005018 int may_retry = 1;
5019
5020 retry_accept:
Emeric Brun46591952012-05-18 15:47:34 +02005021 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005022 ctx->ssl = SSL_new(__objt_listener(conn->target)->bind_conf->initial_ctx);
5023 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005024 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005025 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005026 goto retry_accept;
5027 }
Willy Tarreau20879a02012-12-03 16:32:10 +01005028 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005029 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005030 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005031 ctx->bio = BIO_new(ha_meth);
5032 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01005033 SSL_free(ctx->ssl);
5034 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005035 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005036 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005037 goto retry_accept;
5038 }
Emeric Brun55476152014-11-12 17:35:37 +01005039 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005040 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005041 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005042 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02005043 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02005044
Emeric Brune1f38db2012-09-03 20:36:47 +02005045 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005046 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
5047 SSL_free(ctx->ssl);
5048 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005049 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005050 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005051 goto retry_accept;
5052 }
Emeric Brun55476152014-11-12 17:35:37 +01005053 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005054 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005055 }
5056
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005057#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005058 if (__objt_listener(conn->target)->bind_conf->ssl_conf.early_data) {
5059 b_alloc(&ctx->early_buf);
5060 SSL_set_max_early_data(ctx->ssl,
5061 /* Only allow early data if we managed to allocate
5062 * a buffer.
5063 */
5064 (!b_is_null(&ctx->early_buf)) ?
5065 global.tune.bufsize - global.tune.maxrewrite : 0);
5066 }
5067#endif
5068
Olivier Houchard66ab4982019-02-26 18:37:15 +01005069 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005070
Emeric Brun46591952012-05-18 15:47:34 +02005071 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005072 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005073#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreau5c6176d2021-02-05 10:24:54 +01005074 if (__objt_listener(conn->target)->bind_conf->ssl_conf.early_data)
Willy Tarreau5930fb22021-02-03 11:21:38 +01005075 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005076#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005077
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005078 _HA_ATOMIC_ADD(&sslconns, 1);
5079 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005080 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005081 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005082 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005083 return 0;
5084 }
5085 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005086 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005087err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005088 if (ctx && ctx->wait_event.tasklet)
5089 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005090 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005091 return -1;
5092}
5093
5094
5095/* This is the callback which is used when an SSL handshake is pending. It
5096 * updates the FD status if it wants some polling before being called again.
5097 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5098 * otherwise it returns non-zero and removes itself from the connection's
5099 * flags (the bit is provided in <flag> by the caller).
5100 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005101static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005102{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005103 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005104 int ret;
Willy Tarreaud2871402021-02-02 15:42:25 +01005105 socklen_t lskerr;
5106 int skerr;
5107
Emeric Brun46591952012-05-18 15:47:34 +02005108
Willy Tarreau3c728722014-01-23 13:50:42 +01005109 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005110 return 0;
5111
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005112 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005113 goto out_error;
5114
Willy Tarreaud2871402021-02-02 15:42:25 +01005115 /* don't start calculating a handshake on a dead connection */
5116 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5117 goto out_error;
5118
5119 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5120 * status from the lower layers, so let's check the FD directly. Ideally
5121 * the xprt layers should provide some status indicating their knowledge
5122 * of shutdowns or error.
5123 */
5124 skerr = 0;
5125 lskerr = sizeof(skerr);
5126 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5127 skerr != 0)
5128 goto out_error;
5129
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005130#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005131 /*
5132 * Check if we have early data. If we do, we have to read them
5133 * before SSL_do_handshake() is called, And there's no way to
5134 * detect early data, except to try to read them
5135 */
5136 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005137 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005138
Olivier Houchard54907bb2019-12-19 15:02:39 +01005139 while (1) {
5140 ret = SSL_read_early_data(ctx->ssl,
5141 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5142 &read_data);
5143 if (ret == SSL_READ_EARLY_DATA_ERROR)
5144 goto check_error;
5145 if (read_data > 0) {
5146 conn->flags |= CO_FL_EARLY_DATA;
5147 b_add(&ctx->early_buf, read_data);
5148 }
5149 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5150 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5151 if (!b_data(&ctx->early_buf))
5152 b_free(&ctx->early_buf);
5153 break;
5154 }
5155 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005156 }
5157#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005158 /* If we use SSL_do_handshake to process a reneg initiated by
5159 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5160 * Usually SSL_write and SSL_read are used and process implicitly
5161 * the reneg handshake.
5162 * Here we use SSL_peek as a workaround for reneg.
5163 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005164 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005165 char c;
5166
Olivier Houchard66ab4982019-02-26 18:37:15 +01005167 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005168 if (ret <= 0) {
5169 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005170 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005171
Emeric Brun674b7432012-11-08 19:21:55 +01005172 if (ret == SSL_ERROR_WANT_WRITE) {
5173 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005174 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005175 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005176 return 0;
5177 }
5178 else if (ret == SSL_ERROR_WANT_READ) {
5179 /* handshake may have been completed but we have
5180 * no more data to read.
5181 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005182 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005183 ret = 1;
5184 goto reneg_ok;
5185 }
5186 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005187 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005188 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005189 return 0;
5190 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005191#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005192 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005193 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005194 return 0;
5195 }
5196#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005197 else if (ret == SSL_ERROR_SYSCALL) {
5198 /* if errno is null, then connection was successfully established */
5199 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5200 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005201 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005202#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5203 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005204 conn->err_code = CO_ER_SSL_HANDSHAKE;
5205#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005206 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005207#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005208 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005209 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005210 empty_handshake = state == TLS_ST_BEFORE;
5211#else
Lukas Tribus49799162019-07-08 14:29:15 +02005212 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5213 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005214#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005215 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005216 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005217 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005218 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5219 else
5220 conn->err_code = CO_ER_SSL_EMPTY;
5221 }
5222 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005223 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005224 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5225 else
5226 conn->err_code = CO_ER_SSL_ABORT;
5227 }
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;
Willy Tarreau20879a02012-12-03 16:32:10 +01005232 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005233 conn->err_code = CO_ER_SSL_HANDSHAKE;
5234 }
Lukas Tribus49799162019-07-08 14:29:15 +02005235#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005236 }
Emeric Brun674b7432012-11-08 19:21:55 +01005237 goto out_error;
5238 }
5239 else {
5240 /* Fail on all other handshake errors */
5241 /* Note: OpenSSL may leave unread bytes in the socket's
5242 * buffer, causing an RST to be emitted upon close() on
5243 * TCP sockets. We first try to drain possibly pending
5244 * data to avoid this as much as possible.
5245 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005246 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005247 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005248 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005249 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005250 goto out_error;
5251 }
5252 }
5253 /* read some data: consider handshake completed */
5254 goto reneg_ok;
5255 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005256 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005257check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005258 if (ret != 1) {
5259 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005260 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005261
5262 if (ret == SSL_ERROR_WANT_WRITE) {
5263 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005264 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005265 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005266 return 0;
5267 }
5268 else if (ret == SSL_ERROR_WANT_READ) {
5269 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005270 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005271 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5272 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005273 return 0;
5274 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005275#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005276 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005277 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005278 return 0;
5279 }
5280#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005281 else if (ret == SSL_ERROR_SYSCALL) {
5282 /* if errno is null, then connection was successfully established */
5283 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5284 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005285 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005286#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5287 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005288 conn->err_code = CO_ER_SSL_HANDSHAKE;
5289#else
5290 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005291#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005292 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005293 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005294 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005295#else
Lukas Tribus49799162019-07-08 14:29:15 +02005296 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5297 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005298#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005299 if (empty_handshake) {
5300 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005301 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005302 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5303 else
5304 conn->err_code = CO_ER_SSL_EMPTY;
5305 }
5306 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005307 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005308 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5309 else
5310 conn->err_code = CO_ER_SSL_ABORT;
5311 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005312 }
5313 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005314 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005315 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5316 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005317 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005318 }
Lukas Tribus49799162019-07-08 14:29:15 +02005319#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005320 }
Willy Tarreau89230192012-09-28 20:22:13 +02005321 goto out_error;
5322 }
Emeric Brun46591952012-05-18 15:47:34 +02005323 else {
5324 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005325 /* Note: OpenSSL may leave unread bytes in the socket's
5326 * buffer, causing an RST to be emitted upon close() on
5327 * TCP sockets. We first try to drain possibly pending
5328 * data to avoid this as much as possible.
5329 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005330 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005331 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005332 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005333 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005334 goto out_error;
5335 }
5336 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005337#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005338 else {
5339 /*
5340 * If the server refused the early data, we have to send a
5341 * 425 to the client, as we no longer have the data to sent
5342 * them again.
5343 */
5344 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005345 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005346 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5347 goto out_error;
5348 }
5349 }
5350 }
5351#endif
5352
Emeric Brun46591952012-05-18 15:47:34 +02005353
Emeric Brun674b7432012-11-08 19:21:55 +01005354reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005355
Willy Tarreau5db847a2019-05-09 14:13:35 +02005356#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005357 /* ASYNC engine API doesn't support moving read/write
5358 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005359 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005360 */
5361 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005362 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005363#endif
Emeric Brun46591952012-05-18 15:47:34 +02005364 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005365 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005366 if (objt_server(conn->target)) {
5367 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5368 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5369 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005370 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005371 else {
5372 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5373 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5374 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5375 }
Emeric Brun46591952012-05-18 15:47:34 +02005376 }
5377
5378 /* The connection is now established at both layers, it's time to leave */
5379 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5380 return 1;
5381
5382 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005383 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005384 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005385 ERR_clear_error();
5386
Emeric Brun9fa89732012-10-04 17:09:56 +02005387 /* free resumed session if exists */
Willy Tarreau07d94e42018-09-20 10:57:52 +02005388 if (objt_server(conn->target) && __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5389 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
5390 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Emeric Brun9fa89732012-10-04 17:09:56 +02005391 }
5392
Emeric Brun46591952012-05-18 15:47:34 +02005393 /* Fail on all other handshake errors */
5394 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005395 if (!conn->err_code)
5396 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005397 return 0;
5398}
5399
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005400/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5401 * event subscriber <es> is not allowed to change from a previous call as long
5402 * as at least one event is still subscribed. The <event_type> must only be a
5403 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5404 * unless the transport layer was already released.
5405 */
5406static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005407{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005408 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005409
Olivier Houchard0ff28652019-06-24 18:57:39 +02005410 if (!ctx)
5411 return -1;
5412
Willy Tarreau113d52b2020-01-10 09:20:26 +01005413 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005414 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005415
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005416 ctx->subs = es;
5417 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005418
5419 /* we may have to subscribe to lower layers for new events */
5420 event_type &= ~ctx->wait_event.events;
5421 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5422 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005423 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005424}
5425
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005426/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5427 * The <es> pointer is not allowed to differ from the one passed to the
5428 * subscribe() call. It always returns zero.
5429 */
5430static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005431{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005432 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005433
Willy Tarreau113d52b2020-01-10 09:20:26 +01005434 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005435 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005436
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005437 es->events &= ~event_type;
5438 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005439 ctx->subs = NULL;
5440
5441 /* If we subscribed, and we're not doing the handshake,
5442 * then we subscribed because the upper layer asked for it,
5443 * as the upper layer is no longer interested, we can
5444 * unsubscribe too.
5445 */
5446 event_type &= ctx->wait_event.events;
5447 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5448 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005449
5450 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005451}
5452
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005453/* The connection has been taken over, so destroy the old tasklet and create
5454 * a new one. The original thread ID must be passed into orig_tid
5455 * It should be called with the takeover lock for the old thread held.
5456 * Returns 0 on success, and -1 on failure
5457 */
5458static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
5459{
5460 struct ssl_sock_ctx *ctx = xprt_ctx;
5461 struct tasklet *tl = tasklet_new();
5462
5463 if (!tl)
5464 return -1;
5465
5466 ctx->wait_event.tasklet->context = NULL;
5467 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
5468 ctx->wait_event.tasklet = tl;
5469 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5470 ctx->wait_event.tasklet->context = ctx;
5471 return 0;
5472}
5473
Willy Tarreaub0d3a282021-03-02 17:29:56 +01005474/* notify the next xprt that the connection is about to become idle and that it
5475 * may be stolen at any time after the function returns and that any tasklet in
5476 * the chain must be careful before dereferencing its context.
5477 */
5478static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
5479{
5480 struct ssl_sock_ctx *ctx = xprt_ctx;
5481
5482 if (!ctx || !ctx->wait_event.tasklet)
5483 return;
5484
5485 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5486 if (ctx->xprt)
5487 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
5488}
5489
5490/* notify the next xprt that the connection is not idle anymore and that it may
5491 * not be stolen before the next xprt_set_idle().
5492 */
5493static void ssl_set_used(struct connection *conn, void *xprt_ctx)
5494{
5495 struct ssl_sock_ctx *ctx = xprt_ctx;
5496
5497 if (!ctx || !ctx->wait_event.tasklet)
5498 return;
5499
5500 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5501 if (ctx->xprt)
5502 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
5503}
5504
Olivier Houchard2e055482019-05-27 19:50:12 +02005505/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5506 * Returns 0 on success, and non-zero on failure.
5507 */
5508static 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)
5509{
5510 struct ssl_sock_ctx *ctx = xprt_ctx;
5511
5512 if (oldxprt_ops != NULL)
5513 *oldxprt_ops = ctx->xprt;
5514 if (oldxprt_ctx != NULL)
5515 *oldxprt_ctx = ctx->xprt_ctx;
5516 ctx->xprt = toadd_ops;
5517 ctx->xprt_ctx = toadd_ctx;
5518 return 0;
5519}
5520
Olivier Houchard5149b592019-05-23 17:47:36 +02005521/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5522 * return 0, otherwise just call the remove_xprt method from the underlying
5523 * XPRT.
5524 */
5525static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5526{
5527 struct ssl_sock_ctx *ctx = xprt_ctx;
5528
5529 if (ctx->xprt_ctx == toremove_ctx) {
5530 ctx->xprt_ctx = newctx;
5531 ctx->xprt = newops;
5532 return 0;
5533 }
5534 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5535}
5536
Willy Tarreau9a5a0e02021-01-20 14:55:01 +01005537struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned short state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02005538{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005539 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005540 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005541 struct connection *conn;
5542 int conn_in_list;
5543 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005544
Willy Tarreaub0d3a282021-03-02 17:29:56 +01005545 if (state & TASK_F_USR1) {
5546 /* the tasklet was idling on an idle connection, it might have
5547 * been stolen, let's be careful!
5548 */
5549 HA_SPIN_LOCK(OTHER_LOCK, &idle_conns[tid].takeover_lock);
5550 if (tl->context == NULL) {
5551 HA_SPIN_UNLOCK(OTHER_LOCK, &idle_conns[tid].takeover_lock);
5552 tasklet_free(tl);
5553 return NULL;
5554 }
5555 conn = ctx->conn;
5556 conn_in_list = conn->flags & CO_FL_LIST_MASK;
5557 if (conn_in_list)
5558 MT_LIST_DEL(&conn->list);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005559 HA_SPIN_UNLOCK(OTHER_LOCK, &idle_conns[tid].takeover_lock);
Willy Tarreaub0d3a282021-03-02 17:29:56 +01005560 } else {
5561 conn = ctx->conn;
5562 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005563 }
Willy Tarreaub0d3a282021-03-02 17:29:56 +01005564
Olivier Houchardea8dd942019-05-20 14:02:16 +02005565 /* First if we're doing an handshake, try that */
Willy Tarreaub421f9d2021-02-25 15:31:00 +01005566 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005567 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreaub421f9d2021-02-25 15:31:00 +01005568 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5569 /* handshake completed, leave the bulk queue */
Willy Tarreaua0c6da12021-03-09 17:58:02 +01005570 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreaub421f9d2021-02-25 15:31:00 +01005571 }
5572 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005573 /* If we had an error, or the handshake is done and I/O is available,
5574 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005575 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005576 * we can't be sure conn_fd_handler() will be called again.
5577 */
5578 if ((ctx->conn->flags & CO_FL_ERROR) ||
5579 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005580 int woke = 0;
5581
5582 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005583 if (ctx->subs) {
5584 tasklet_wakeup(ctx->subs->tasklet);
5585 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005586 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005587 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005588 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005589
Olivier Houchardea8dd942019-05-20 14:02:16 +02005590 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005591 * upper layers know. If we have no mux, create it,
5592 * and once we have a mux, call its wake method if we didn't
5593 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005594 */
5595 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005596 if (!ctx->conn->mux)
5597 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005598 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005599 ret = ctx->conn->mux->wake(ctx->conn);
5600 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005601 }
5602 }
Olivier Houchard54907bb2019-12-19 15:02:39 +01005603#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5604 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005605 else if (b_data(&ctx->early_buf) && ctx->subs &&
5606 ctx->subs->events & SUB_RETRY_RECV) {
5607 tasklet_wakeup(ctx->subs->tasklet);
5608 ctx->subs->events &= ~SUB_RETRY_RECV;
5609 if (!ctx->subs->events)
5610 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005611 }
5612#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005613leave:
5614 if (!ret && conn_in_list) {
5615 struct server *srv = objt_server(conn->target);
5616
5617 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreaua9d7b762020-07-10 08:28:20 +02005618 MT_LIST_ADDQ(&srv->safe_conns[tid], &conn->list);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005619 else
Willy Tarreaua9d7b762020-07-10 08:28:20 +02005620 MT_LIST_ADDQ(&srv->idle_conns[tid], &conn->list);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005621 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005622 return NULL;
5623}
5624
Emeric Brun46591952012-05-18 15:47:34 +02005625/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01005626 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02005627 * buffer wraps, in which case a second call may be performed. The connection's
5628 * flags are updated with whatever special event is detected (error, read0,
5629 * empty). The caller is responsible for taking care of those events and
5630 * avoiding the call if inappropriate. The function does not call the
5631 * connection's polling update function, so the caller is responsible for this.
5632 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005633static 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 +02005634{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005635 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02005636 ssize_t ret;
5637 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02005638
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005639 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005640 goto out_error;
5641
Olivier Houchard54907bb2019-12-19 15:02:39 +01005642#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5643 if (b_data(&ctx->early_buf)) {
5644 try = b_contig_space(buf);
5645 if (try > b_data(&ctx->early_buf))
5646 try = b_data(&ctx->early_buf);
5647 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
5648 b_add(buf, try);
5649 b_del(&ctx->early_buf, try);
5650 if (b_data(&ctx->early_buf) == 0)
5651 b_free(&ctx->early_buf);
5652 return try;
5653 }
5654#endif
5655
Willy Tarreau911db9b2020-01-23 16:27:54 +01005656 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005657 /* a handshake was requested */
5658 return 0;
5659
Emeric Brun46591952012-05-18 15:47:34 +02005660 /* read the largest possible block. For this, we perform only one call
5661 * to recv() unless the buffer wraps and we exactly fill the first hunk,
5662 * in which case we accept to do it once again. A new attempt is made on
5663 * EINTR too.
5664 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01005665 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005666
Willy Tarreau591d4452018-06-15 17:21:00 +02005667 try = b_contig_space(buf);
5668 if (!try)
5669 break;
5670
Willy Tarreauabf08d92014-01-14 11:31:27 +01005671 if (try > count)
5672 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02005673
Olivier Houchard66ab4982019-02-26 18:37:15 +01005674 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005675
Emeric Brune1f38db2012-09-03 20:36:47 +02005676 if (conn->flags & CO_FL_ERROR) {
5677 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005678 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005679 }
Emeric Brun46591952012-05-18 15:47:34 +02005680 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02005681 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005682 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005683 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005684 }
Emeric Brun46591952012-05-18 15:47:34 +02005685 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005686 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005687 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005688 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02005689 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005690 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005691#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005692 /* Async mode can be re-enabled, because we're leaving data state.*/
5693 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005694 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005695#endif
Emeric Brun46591952012-05-18 15:47:34 +02005696 break;
5697 }
5698 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005699 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005700 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5701 SUB_RETRY_RECV,
5702 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01005703 /* handshake is running, and it may need to re-enable read */
5704 conn->flags |= CO_FL_SSL_WAIT_HS;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005705#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005706 /* Async mode can be re-enabled, because we're leaving data state.*/
5707 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005708 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005709#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005710 break;
5711 }
Emeric Brun46591952012-05-18 15:47:34 +02005712 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005713 } else if (ret == SSL_ERROR_ZERO_RETURN)
5714 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005715 /* For SSL_ERROR_SYSCALL, make sure to clear the error
5716 * stack before shutting down the connection for
5717 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005718 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
5719 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02005720 /* otherwise it's a real error */
5721 goto out_error;
5722 }
5723 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005724 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005725 return done;
5726
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005727 clear_ssl_error:
5728 /* Clear openssl global errors stack */
5729 ssl_sock_dump_errors(conn);
5730 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02005731 read0:
5732 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005733 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005734
Emeric Brun46591952012-05-18 15:47:34 +02005735 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005736 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01005737 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005738 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005739 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005740 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005741}
5742
5743
Willy Tarreau787db9a2018-06-14 18:31:46 +02005744/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
5745 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
5746 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02005747 * Only one call to send() is performed, unless the buffer wraps, in which case
5748 * a second call may be performed. The connection's flags are updated with
5749 * whatever special event is detected (error, empty). The caller is responsible
5750 * for taking care of those events and avoiding the call if inappropriate. The
5751 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02005752 * is responsible for this. The buffer's output is not adjusted, it's up to the
5753 * caller to take care of this. It's up to the caller to update the buffer's
5754 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02005755 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005756static 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 +02005757{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005758 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005759 ssize_t ret;
5760 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02005761
5762 done = 0;
5763
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005764 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005765 goto out_error;
5766
Willy Tarreau911db9b2020-01-23 16:27:54 +01005767 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005768 /* a handshake was requested */
5769 return 0;
5770
5771 /* send the largest possible block. For this we perform only one call
5772 * to send() unless the buffer wraps and we exactly fill the first hunk,
5773 * in which case we accept to do it once again.
5774 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02005775 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005776#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005777 size_t written_data;
5778#endif
5779
Willy Tarreau787db9a2018-06-14 18:31:46 +02005780 try = b_contig_data(buf, done);
5781 if (try > count)
5782 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01005783
Willy Tarreau7bed9452014-02-02 02:00:24 +01005784 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005785 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01005786 global_ssl.max_record && try > global_ssl.max_record) {
5787 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005788 }
5789 else {
5790 /* we need to keep the information about the fact that
5791 * we're not limiting the upcoming send(), because if it
5792 * fails, we'll have to retry with at least as many data.
5793 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005794 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005795 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01005796
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005797#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02005798 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005799 unsigned int max_early;
5800
Olivier Houchard522eea72017-11-03 16:27:47 +01005801 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01005802 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01005803 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005804 if (SSL_get0_session(ctx->ssl))
5805 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01005806 else
5807 max_early = 0;
5808 }
5809
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005810 if (try + ctx->sent_early_data > max_early) {
5811 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01005812 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02005813 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005814 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005815 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01005816 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005817 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005818 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005819 if (ret == 1) {
5820 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005821 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005822 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005823 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005824 /* Initiate the handshake, now */
5825 tasklet_wakeup(ctx->wait_event.tasklet);
5826 }
Olivier Houchard522eea72017-11-03 16:27:47 +01005827
Olivier Houchardc2aae742017-09-22 18:26:28 +02005828 }
5829
5830 } else
5831#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005832 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01005833
Emeric Brune1f38db2012-09-03 20:36:47 +02005834 if (conn->flags & CO_FL_ERROR) {
5835 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005836 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005837 }
Emeric Brun46591952012-05-18 15:47:34 +02005838 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005839 /* A send succeeded, so we can consider ourself connected */
5840 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005841 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005842 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005843 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005844 }
5845 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005846 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005847
Emeric Brun46591952012-05-18 15:47:34 +02005848 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005849 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01005850 /* handshake is running, and it may need to re-enable write */
5851 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005852 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005853#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005854 /* Async mode can be re-enabled, because we're leaving data state.*/
5855 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005856 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005857#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005858 break;
5859 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005860
Emeric Brun46591952012-05-18 15:47:34 +02005861 break;
5862 }
5863 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005864 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02005865 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005866 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5867 SUB_RETRY_RECV,
5868 &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005869#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005870 /* Async mode can be re-enabled, because we're leaving data state.*/
5871 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005872 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005873#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005874 break;
5875 }
Emeric Brun46591952012-05-18 15:47:34 +02005876 goto out_error;
5877 }
5878 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005879 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005880 return done;
5881
5882 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005883 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005884 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005885 ERR_clear_error();
5886
Emeric Brun46591952012-05-18 15:47:34 +02005887 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005888 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005889}
5890
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005891static void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02005892
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005893 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005894
Olivier Houchardea8dd942019-05-20 14:02:16 +02005895
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005896 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005897 if (ctx->wait_event.events != 0)
5898 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
5899 ctx->wait_event.events,
5900 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01005901 if (ctx->subs) {
5902 ctx->subs->events = 0;
5903 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005904 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005905
Olivier Houchard692c1d02019-05-23 18:41:47 +02005906 if (ctx->xprt->close)
5907 ctx->xprt->close(conn, ctx->xprt_ctx);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005908#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +02005909 if (global_ssl.async) {
5910 OSSL_ASYNC_FD all_fd[32], afd;
5911 size_t num_all_fds = 0;
5912 int i;
5913
Olivier Houchard66ab4982019-02-26 18:37:15 +01005914 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005915 if (num_all_fds > 32) {
5916 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
5917 return;
5918 }
5919
Olivier Houchard66ab4982019-02-26 18:37:15 +01005920 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005921
5922 /* If an async job is pending, we must try to
5923 to catch the end using polling before calling
5924 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005925 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02005926 for (i=0 ; i < num_all_fds ; i++) {
5927 /* switch on an handler designed to
5928 * handle the SSL_free
5929 */
5930 afd = all_fd[i];
5931 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005932 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02005933 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00005934 /* To ensure that the fd cache won't be used
5935 * and we'll catch a real RD event.
5936 */
5937 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02005938 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005939 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005940 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005941 _HA_ATOMIC_ADD(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005942 return;
5943 }
Emeric Brun3854e012017-05-17 20:42:48 +02005944 /* Else we can remove the fds from the fdtab
5945 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02005946 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02005947 * because the fd is owned by the engine.
5948 * the engine is responsible to close
5949 */
5950 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +02005951 fd_stop_both(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005952 }
5953#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005954 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01005955 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005956 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005957 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005958 _HA_ATOMIC_SUB(&sslconns, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005959 }
Emeric Brun46591952012-05-18 15:47:34 +02005960}
5961
5962/* This function tries to perform a clean shutdown on an SSL connection, and in
5963 * any case, flags the connection as reusable if no handshake was in progress.
5964 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005965static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02005966{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005967 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005968
Willy Tarreau911db9b2020-01-23 16:27:54 +01005969 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005970 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01005971 if (!clean)
5972 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005973 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005974 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005975 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01005976 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005977 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005978 ERR_clear_error();
5979 }
Emeric Brun46591952012-05-18 15:47:34 +02005980}
5981
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01005982
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005983/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01005984int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
5985{
5986 struct ssl_sock_ctx *ctx;
5987 X509 *crt;
5988
5989 if (!ssl_sock_is_ssl(conn))
5990 return 0;
5991
5992 ctx = conn->xprt_ctx;
5993
5994 crt = SSL_get_certificate(ctx->ssl);
5995 if (!crt)
5996 return 0;
5997
5998 return cert_get_pkey_algo(crt, out);
5999}
6000
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006001/* used for ppv2 cert signature (can be used for logging) */
6002const char *ssl_sock_get_cert_sig(struct connection *conn)
6003{
Christopher Faulet82004142019-09-10 10:12:03 +02006004 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006005
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006006 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6007 X509 *crt;
6008
6009 if (!ssl_sock_is_ssl(conn))
6010 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006011 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006012 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006013 if (!crt)
6014 return NULL;
6015 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6016 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6017}
6018
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006019/* used for ppv2 authority */
6020const char *ssl_sock_get_sni(struct connection *conn)
6021{
6022#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006023 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006024
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006025 if (!ssl_sock_is_ssl(conn))
6026 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006027 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006028 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006029#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006030 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006031#endif
6032}
6033
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006034/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006035const char *ssl_sock_get_cipher_name(struct connection *conn)
6036{
Christopher Faulet82004142019-09-10 10:12:03 +02006037 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006038
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006039 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006040 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006041 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006042 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006043}
6044
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006045/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006046const char *ssl_sock_get_proto_version(struct connection *conn)
6047{
Christopher Faulet82004142019-09-10 10:12:03 +02006048 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006049
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006050 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006051 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006052 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006053 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006054}
6055
Olivier Houchardab28a322018-12-21 19:45:40 +01006056void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6057{
6058#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02006059 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006060
Olivier Houcharde488ea82019-06-28 14:10:33 +02006061 if (!ssl_sock_is_ssl(conn))
6062 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006063 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006064 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006065#endif
6066}
6067
Willy Tarreau119a4082016-12-22 21:58:38 +01006068/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6069 * to disable SNI.
6070 */
Willy Tarreau63076412015-07-10 11:33:32 +02006071void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6072{
6073#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006074 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006075
Willy Tarreau119a4082016-12-22 21:58:38 +01006076 char *prev_name;
6077
Willy Tarreau63076412015-07-10 11:33:32 +02006078 if (!ssl_sock_is_ssl(conn))
6079 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006080 ctx = conn->xprt_ctx;
Willy Tarreau63076412015-07-10 11:33:32 +02006081
Willy Tarreau119a4082016-12-22 21:58:38 +01006082 /* if the SNI changes, we must destroy the reusable context so that a
6083 * new connection will present a new SNI. As an optimization we could
6084 * later imagine having a small cache of ssl_ctx to hold a few SNI per
6085 * server.
6086 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006087 prev_name = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau119a4082016-12-22 21:58:38 +01006088 if ((!prev_name && hostname) ||
6089 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006090 SSL_set_session(ctx->ssl, NULL);
Willy Tarreau119a4082016-12-22 21:58:38 +01006091
Olivier Houchard66ab4982019-02-26 18:37:15 +01006092 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006093#endif
6094}
6095
Emeric Brun0abf8362014-06-24 18:26:41 +02006096/* Extract peer certificate's common name into the chunk dest
6097 * Returns
6098 * the len of the extracted common name
6099 * or 0 if no CN found in DN
6100 * or -1 on error case (i.e. no peer certificate)
6101 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006102int ssl_sock_get_remote_common_name(struct connection *conn,
6103 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006104{
Christopher Faulet82004142019-09-10 10:12:03 +02006105 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04006106 X509 *crt = NULL;
6107 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006108 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006109 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006110 .area = (char *)&find_cn,
6111 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006112 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006113 int result = -1;
David Safb76832014-05-08 23:42:08 -04006114
6115 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02006116 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02006117 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006118
6119 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006120 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006121 if (!crt)
6122 goto out;
6123
6124 name = X509_get_subject_name(crt);
6125 if (!name)
6126 goto out;
David Safb76832014-05-08 23:42:08 -04006127
Emeric Brun0abf8362014-06-24 18:26:41 +02006128 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6129out:
David Safb76832014-05-08 23:42:08 -04006130 if (crt)
6131 X509_free(crt);
6132
6133 return result;
6134}
6135
Dave McCowan328fb582014-07-30 10:39:13 -04006136/* returns 1 if client passed a certificate for this session, 0 if not */
6137int ssl_sock_get_cert_used_sess(struct connection *conn)
6138{
Christopher Faulet82004142019-09-10 10:12:03 +02006139 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006140 X509 *crt = NULL;
6141
6142 if (!ssl_sock_is_ssl(conn))
6143 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006144 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006145
6146 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006147 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006148 if (!crt)
6149 return 0;
6150
6151 X509_free(crt);
6152 return 1;
6153}
6154
6155/* returns 1 if client passed a certificate for this connection, 0 if not */
6156int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006157{
Christopher Faulet82004142019-09-10 10:12:03 +02006158 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006159
David Safb76832014-05-08 23:42:08 -04006160 if (!ssl_sock_is_ssl(conn))
6161 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006162 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006163 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006164}
6165
6166/* returns result from SSL verify */
6167unsigned int ssl_sock_get_verify_result(struct connection *conn)
6168{
Christopher Faulet82004142019-09-10 10:12:03 +02006169 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006170
David Safb76832014-05-08 23:42:08 -04006171 if (!ssl_sock_is_ssl(conn))
6172 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006173 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006174 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006175}
6176
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006177/* Returns the application layer protocol name in <str> and <len> when known.
6178 * Zero is returned if the protocol name was not found, otherwise non-zero is
6179 * returned. The string is allocated in the SSL context and doesn't have to be
6180 * freed by the caller. NPN is also checked if available since older versions
6181 * of openssl (1.0.1) which are more common in field only support this one.
6182 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006183static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006184{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006185#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6186 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006187 struct ssl_sock_ctx *ctx = xprt_ctx;
6188 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006189 return 0;
6190
6191 *str = NULL;
6192
6193#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006194 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006195 if (*str)
6196 return 1;
6197#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006198#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006199 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006200 if (*str)
6201 return 1;
6202#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006203#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006204 return 0;
6205}
6206
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006207/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006208int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006209{
6210 X509 *ca;
6211 X509_NAME *name = NULL;
6212 ASN1_OCTET_STRING *skid = NULL;
6213 STACK_OF(X509) *chain = NULL;
6214 struct issuer_chain *issuer;
6215 struct eb64_node *node;
6216 char *path;
6217 u64 key;
6218 int ret = 0;
6219
6220 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6221 if (chain == NULL) {
6222 chain = sk_X509_new_null();
6223 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6224 name = X509_get_subject_name(ca);
6225 }
6226 if (!sk_X509_push(chain, ca)) {
6227 X509_free(ca);
6228 goto end;
6229 }
6230 }
6231 if (!chain) {
6232 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6233 goto end;
6234 }
6235 if (!skid) {
6236 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6237 goto end;
6238 }
6239 if (!name) {
6240 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6241 goto end;
6242 }
6243 key = XXH64(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006244 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006245 issuer = container_of(node, typeof(*issuer), node);
6246 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6247 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6248 goto end;
6249 }
6250 }
6251 issuer = calloc(1, sizeof *issuer);
6252 path = strdup(fp);
6253 if (!issuer || !path) {
6254 free(issuer);
6255 free(path);
6256 goto end;
6257 }
6258 issuer->node.key = key;
6259 issuer->path = path;
6260 issuer->chain = chain;
6261 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006262 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006263 ret = 1;
6264 end:
6265 if (skid)
6266 ASN1_OCTET_STRING_free(skid);
6267 if (chain)
6268 sk_X509_pop_free(chain, X509_free);
6269 return ret;
6270}
6271
William Lallemandda8584c2020-05-14 10:14:37 +02006272 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006273{
6274 AUTHORITY_KEYID *akid;
6275 struct issuer_chain *issuer = NULL;
6276
6277 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemand829d0712020-11-19 16:24:13 +01006278 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006279 struct eb64_node *node;
6280 u64 hk;
6281 hk = XXH64(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
6282 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6283 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6284 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6285 issuer = ti;
6286 break;
6287 }
6288 }
6289 AUTHORITY_KEYID_free(akid);
6290 }
6291 return issuer;
6292}
6293
William Lallemanddad31052020-05-14 17:47:32 +02006294void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006295{
6296 struct eb64_node *node, *back;
6297 struct issuer_chain *issuer;
6298
William Lallemande0f3fd52020-02-25 14:53:06 +01006299 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006300 while (node) {
6301 issuer = container_of(node, typeof(*issuer), node);
6302 back = eb64_next(node);
6303 eb64_delete(node);
6304 free(issuer->path);
6305 sk_X509_pop_free(issuer->chain, X509_free);
6306 free(issuer);
6307 node = back;
6308 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006309}
6310
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006311#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006312static int ssl_check_async_engine_count(void) {
6313 int err_code = 0;
6314
Emeric Brun3854e012017-05-17 20:42:48 +02006315 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006316 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006317 err_code = ERR_ABORT;
6318 }
6319 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006320}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006321#endif
6322
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006323/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau767dedd2021-01-21 08:53:50 +01006324 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006325 */
Willy Tarreau6cb467e2021-01-21 08:26:06 +01006326static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006327{
6328 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau767dedd2021-01-21 08:53:50 +01006329 int ret = 0;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006330
6331 if (!sctx)
Willy Tarreau767dedd2021-01-21 08:53:50 +01006332 return ret;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006333
Willy Tarreau767dedd2021-01-21 08:53:50 +01006334 if (sctx->conn != conn) {
6335 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6336 ret = 1;
6337 }
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006338 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6339
6340 if (sctx->xprt) {
6341 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6342 if (sctx->xprt_ctx)
6343 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6344 }
6345
6346 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau767dedd2021-01-21 08:53:50 +01006347
6348 /* as soon as a shutdown is reported the lower layer unregisters its
6349 * subscriber, so the situations below are transient and rare enough to
6350 * be reported as suspicious. In any case they shouldn't last.
6351 */
6352 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
6353 ret = 1;
6354 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
6355 ret = 1;
6356
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006357 chunk_appendf(&trash, " .subs=%p", sctx->subs);
6358 if (sctx->subs) {
6359 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau767dedd2021-01-21 08:53:50 +01006360 if (sctx->subs->tasklet->calls >= 1000000)
6361 ret = 1;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006362 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
6363 sctx->subs->tasklet->calls,
6364 sctx->subs->tasklet->context);
6365 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
6366 chunk_appendf(&trash, ")");
6367 }
6368 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
6369 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau767dedd2021-01-21 08:53:50 +01006370 return ret;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006371}
6372
William Lallemand32af2032016-10-29 18:09:35 +02006373/* This function is used with TLS ticket keys management. It permits to browse
6374 * each reference. The variable <getnext> must contain the current node,
6375 * <end> point to the root node.
6376 */
6377#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6378static inline
6379struct tls_keys_ref *tlskeys_list_get_next(struct tls_keys_ref *getnext, struct list *end)
6380{
6381 struct tls_keys_ref *ref = getnext;
6382
6383 while (1) {
6384
6385 /* Get next list entry. */
6386 ref = LIST_NEXT(&ref->list, struct tls_keys_ref *, list);
6387
6388 /* If the entry is the last of the list, return NULL. */
6389 if (&ref->list == end)
6390 return NULL;
6391
6392 return ref;
6393 }
6394}
6395
6396static inline
6397struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6398{
6399 int id;
6400 char *error;
6401
6402 /* If the reference starts by a '#', this is numeric id. */
6403 if (reference[0] == '#') {
6404 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6405 id = strtol(reference + 1, &error, 10);
6406 if (*error != '\0')
6407 return NULL;
6408
6409 /* Perform the unique id lookup. */
6410 return tlskeys_ref_lookupid(id);
6411 }
6412
6413 /* Perform the string lookup. */
6414 return tlskeys_ref_lookup(reference);
6415}
6416#endif
6417
6418
6419#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6420
6421static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6422
6423static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6424 return cli_io_handler_tlskeys_files(appctx);
6425}
6426
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006427/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6428 * (next index to be dumped), and cli.p0 (next key reference).
6429 */
William Lallemand32af2032016-10-29 18:09:35 +02006430static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6431
6432 struct stream_interface *si = appctx->owner;
6433
6434 switch (appctx->st2) {
6435 case STAT_ST_INIT:
6436 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006437 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006438 * later and restart at the state "STAT_ST_INIT".
6439 */
6440 chunk_reset(&trash);
6441
6442 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6443 chunk_appendf(&trash, "# id secret\n");
6444 else
6445 chunk_appendf(&trash, "# id (file)\n");
6446
Willy Tarreau06d80a92017-10-19 14:32:15 +02006447 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006448 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006449 return 0;
6450 }
6451
William Lallemand32af2032016-10-29 18:09:35 +02006452 /* Now, we start the browsing of the references lists.
6453 * Note that the following call to LIST_ELEM return bad pointer. The only
6454 * available field of this pointer is <list>. It is used with the function
6455 * tlskeys_list_get_next() for retruning the first available entry
6456 */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006457 if (appctx->ctx.cli.p0 == NULL) {
6458 appctx->ctx.cli.p0 = LIST_ELEM(&tlskeys_reference, struct tls_keys_ref *, list);
6459 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006460 }
6461
6462 appctx->st2 = STAT_ST_LIST;
6463 /* fall through */
6464
6465 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006466 while (appctx->ctx.cli.p0) {
6467 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006468
6469 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006470 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006471 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006472
6473 if (appctx->ctx.cli.i1 == 0)
6474 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6475
William Lallemand32af2032016-10-29 18:09:35 +02006476 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006477 int head;
6478
6479 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6480 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006481 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006482 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006483
6484 chunk_reset(t2);
6485 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006486 if (ref->key_size_bits == 128) {
6487 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6488 sizeof(struct tls_sess_key_128),
6489 t2->area, t2->size);
6490 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6491 t2->area);
6492 }
6493 else if (ref->key_size_bits == 256) {
6494 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6495 sizeof(struct tls_sess_key_256),
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 {
6501 /* This case should never happen */
6502 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6503 }
William Lallemand32af2032016-10-29 18:09:35 +02006504
Willy Tarreau06d80a92017-10-19 14:32:15 +02006505 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006506 /* let's try again later from this stream. We add ourselves into
6507 * this stream's users so that it can remove us upon termination.
6508 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006509 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006510 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006511 return 0;
6512 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006513 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006514 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006515 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006516 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006517 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006518 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006519 /* let's try again later from this stream. We add ourselves into
6520 * this stream's users so that it can remove us upon termination.
6521 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006522 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006523 return 0;
6524 }
6525
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006526 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006527 break;
6528
6529 /* get next list entry and check the end of the list */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006530 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006531 }
6532
6533 appctx->st2 = STAT_ST_FIN;
6534 /* fall through */
6535
6536 default:
6537 appctx->st2 = STAT_ST_FIN;
6538 return 1;
6539 }
6540 return 0;
6541}
6542
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006543/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006544static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006545{
William Lallemand32af2032016-10-29 18:09:35 +02006546 /* no parameter, shows only file list */
6547 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006548 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006549 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006550 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006551 }
6552
6553 if (args[2][0] == '*') {
6554 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006555 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006556 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006557 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006558 if (!appctx->ctx.cli.p0)
6559 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006560 }
William Lallemand32af2032016-10-29 18:09:35 +02006561 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006562 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006563}
6564
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006565static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006566{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006567 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006568 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006569
William Lallemand32af2032016-10-29 18:09:35 +02006570 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006571 if (!*args[3] || !*args[4])
6572 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 +02006573
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006574 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006575 if (!ref)
6576 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006577
Willy Tarreau1c913e42018-08-22 05:26:57 +02006578 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006579 if (ret < 0)
6580 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006581
Willy Tarreau1c913e42018-08-22 05:26:57 +02006582 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006583 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6584 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006585
Willy Tarreau9d008692019-08-09 11:21:01 +02006586 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006587}
William Lallemandd4f946c2019-12-05 10:26:40 +01006588#endif
William Lallemand419e6342020-04-08 12:05:39 +02006589
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006590static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006591{
6592#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6593 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006594 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006595
6596 if (!payload)
6597 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006598
6599 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006600 if (!*payload)
6601 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006602
6603 /* remove \r and \n from the payload */
6604 for (i = 0, j = 0; payload[i]; i++) {
6605 if (payload[i] == '\r' || payload[i] == '\n')
6606 continue;
6607 payload[j++] = payload[i];
6608 }
6609 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006610
Willy Tarreau1c913e42018-08-22 05:26:57 +02006611 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006612 if (ret < 0)
6613 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006614
Willy Tarreau1c913e42018-08-22 05:26:57 +02006615 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02006616 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02006617 if (err)
6618 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
6619 else
6620 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006621 }
Willy Tarreau9d008692019-08-09 11:21:01 +02006622
6623 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006624#else
Willy Tarreau9d008692019-08-09 11:21:01 +02006625 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 +02006626#endif
6627
Elliot Otchet71f82972020-01-15 08:12:14 -05006628}
6629
William Lallemand32af2032016-10-29 18:09:35 +02006630/* register cli keywords */
6631static struct cli_kw_list cli_kws = {{ },{
6632#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6633 { { "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 +02006634 { { "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 +02006635#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006636 { { "set", "ssl", "ocsp-response", NULL }, NULL, cli_parse_set_ocspresponse, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02006637 { { NULL }, NULL, NULL, NULL }
6638}};
6639
Willy Tarreau0108d902018-11-25 19:14:37 +01006640INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02006641
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02006642/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02006643struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02006644 .snd_buf = ssl_sock_from_buf,
6645 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01006646 .subscribe = ssl_subscribe,
6647 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02006648 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02006649 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02006650 .rcv_pipe = NULL,
6651 .snd_pipe = NULL,
6652 .shutr = NULL,
6653 .shutw = ssl_sock_shutw,
6654 .close = ssl_sock_close,
6655 .init = ssl_sock_init,
Willy Tarreau55d37912016-12-21 23:38:39 +01006656 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01006657 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01006658 .prepare_srv = ssl_sock_prepare_srv_ctx,
6659 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006660 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006661 .takeover = ssl_takeover,
Willy Tarreaub0d3a282021-03-02 17:29:56 +01006662 .set_idle = ssl_set_idle,
6663 .set_used = ssl_set_used,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01006664 .name = "SSL",
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006665 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02006666};
6667
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006668enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
6669 struct session *sess, struct stream *s, int flags)
6670{
6671 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006672 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006673
6674 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006675 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006676
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006677 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006678 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006679 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006680 s->req.flags |= CF_READ_NULL;
6681 return ACT_RET_YIELD;
6682 }
6683 }
6684 return (ACT_RET_CONT);
6685}
6686
6687static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
6688{
6689 rule->action_ptr = ssl_action_wait_for_hs;
6690
6691 return ACT_RET_PRS_OK;
6692}
6693
6694static struct action_kw_list http_req_actions = {ILH, {
6695 { "wait-for-handshake", ssl_parse_wait_for_hs },
6696 { /* END */ }
6697}};
6698
Willy Tarreau0108d902018-11-25 19:14:37 +01006699INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
6700
Ilya Shipitsin49bab752021-02-06 18:59:22 +05006701#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006702
6703static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6704{
6705 if (ptr) {
6706 chunk_destroy(ptr);
6707 free(ptr);
6708 }
6709}
6710
6711#endif
William Lallemand76b4a122020-08-04 17:41:39 +02006712
6713#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
6714static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6715{
6716 struct ocsp_cbk_arg *ocsp_arg;
6717
6718 if (ptr) {
6719 ocsp_arg = ptr;
6720
6721 if (ocsp_arg->is_single) {
6722 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
6723 ocsp_arg->s_ocsp = NULL;
6724 } else {
6725 int i;
6726
6727 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
6728 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
6729 ocsp_arg->m_ocsp[i] = NULL;
6730 }
6731 }
6732 free(ocsp_arg);
6733 }
6734}
6735#endif
6736
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006737static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6738{
Willy Tarreaubafbe012017-11-24 17:34:44 +01006739 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006740}
William Lallemand7d42ef52020-07-06 11:41:30 +02006741
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05006742#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02006743static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6744{
6745 struct ssl_keylog *keylog;
6746
6747 if (!ptr)
6748 return;
6749
6750 keylog = ptr;
6751
6752 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
6753 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
6754 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
6755 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
6756 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
6757 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
6758 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
6759 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
6760
6761 pool_free(pool_head_ssl_keylog, ptr);
6762}
6763#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006764
Emeric Brun46591952012-05-18 15:47:34 +02006765__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02006766static void __ssl_sock_init(void)
6767{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006768#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006769 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006770 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006771#endif
Emeric Brun46591952012-05-18 15:47:34 +02006772
Willy Tarreauef934602016-12-22 23:12:01 +01006773 if (global_ssl.listen_default_ciphers)
6774 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
6775 if (global_ssl.connect_default_ciphers)
6776 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Emmanuel Hocdet839af572019-05-14 16:27:35 +02006777#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02006778 if (global_ssl.listen_default_ciphersuites)
6779 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
6780 if (global_ssl.connect_default_ciphersuites)
6781 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
6782#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01006783
Willy Tarreau13e14102016-12-22 20:25:26 +01006784 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006785#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02006786 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08006787#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006788#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006789 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006790 n = sk_SSL_COMP_num(cm);
6791 while (n--) {
6792 (void) sk_SSL_COMP_pop(cm);
6793 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006794#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006795
Willy Tarreau5db847a2019-05-09 14:13:35 +02006796#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006797 ssl_locking_init();
6798#endif
Ilya Shipitsin49bab752021-02-06 18:59:22 +05006799#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006800 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
6801#endif
William Lallemand76b4a122020-08-04 17:41:39 +02006802
6803#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
6804 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
6805#endif
6806
Thierry FOURNIER28962c92018-06-17 21:37:05 +02006807 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02006808 ssl_capture_ptr_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_capture_free_func);
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05006809#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02006810 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
6811#endif
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006812#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006813 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006814 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006815#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01006816#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6817 hap_register_post_check(tlskeys_finalize_config);
6818#endif
Willy Tarreau80713382018-11-26 10:19:54 +01006819
6820 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
6821 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
6822
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006823 hap_register_post_deinit(ssl_free_global_issuers);
6824
Willy Tarreau80713382018-11-26 10:19:54 +01006825#ifndef OPENSSL_NO_DH
6826 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
6827 hap_register_post_deinit(ssl_free_dh);
6828#endif
6829#ifndef OPENSSL_NO_ENGINE
6830 hap_register_post_deinit(ssl_free_engines);
6831#endif
6832 /* Load SSL string for the verbose & debug mode. */
6833 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02006834 ha_meth = BIO_meth_new(0x666, "ha methods");
6835 BIO_meth_set_write(ha_meth, ha_ssl_write);
6836 BIO_meth_set_read(ha_meth, ha_ssl_read);
6837 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
6838 BIO_meth_set_create(ha_meth, ha_ssl_new);
6839 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
6840 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
6841 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02006842
6843 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006844
Dragan Dosen9ac98092020-05-11 15:51:45 +02006845 /* Try to register dedicated SSL/TLS protocol message callbacks for
6846 * heartbleed attack (CVE-2014-0160) and clienthello.
6847 */
6848 hap_register_post_check(ssl_sock_register_msg_callbacks);
6849
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006850 /* Try to free all callbacks that were registered by using
6851 * ssl_sock_register_msg_callback().
6852 */
6853 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01006854}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01006855
Willy Tarreau80713382018-11-26 10:19:54 +01006856/* Compute and register the version string */
6857static void ssl_register_build_options()
6858{
6859 char *ptr = NULL;
6860 int i;
6861
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006862 memprintf(&ptr, "Built with OpenSSL version : "
6863#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006864 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006865#else /* OPENSSL_IS_BORINGSSL */
6866 OPENSSL_VERSION_TEXT
6867 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08006868 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02006869 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006870#endif
6871 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006872#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006873 "no (library version too old)"
6874#elif defined(OPENSSL_NO_TLSEXT)
6875 "no (disabled via OPENSSL_NO_TLSEXT)"
6876#else
6877 "yes"
6878#endif
6879 "", ptr);
6880
6881 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
6882#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
6883 "yes"
6884#else
6885#ifdef OPENSSL_NO_TLSEXT
6886 "no (because of OPENSSL_NO_TLSEXT)"
6887#else
6888 "no (version might be too old, 0.9.8f min needed)"
6889#endif
6890#endif
6891 "", ptr);
6892
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02006893 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
6894 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
6895 if (methodVersions[i].option)
6896 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006897
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006898 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01006899}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006900
Willy Tarreau80713382018-11-26 10:19:54 +01006901INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02006902
Emeric Brun46591952012-05-18 15:47:34 +02006903
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006904#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006905void ssl_free_engines(void) {
6906 struct ssl_engine_list *wl, *wlb;
6907 /* free up engine list */
6908 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
6909 ENGINE_finish(wl->e);
6910 ENGINE_free(wl->e);
6911 LIST_DEL(&wl->list);
6912 free(wl);
6913 }
6914}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006915#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02006916
Remi Gacogned3a23c32015-05-28 16:39:47 +02006917#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00006918void ssl_free_dh(void) {
6919 if (local_dh_1024) {
6920 DH_free(local_dh_1024);
6921 local_dh_1024 = NULL;
6922 }
6923 if (local_dh_2048) {
6924 DH_free(local_dh_2048);
6925 local_dh_2048 = NULL;
6926 }
6927 if (local_dh_4096) {
6928 DH_free(local_dh_4096);
6929 local_dh_4096 = NULL;
6930 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02006931 if (global_dh) {
6932 DH_free(global_dh);
6933 global_dh = NULL;
6934 }
Grant Zhang872f9c22017-01-21 01:10:18 +00006935}
6936#endif
6937
6938__attribute__((destructor))
6939static void __ssl_sock_deinit(void)
6940{
6941#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006942 if (ssl_ctx_lru_tree) {
6943 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01006944 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02006945 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02006946#endif
6947
Willy Tarreau5db847a2019-05-09 14:13:35 +02006948#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006949 ERR_remove_state(0);
6950 ERR_free_strings();
6951
6952 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08006953#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02006954
Willy Tarreau5db847a2019-05-09 14:13:35 +02006955#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006956 CRYPTO_cleanup_all_ex_data();
6957#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02006958 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02006959}
6960
Emeric Brun46591952012-05-18 15:47:34 +02006961/*
6962 * Local variables:
6963 * c-indent-level: 8
6964 * c-basic-offset: 8
6965 * End:
6966 */