blob: f142b0b5193a6afe3f445043c5794d57c5237813 [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
William Lallemanddad31052020-05-14 17:47:32 +0200303int ssl_store_load_locations_file(char *path)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200304{
305 if (ssl_store_get0_locations_file(path) == NULL) {
306 struct cafile_entry *ca_e;
307 X509_STORE *store = X509_STORE_new();
308 if (X509_STORE_load_locations(store, path, NULL)) {
309 int pathlen;
310 pathlen = strlen(path);
311 ca_e = calloc(1, sizeof(*ca_e) + pathlen + 1);
312 if (ca_e) {
313 memcpy(ca_e->path, path, pathlen + 1);
314 ca_e->ca_store = store;
315 ebst_insert(&cafile_tree, &ca_e->node);
316 return 1;
317 }
318 }
319 X509_STORE_free(store);
320 return 0;
321 }
322 return 1;
323}
324
325/* mimic what X509_STORE_load_locations do with store_ctx */
326static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
327{
328 X509_STORE *store;
329 store = ssl_store_get0_locations_file(path);
330 if (store_ctx && store) {
331 int i;
332 X509_OBJECT *obj;
333 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
334 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
335 obj = sk_X509_OBJECT_value(objs, i);
336 switch (X509_OBJECT_get_type(obj)) {
337 case X509_LU_X509:
338 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
339 break;
340 case X509_LU_CRL:
341 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
342 break;
343 default:
344 break;
345 }
346 }
347 return 1;
348 }
349 return 0;
350}
351
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500352/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200353static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
354{
355 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
356 return ssl_set_cert_crl_file(store_ctx, path);
357}
358
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200359/*
360 Extract CA_list from CA_file already in tree.
361 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
362 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
363*/
364static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
365{
366 struct ebmb_node *eb;
367 struct cafile_entry *ca_e;
368
369 eb = ebst_lookup(&cafile_tree, path);
370 if (!eb)
371 return NULL;
372 ca_e = ebmb_entry(eb, struct cafile_entry, node);
373
374 if (ca_e->ca_list == NULL) {
375 int i;
376 unsigned long key;
377 struct eb_root ca_name_tree = EB_ROOT;
378 struct eb64_node *node, *back;
379 struct {
380 struct eb64_node node;
381 X509_NAME *xname;
382 } *ca_name;
383 STACK_OF(X509_OBJECT) *objs;
384 STACK_OF(X509_NAME) *skn;
385 X509 *x;
386 X509_NAME *xn;
387
388 skn = sk_X509_NAME_new_null();
389 /* take x509 from cafile_tree */
390 objs = X509_STORE_get0_objects(ca_e->ca_store);
391 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
392 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
393 if (!x)
394 continue;
395 xn = X509_get_subject_name(x);
396 if (!xn)
397 continue;
398 /* Check for duplicates. */
399 key = X509_NAME_hash(xn);
400 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
401 node && ca_name == NULL;
402 node = eb64_next(node)) {
403 ca_name = container_of(node, typeof(*ca_name), node);
404 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
405 ca_name = NULL;
406 }
407 /* find a duplicate */
408 if (ca_name)
409 continue;
410 ca_name = calloc(1, sizeof *ca_name);
411 xn = X509_NAME_dup(xn);
412 if (!ca_name ||
413 !xn ||
414 !sk_X509_NAME_push(skn, xn)) {
415 free(ca_name);
416 X509_NAME_free(xn);
417 sk_X509_NAME_pop_free(skn, X509_NAME_free);
418 sk_X509_NAME_free(skn);
419 skn = NULL;
420 break;
421 }
422 ca_name->node.key = key;
423 ca_name->xname = xn;
424 eb64_insert(&ca_name_tree, &ca_name->node);
425 }
426 ca_e->ca_list = skn;
427 /* remove temporary ca_name tree */
428 node = eb64_first(&ca_name_tree);
429 while (node) {
430 ca_name = container_of(node, typeof(*ca_name), node);
431 back = eb64_next(node);
432 eb64_delete(node);
433 free(ca_name);
434 node = back;
435 }
436 }
437 return ca_e->ca_list;
438}
439
Willy Tarreaubafbe012017-11-24 17:34:44 +0100440struct pool_head *pool_head_ssl_capture = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200441int ssl_capture_ptr_index = -1;
Thierry FOURNIER28962c92018-06-17 21:37:05 +0200442static int ssl_app_data_index = -1;
Willy Tarreauef934602016-12-22 23:12:01 +0100443
Ilya Shipitsin04a5a442020-11-03 14:15:38 +0500444#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200445int ssl_keylog_index = -1;
446struct pool_head *pool_head_ssl_keylog = NULL;
447struct pool_head *pool_head_ssl_keylog_str = NULL;
448#endif
449
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200450#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
451struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
452#endif
453
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200454#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200455unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000456struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
457struct ssl_engine_list {
458 struct list list;
459 ENGINE *e;
460};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200461#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000462
Remi Gacogne8de54152014-07-15 11:36:40 +0200463#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200464static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200465static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200466static DH *local_dh_1024 = NULL;
467static DH *local_dh_2048 = NULL;
468static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100469static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200470#endif /* OPENSSL_NO_DH */
471
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100472#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200473/* X509V3 Extensions that will be added on generated certificates */
474#define X509V3_EXT_SIZE 5
475static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
476 "basicConstraints",
477 "nsComment",
478 "subjectKeyIdentifier",
479 "authorityKeyIdentifier",
480 "keyUsage",
481};
482static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
483 "CA:FALSE",
484 "\"OpenSSL Generated Certificate\"",
485 "hash",
486 "keyid,issuer:always",
487 "nonRepudiation,digitalSignature,keyEncipherment"
488};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200489/* LRU cache to store generated certificate */
490static struct lru64_head *ssl_ctx_lru_tree = NULL;
491static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200492static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100493__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200494
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200495#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
496
yanbzhube2774d2015-12-10 15:07:30 -0500497/* The order here matters for picking a default context,
498 * keep the most common keytype at the bottom of the list
499 */
500const char *SSL_SOCK_KEYTYPE_NAMES[] = {
501 "dsa",
502 "ecdsa",
503 "rsa"
504};
yanbzhube2774d2015-12-10 15:07:30 -0500505
William Lallemandc3cd35f2017-11-28 11:04:43 +0100506static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100507static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
508
Dragan Dosen9ac98092020-05-11 15:51:45 +0200509/* Dedicated callback functions for heartbeat and clienthello.
510 */
511#ifdef TLS1_RT_HEARTBEAT
512static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
513 int content_type, const void *buf, size_t len,
514 SSL *ssl);
515#endif
516static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
517 int content_type, const void *buf, size_t len,
518 SSL *ssl);
519
Ilya Shipitsin04a5a442020-11-03 14:15:38 +0500520#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200521static void ssl_init_keylog(struct connection *conn, int write_p, int version,
522 int content_type, const void *buf, size_t len,
523 SSL *ssl);
524#endif
525
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200526/* List head of all registered SSL/TLS protocol message callbacks. */
527struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
528
529/* Registers the function <func> in order to be called on SSL/TLS protocol
530 * message processing. It will return 0 if the function <func> is not set
531 * or if it fails to allocate memory.
532 */
533int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
534{
535 struct ssl_sock_msg_callback *cbk;
536
537 if (!func)
538 return 0;
539
540 cbk = calloc(1, sizeof(*cbk));
541 if (!cbk) {
542 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
543 return 0;
544 }
545
546 cbk->func = func;
547
548 LIST_ADDQ(&ssl_sock_msg_callbacks, &cbk->list);
549
550 return 1;
551}
552
Dragan Dosen9ac98092020-05-11 15:51:45 +0200553/* Used to register dedicated SSL/TLS protocol message callbacks.
554 */
555static int ssl_sock_register_msg_callbacks(void)
556{
557#ifdef TLS1_RT_HEARTBEAT
558 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
559 return ERR_ABORT;
560#endif
561 if (global_ssl.capture_cipherlist > 0) {
562 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
563 return ERR_ABORT;
564 }
Ilya Shipitsin04a5a442020-11-03 14:15:38 +0500565#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200566 if (global_ssl.keylog > 0) {
567 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
568 return ERR_ABORT;
569 }
570#endif
571
Dragan Dosen9ac98092020-05-11 15:51:45 +0200572 return 0;
573}
574
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200575/* Used to free all SSL/TLS protocol message callbacks that were
576 * registered by using ssl_sock_register_msg_callback().
577 */
578static void ssl_sock_unregister_msg_callbacks(void)
579{
580 struct ssl_sock_msg_callback *cbk, *cbkback;
581
582 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
583 LIST_DEL(&cbk->list);
584 free(cbk);
585 }
586}
587
Dragan Doseneb607fe2020-05-11 17:17:06 +0200588SSL *ssl_sock_get_ssl_object(struct connection *conn)
589{
590 if (!ssl_sock_is_ssl(conn))
591 return NULL;
592
593 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
594}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100595/*
596 * This function gives the detail of the SSL error. It is used only
597 * if the debug mode and the verbose mode are activated. It dump all
598 * the SSL error until the stack was empty.
599 */
600static forceinline void ssl_sock_dump_errors(struct connection *conn)
601{
602 unsigned long ret;
603
604 if (unlikely(global.mode & MODE_DEBUG)) {
605 while(1) {
606 ret = ERR_get_error();
607 if (ret == 0)
608 return;
609 fprintf(stderr, "fd[%04x] OpenSSL error[0x%lx] %s: %s\n",
Willy Tarreau585744b2017-08-24 14:31:19 +0200610 (unsigned short)conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100611 ERR_func_error_string(ret), ERR_reason_error_string(ret));
612 }
613 }
614}
615
yanbzhube2774d2015-12-10 15:07:30 -0500616
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200617#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200618int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000619{
620 int err_code = ERR_ABORT;
621 ENGINE *engine;
622 struct ssl_engine_list *el;
623
624 /* grab the structural reference to the engine */
625 engine = ENGINE_by_id(engine_id);
626 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100627 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000628 goto fail_get;
629 }
630
631 if (!ENGINE_init(engine)) {
632 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100633 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000634 goto fail_init;
635 }
636
637 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100638 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000639 goto fail_set_method;
640 }
641
642 el = calloc(1, sizeof(*el));
643 el->e = engine;
644 LIST_ADD(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100645 nb_engines++;
646 if (global_ssl.async)
647 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000648 return 0;
649
650fail_set_method:
651 /* release the functional reference from ENGINE_init() */
652 ENGINE_finish(engine);
653
654fail_init:
655 /* release the structural reference from ENGINE_by_id() */
656 ENGINE_free(engine);
657
658fail_get:
659 return err_code;
660}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200661#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000662
Willy Tarreau5db847a2019-05-09 14:13:35 +0200663#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +0200664/*
665 * openssl async fd handler
666 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200667void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000668{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200669 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000670
Emeric Brun3854e012017-05-17 20:42:48 +0200671 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000672 * to poll this fd until it is requested
673 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000674 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000675 fd_cant_recv(fd);
676
677 /* crypto engine is available, let's notify the associated
678 * connection that it can pursue its processing.
679 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200680 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000681}
682
Emeric Brun3854e012017-05-17 20:42:48 +0200683/*
684 * openssl async delayed SSL_free handler
685 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200686void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000687{
688 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200689 OSSL_ASYNC_FD all_fd[32];
690 size_t num_all_fds = 0;
691 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000692
Emeric Brun3854e012017-05-17 20:42:48 +0200693 /* We suppose that the async job for a same SSL *
694 * are serialized. So if we are awake it is
695 * because the running job has just finished
696 * and we can remove all async fds safely
697 */
698 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
699 if (num_all_fds > 32) {
700 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
701 return;
702 }
703
704 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
705 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200706 fd_stop_both(all_fd[i]);
Emeric Brun3854e012017-05-17 20:42:48 +0200707
708 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000709 SSL_free(ssl);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +0100710 _HA_ATOMIC_SUB(&sslconns, 1);
711 _HA_ATOMIC_SUB(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000712}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000713/*
Emeric Brun3854e012017-05-17 20:42:48 +0200714 * function used to manage a returned SSL_ERROR_WANT_ASYNC
715 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000716 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200717static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000718{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100719 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200720 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200721 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000722 size_t num_add_fds = 0;
723 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200724 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000725
726 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
727 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200728 if (num_add_fds > 32 || num_del_fds > 32) {
729 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 +0000730 return;
731 }
732
Emeric Brun3854e012017-05-17 20:42:48 +0200733 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000734
Emeric Brun3854e012017-05-17 20:42:48 +0200735 /* We remove unused fds from the fdtab */
736 for (i=0 ; i < num_del_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200737 fd_stop_both(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000738
Emeric Brun3854e012017-05-17 20:42:48 +0200739 /* We add new fds to the fdtab */
740 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200741 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000742 }
743
Emeric Brun3854e012017-05-17 20:42:48 +0200744 num_add_fds = 0;
745 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
746 if (num_add_fds > 32) {
747 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
748 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000749 }
Emeric Brun3854e012017-05-17 20:42:48 +0200750
751 /* We activate the polling for all known async fds */
752 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000753 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200754 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000755 /* To ensure that the fd cache won't be used
756 * We'll prefer to catch a real RD event
757 * because handling an EAGAIN on this fd will
758 * result in a context switch and also
759 * some engines uses a fd in blocking mode.
760 */
761 fd_cant_recv(add_fd[i]);
762 }
Emeric Brun3854e012017-05-17 20:42:48 +0200763
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000764}
765#endif
766
William Lallemand104a7a62019-10-14 14:14:59 +0200767#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200768/*
769 * This function returns the number of seconds elapsed
770 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
771 * date presented un ASN1_GENERALIZEDTIME.
772 *
773 * In parsing error case, it returns -1.
774 */
775static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
776{
777 long epoch;
778 char *p, *end;
779 const unsigned short month_offset[12] = {
780 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
781 };
782 int year, month;
783
784 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
785
786 p = (char *)d->data;
787 end = p + d->length;
788
789 if (end - p < 4) return -1;
790 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
791 p += 4;
792 if (end - p < 2) return -1;
793 month = 10 * (p[0] - '0') + p[1] - '0';
794 if (month < 1 || month > 12) return -1;
795 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
796 We consider leap years and the current month (<marsh or not) */
797 epoch = ( ((year - 1970) * 365)
798 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
799 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
800 + month_offset[month-1]
801 ) * 24 * 60 * 60;
802 p += 2;
803 if (end - p < 2) return -1;
804 /* Add the number of seconds of completed days of current month */
805 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
806 p += 2;
807 if (end - p < 2) return -1;
808 /* Add the completed hours of the current day */
809 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
810 p += 2;
811 if (end - p < 2) return -1;
812 /* Add the completed minutes of the current hour */
813 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
814 p += 2;
815 if (p == end) return -1;
816 /* Test if there is available seconds */
817 if (p[0] < '0' || p[0] > '9')
818 goto nosec;
819 if (end - p < 2) return -1;
820 /* Add the seconds of the current minute */
821 epoch += 10 * (p[0] - '0') + p[1] - '0';
822 p += 2;
823 if (p == end) return -1;
824 /* Ignore seconds float part if present */
825 if (p[0] == '.') {
826 do {
827 if (++p == end) return -1;
828 } while (p[0] >= '0' && p[0] <= '9');
829 }
830
831nosec:
832 if (p[0] == 'Z') {
833 if (end - p != 1) return -1;
834 return epoch;
835 }
836 else if (p[0] == '+') {
837 if (end - p != 5) return -1;
838 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700839 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 +0200840 }
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
847 return -1;
848}
849
William Lallemand104a7a62019-10-14 14:14:59 +0200850/*
851 * struct alignment works here such that the key.key is the same as key_data
852 * Do not change the placement of key_data
853 */
854struct certificate_ocsp {
855 struct ebmb_node key;
856 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
857 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200858 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200859 long expire;
860};
861
862struct ocsp_cbk_arg {
863 int is_single;
864 int single_kt;
865 union {
866 struct certificate_ocsp *s_ocsp;
867 /*
868 * m_ocsp will have multiple entries dependent on key type
869 * Entry 0 - DSA
870 * Entry 1 - ECDSA
871 * Entry 2 - RSA
872 */
873 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
874 };
875};
876
Emeric Brun1d3865b2014-06-20 15:37:32 +0200877static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200878
879/* This function starts to check if the OCSP response (in DER format) contained
880 * in chunk 'ocsp_response' is valid (else exits on error).
881 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
882 * contained in the OCSP Response and exits on error if no match.
883 * If it's a valid OCSP Response:
884 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
885 * pointed by 'ocsp'.
886 * If 'ocsp' is NULL, the function looks up into the OCSP response's
887 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
888 * from the response) and exits on error if not found. Finally, If an OCSP response is
889 * already present in the container, it will be overwritten.
890 *
891 * Note: OCSP response containing more than one OCSP Single response is not
892 * considered valid.
893 *
894 * Returns 0 on success, 1 in error case.
895 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200896static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
897 struct certificate_ocsp *ocsp,
898 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200899{
900 OCSP_RESPONSE *resp;
901 OCSP_BASICRESP *bs = NULL;
902 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200903 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200904 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200905 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200906 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200907 int reason;
908 int ret = 1;
909
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200910 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
911 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200912 if (!resp) {
913 memprintf(err, "Unable to parse OCSP response");
914 goto out;
915 }
916
917 rc = OCSP_response_status(resp);
918 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
919 memprintf(err, "OCSP response status not successful");
920 goto out;
921 }
922
923 bs = OCSP_response_get1_basic(resp);
924 if (!bs) {
925 memprintf(err, "Failed to get basic response from OCSP Response");
926 goto out;
927 }
928
929 count_sr = OCSP_resp_count(bs);
930 if (count_sr > 1) {
931 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
932 goto out;
933 }
934
935 sr = OCSP_resp_get0(bs, 0);
936 if (!sr) {
937 memprintf(err, "Failed to get OCSP single response");
938 goto out;
939 }
940
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200941 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
942
Emeric Brun4147b2e2014-06-16 18:36:30 +0200943 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200944 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200945 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200946 goto out;
947 }
948
Emeric Brun13a6b482014-06-20 15:44:34 +0200949 if (!nextupd) {
950 memprintf(err, "OCSP single response: missing nextupdate");
951 goto out;
952 }
953
Emeric Brunc8b27b62014-06-19 14:16:17 +0200954 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200955 if (!rc) {
956 memprintf(err, "OCSP single response: no longer valid.");
957 goto out;
958 }
959
960 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200961 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +0200962 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
963 goto out;
964 }
965 }
966
967 if (!ocsp) {
968 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
969 unsigned char *p;
970
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200971 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200972 if (!rc) {
973 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
974 goto out;
975 }
976
977 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
978 memprintf(err, "OCSP single response: Certificate ID too long");
979 goto out;
980 }
981
982 p = key;
983 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200984 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200985 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
986 if (!ocsp) {
987 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
988 goto out;
989 }
990 }
991
992 /* According to comments on "chunk_dup", the
993 previous chunk buffer will be freed */
994 if (!chunk_dup(&ocsp->response, ocsp_response)) {
995 memprintf(err, "OCSP response: Memory allocation error");
996 goto out;
997 }
998
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200999 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
1000
Emeric Brun4147b2e2014-06-16 18:36:30 +02001001 ret = 0;
1002out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001003 ERR_clear_error();
1004
Emeric Brun4147b2e2014-06-16 18:36:30 +02001005 if (bs)
1006 OCSP_BASICRESP_free(bs);
1007
1008 if (resp)
1009 OCSP_RESPONSE_free(resp);
1010
1011 return ret;
1012}
1013/*
1014 * External function use to update the OCSP response in the OCSP response's
1015 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1016 * to update in DER format.
1017 *
1018 * Returns 0 on success, 1 in error case.
1019 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001020int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001021{
1022 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1023}
1024
William Lallemand4a660132019-10-14 14:51:41 +02001025#endif
1026
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001027#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1028static 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)
1029{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001030 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001031 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001032 struct connection *conn;
1033 int head;
1034 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001035 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001036
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001037 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001038 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001039 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1040
1041 keys = ref->tlskeys;
1042 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001043
1044 if (enc) {
1045 memcpy(key_name, keys[head].name, 16);
1046
1047 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001048 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001049
Emeric Brun9e754772019-01-10 17:51:55 +01001050 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001051
Emeric Brun9e754772019-01-10 17:51:55 +01001052 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1053 goto end;
1054
Willy Tarreau9356dac2019-05-10 09:22:53 +02001055 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001056 ret = 1;
1057 }
1058 else if (ref->key_size_bits == 256 ) {
1059
1060 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1061 goto end;
1062
Willy Tarreau9356dac2019-05-10 09:22:53 +02001063 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001064 ret = 1;
1065 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001066 } else {
1067 for (i = 0; i < TLS_TICKETS_NO; i++) {
1068 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1069 goto found;
1070 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001071 ret = 0;
1072 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001073
Christopher Faulet16f45c82018-02-16 11:23:49 +01001074 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001075 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001076 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 +01001077 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1078 goto end;
1079 /* 2 for key renewal, 1 if current key is still valid */
1080 ret = i ? 2 : 1;
1081 }
1082 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001083 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 +01001084 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1085 goto end;
1086 /* 2 for key renewal, 1 if current key is still valid */
1087 ret = i ? 2 : 1;
1088 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001089 }
Emeric Brun9e754772019-01-10 17:51:55 +01001090
Christopher Faulet16f45c82018-02-16 11:23:49 +01001091 end:
1092 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1093 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001094}
1095
1096struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1097{
1098 struct tls_keys_ref *ref;
1099
1100 list_for_each_entry(ref, &tlskeys_reference, list)
1101 if (ref->filename && strcmp(filename, ref->filename) == 0)
1102 return ref;
1103 return NULL;
1104}
1105
1106struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1107{
1108 struct tls_keys_ref *ref;
1109
1110 list_for_each_entry(ref, &tlskeys_reference, list)
1111 if (ref->unique_id == unique_id)
1112 return ref;
1113 return NULL;
1114}
1115
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001116/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001117 * match existing ones, this function returns -1
1118 * else it returns 0 on success.
1119 */
1120int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001121 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001122{
Emeric Brun9e754772019-01-10 17:51:55 +01001123 if (ref->key_size_bits == 128) {
1124 if (tlskey->data != sizeof(struct tls_sess_key_128))
1125 return -1;
1126 }
1127 else if (ref->key_size_bits == 256) {
1128 if (tlskey->data != sizeof(struct tls_sess_key_256))
1129 return -1;
1130 }
1131 else
1132 return -1;
1133
Christopher Faulet16f45c82018-02-16 11:23:49 +01001134 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001135 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1136 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001137 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1138 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001139
1140 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001141}
1142
Willy Tarreau83061a82018-07-13 11:56:34 +02001143int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001144{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001145 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1146
1147 if(!ref) {
1148 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1149 return 1;
1150 }
Emeric Brun9e754772019-01-10 17:51:55 +01001151 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1152 memprintf(err, "Invalid key size");
1153 return 1;
1154 }
1155
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001156 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001157}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001158
1159/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001160 * automatic ids. It's called just after the basic checks. It returns
1161 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001162 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001163static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001164{
1165 int i = 0;
1166 struct tls_keys_ref *ref, *ref2, *ref3;
1167 struct list tkr = LIST_HEAD_INIT(tkr);
1168
1169 list_for_each_entry(ref, &tlskeys_reference, list) {
1170 if (ref->unique_id == -1) {
1171 /* Look for the first free id. */
1172 while (1) {
1173 list_for_each_entry(ref2, &tlskeys_reference, list) {
1174 if (ref2->unique_id == i) {
1175 i++;
1176 break;
1177 }
1178 }
1179 if (&ref2->list == &tlskeys_reference)
1180 break;
1181 }
1182
1183 /* Uses the unique id and increment it for the next entry. */
1184 ref->unique_id = i;
1185 i++;
1186 }
1187 }
1188
1189 /* This sort the reference list by id. */
1190 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
1191 LIST_DEL(&ref->list);
1192 list_for_each_entry(ref3, &tkr, list) {
1193 if (ref->unique_id < ref3->unique_id) {
1194 LIST_ADDQ(&ref3->list, &ref->list);
1195 break;
1196 }
1197 }
1198 if (&ref3->list == &tkr)
1199 LIST_ADDQ(&tkr, &ref->list);
1200 }
1201
1202 /* swap root */
1203 LIST_ADD(&tkr, &tlskeys_reference);
1204 LIST_DEL(&tkr);
Willy Tarreaud1c57502016-12-22 22:46:15 +01001205 return 0;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001206}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001207#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1208
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001209#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001210int ocsp_ex_index = -1;
1211
yanbzhube2774d2015-12-10 15:07:30 -05001212int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1213{
1214 switch (evp_keytype) {
1215 case EVP_PKEY_RSA:
1216 return 2;
1217 case EVP_PKEY_DSA:
1218 return 0;
1219 case EVP_PKEY_EC:
1220 return 1;
1221 }
1222
1223 return -1;
1224}
1225
Emeric Brun4147b2e2014-06-16 18:36:30 +02001226/*
1227 * Callback used to set OCSP status extension content in server hello.
1228 */
1229int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1230{
yanbzhube2774d2015-12-10 15:07:30 -05001231 struct certificate_ocsp *ocsp;
1232 struct ocsp_cbk_arg *ocsp_arg;
1233 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001234 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001235 EVP_PKEY *ssl_pkey;
1236 int key_type;
1237 int index;
1238
William Lallemand76b4a122020-08-04 17:41:39 +02001239 ctx = SSL_get_SSL_CTX(ssl);
1240 if (!ctx)
1241 return SSL_TLSEXT_ERR_NOACK;
1242
1243 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1244 if (!ocsp_arg)
1245 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001246
1247 ssl_pkey = SSL_get_privatekey(ssl);
1248 if (!ssl_pkey)
1249 return SSL_TLSEXT_ERR_NOACK;
1250
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001251 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001252
1253 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1254 ocsp = ocsp_arg->s_ocsp;
1255 else {
1256 /* For multiple certs per context, we have to find the correct OCSP response based on
1257 * the certificate type
1258 */
1259 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1260
1261 if (index < 0)
1262 return SSL_TLSEXT_ERR_NOACK;
1263
1264 ocsp = ocsp_arg->m_ocsp[index];
1265
1266 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001267
1268 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001269 !ocsp->response.area ||
1270 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001271 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001272 return SSL_TLSEXT_ERR_NOACK;
1273
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001274 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001275 if (!ssl_buf)
1276 return SSL_TLSEXT_ERR_NOACK;
1277
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001278 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1279 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001280
1281 return SSL_TLSEXT_ERR_OK;
1282}
1283
William Lallemand4a660132019-10-14 14:51:41 +02001284#endif
1285
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001286#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001287
1288
1289/*
1290 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1291 * used anymore. Also removes it from the tree if free'd.
1292 */
1293static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1294{
1295 if (!ocsp)
1296 return;
1297
1298 ocsp->refcount--;
1299 if (ocsp->refcount <= 0) {
1300 ebmb_delete(&ocsp->key);
1301 chunk_destroy(&ocsp->response);
1302 free(ocsp);
1303 }
1304}
1305
1306
Emeric Brun4147b2e2014-06-16 18:36:30 +02001307/*
1308 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001309 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1310 * status extension, the issuer's certificate is mandatory. It should be
1311 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001312 *
William Lallemand246c0242019-10-11 08:59:13 +02001313 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1314 * OCSP response. If file is empty or content is not a valid OCSP response,
1315 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1316 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001317 *
1318 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001319 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001320 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001321static 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 +02001322{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001323 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001324 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001325 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001326 struct certificate_ocsp *ocsp = NULL, *iocsp;
1327 char *warn = NULL;
1328 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001329 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001330
Emeric Brun4147b2e2014-06-16 18:36:30 +02001331
William Lallemand246c0242019-10-11 08:59:13 +02001332 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001333 if (!x)
1334 goto out;
1335
William Lallemand246c0242019-10-11 08:59:13 +02001336 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001337 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1338 if (chain) {
1339 /* check if one of the certificate of the chain is the issuer */
1340 for (i = 0; i < sk_X509_num(chain); i++) {
1341 X509 *ti = sk_X509_value(chain, i);
1342 if (X509_check_issued(ti, x) == X509_V_OK) {
1343 issuer = ti;
1344 break;
1345 }
1346 }
1347 }
William Lallemand246c0242019-10-11 08:59:13 +02001348 if (!issuer)
1349 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001350
1351 cid = OCSP_cert_to_id(0, x, issuer);
1352 if (!cid)
1353 goto out;
1354
1355 i = i2d_OCSP_CERTID(cid, NULL);
1356 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1357 goto out;
1358
Vincent Bernat02779b62016-04-03 13:48:43 +02001359 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001360 if (!ocsp)
1361 goto out;
1362
1363 p = ocsp->key_data;
1364 i2d_OCSP_CERTID(cid, &p);
1365
1366 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1367 if (iocsp == ocsp)
1368 ocsp = NULL;
1369
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001370#ifndef SSL_CTX_get_tlsext_status_cb
1371# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1372 *cb = (void (*) (void))ctx->tlsext_status_cb;
1373#endif
1374 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1375
1376 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001377 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001378 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001379
William Lallemanda560c062020-07-31 11:43:20 +02001380 cb_arg = calloc(1, sizeof(*cb_arg));
1381 if (!cb_arg)
1382 goto out;
1383
yanbzhube2774d2015-12-10 15:07:30 -05001384 cb_arg->is_single = 1;
1385 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001386 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001387
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001388 pkey = X509_get_pubkey(x);
1389 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1390 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001391
1392 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001393 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 */
1394
yanbzhube2774d2015-12-10 15:07:30 -05001395 } else {
1396 /*
1397 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1398 * Update that cb_arg with the new cert's staple
1399 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001400 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001401 struct certificate_ocsp *tmp_ocsp;
1402 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001403 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001404 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001405
William Lallemand76b4a122020-08-04 17:41:39 +02001406 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001407
1408 /*
1409 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1410 * the order of operations below matter, take care when changing it
1411 */
1412 tmp_ocsp = cb_arg->s_ocsp;
1413 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1414 cb_arg->s_ocsp = NULL;
1415 cb_arg->m_ocsp[index] = tmp_ocsp;
1416 cb_arg->is_single = 0;
1417 cb_arg->single_kt = 0;
1418
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001419 pkey = X509_get_pubkey(x);
1420 key_type = EVP_PKEY_base_id(pkey);
1421 EVP_PKEY_free(pkey);
1422
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001423 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001424 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001425 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001426 iocsp->refcount++;
1427 }
yanbzhube2774d2015-12-10 15:07:30 -05001428 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001429
1430 ret = 0;
1431
1432 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001433 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001434 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001435 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001436 }
1437
1438out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001439 if (cid)
1440 OCSP_CERTID_free(cid);
1441
1442 if (ocsp)
1443 free(ocsp);
1444
1445 if (warn)
1446 free(warn);
1447
Emeric Brun4147b2e2014-06-16 18:36:30 +02001448 return ret;
1449}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001450#endif
1451
1452#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001453static 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 +02001454{
William Lallemand4a660132019-10-14 14:51:41 +02001455 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 +02001456}
1457#endif
1458
William Lallemand4a660132019-10-14 14:51:41 +02001459
Ilya Shipitsine4f38f92021-02-06 18:55:27 +05001460#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001461
1462#define CT_EXTENSION_TYPE 18
1463
William Lallemand03c331c2020-05-13 10:10:01 +02001464int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001465
1466int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1467{
Willy Tarreau83061a82018-07-13 11:56:34 +02001468 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001469
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001470 *out = (unsigned char *) sctl->area;
1471 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001472
1473 return 1;
1474}
1475
1476int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1477{
1478 return 1;
1479}
1480
William Lallemanda17f4112019-10-10 15:16:44 +02001481static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001482{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001483 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001484
William Lallemanda17f4112019-10-10 15:16:44 +02001485 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 +01001486 goto out;
1487
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001488 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1489
1490 ret = 0;
1491
1492out:
1493 return ret;
1494}
1495
1496#endif
1497
Emeric Brune1f38db2012-09-03 20:36:47 +02001498void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1499{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001500 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001501 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001502 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001503 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001504
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001505#ifndef SSL_OP_NO_RENEGOTIATION
1506 /* Please note that BoringSSL defines this macro to zero so don't
1507 * change this to #if and do not assign a default value to this macro!
1508 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001509 if (where & SSL_CB_HANDSHAKE_START) {
1510 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001511 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 +02001512 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001513 conn->err_code = CO_ER_SSL_RENEG;
1514 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001515 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001516#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001517
1518 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001519 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001520 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001521 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001522 consider that the buffering was activated,
1523 so we rise the output buffer size from 4k
1524 to 16k */
1525 write_bio = SSL_get_wbio(ssl);
1526 if (write_bio != SSL_get_rbio(ssl)) {
1527 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001528 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001529 }
1530 }
1531 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001532}
1533
Emeric Brune64aef12012-09-21 13:15:06 +02001534/* Callback is called for each certificate of the chain during a verify
1535 ok is set to 1 if preverify detect no error on current certificate.
1536 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001537int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001538{
1539 SSL *ssl;
1540 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001541 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001542 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001543
1544 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001545 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001546
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001547 ctx = conn->xprt_ctx;
1548
1549 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001550
Emeric Brun81c00f02012-09-21 14:31:21 +02001551 if (ok) /* no errors */
1552 return ok;
1553
1554 depth = X509_STORE_CTX_get_error_depth(x_store);
1555 err = X509_STORE_CTX_get_error(x_store);
1556
1557 /* check if CA error needs to be ignored */
1558 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001559 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1560 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1561 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001562 }
1563
Willy Tarreau731248f2020-02-04 14:02:02 +01001564 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001565 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001566 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001567 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001568 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001569
Willy Tarreau20879a02012-12-03 16:32:10 +01001570 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001571 return 0;
1572 }
1573
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001574 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1575 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001576
Emeric Brun81c00f02012-09-21 14:31:21 +02001577 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001578 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001579 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001580 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001581 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001582 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001583
Willy Tarreau20879a02012-12-03 16:32:10 +01001584 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001585 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001586}
1587
Dragan Dosen9ac98092020-05-11 15:51:45 +02001588#ifdef TLS1_RT_HEARTBEAT
1589static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1590 int content_type, const void *buf, size_t len,
1591 SSL *ssl)
1592{
1593 /* test heartbeat received (write_p is set to 0
1594 for a received record) */
1595 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1596 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1597 const unsigned char *p = buf;
1598 unsigned int payload;
1599
1600 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1601
1602 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1603 if (*p != TLS1_HB_REQUEST)
1604 return;
1605
1606 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1607 goto kill_it;
1608
1609 payload = (p[1] * 256) + p[2];
1610 if (3 + payload + 16 <= len)
1611 return; /* OK no problem */
1612 kill_it:
1613 /* We have a clear heartbleed attack (CVE-2014-0160), the
1614 * advertised payload is larger than the advertised packet
1615 * length, so we have garbage in the buffer between the
1616 * payload and the end of the buffer (p+len). We can't know
1617 * if the SSL stack is patched, and we don't know if we can
1618 * safely wipe out the area between p+3+len and payload.
1619 * So instead, we prevent the response from being sent by
1620 * setting the max_send_fragment to 0 and we report an SSL
1621 * error, which will kill this connection. It will be reported
1622 * above as SSL_ERROR_SSL while an other handshake failure with
1623 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1624 */
1625 ssl->max_send_fragment = 0;
1626 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1627 }
1628}
1629#endif
1630
1631static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1632 int content_type, const void *buf, size_t len,
1633 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001634{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001635 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001636 unsigned char *msg;
1637 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001638 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001639
1640 /* This function is called for "from client" and "to server"
1641 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001642 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001643 */
1644
1645 /* "write_p" is set to 0 is the bytes are received messages,
1646 * otherwise it is set to 1.
1647 */
1648 if (write_p != 0)
1649 return;
1650
1651 /* content_type contains the type of message received or sent
1652 * according with the SSL/TLS protocol spec. This message is
1653 * encoded with one byte. The value 256 (two bytes) is used
1654 * for designing the SSL/TLS record layer. According with the
1655 * rfc6101, the expected message (other than 256) are:
1656 * - change_cipher_spec(20)
1657 * - alert(21)
1658 * - handshake(22)
1659 * - application_data(23)
1660 * - (255)
1661 * We are interessed by the handshake and specially the client
1662 * hello.
1663 */
1664 if (content_type != 22)
1665 return;
1666
1667 /* The message length is at least 4 bytes, containing the
1668 * message type and the message length.
1669 */
1670 if (len < 4)
1671 return;
1672
1673 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001674 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001675 * - hello_request(0)
1676 * - client_hello(1)
1677 * - server_hello(2)
1678 * - certificate(11)
1679 * - server_key_exchange (12)
1680 * - certificate_request(13)
1681 * - server_hello_done(14)
1682 * We are interested by the client hello.
1683 */
1684 msg = (unsigned char *)buf;
1685 if (msg[0] != 1)
1686 return;
1687
1688 /* Next three bytes are the length of the message. The total length
1689 * must be this decoded length + 4. If the length given as argument
1690 * is not the same, we abort the protocol dissector.
1691 */
1692 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1693 if (len < rec_len + 4)
1694 return;
1695 msg += 4;
1696 end = msg + rec_len;
1697 if (end < msg)
1698 return;
1699
1700 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1701 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001702 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1703 */
1704 msg += 1 + 1 + 4 + 28;
1705 if (msg > end)
1706 return;
1707
1708 /* Next, is session id:
1709 * if present, we have to jump by length + 1 for the size information
1710 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001711 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001712 if (msg[0] > 0)
1713 msg += msg[0];
1714 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001715 if (msg > end)
1716 return;
1717
1718 /* Next two bytes are the ciphersuite length. */
1719 if (msg + 2 > end)
1720 return;
1721 rec_len = (msg[0] << 8) + msg[1];
1722 msg += 2;
1723 if (msg + rec_len > end || msg + rec_len < msg)
1724 return;
1725
Willy Tarreaubafbe012017-11-24 17:34:44 +01001726 capture = pool_alloc_dirty(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001727 if (!capture)
1728 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001729 /* Compute the xxh64 of the ciphersuite. */
1730 capture->xxh64 = XXH64(msg, rec_len, 0);
1731
1732 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001733 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1734 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001735 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001736
1737 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001738}
William Lallemand7d42ef52020-07-06 11:41:30 +02001739
1740
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05001741#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001742static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1743 int content_type, const void *buf, size_t len,
1744 SSL *ssl)
1745{
1746 struct ssl_keylog *keylog;
1747
1748 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1749 return;
1750
1751 keylog = pool_alloc(pool_head_ssl_keylog);
1752 if (!keylog)
1753 return;
1754
1755 memset(keylog, 0, sizeof(*keylog));
1756
1757 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1758 pool_free(pool_head_ssl_keylog, keylog);
1759 return;
1760 }
1761}
1762#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001763
Emeric Brun29f037d2014-04-25 19:05:36 +02001764/* Callback is called for ssl protocol analyse */
1765void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1766{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001767 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1768 struct ssl_sock_msg_callback *cbk;
1769
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001770 /* Try to call all callback functions that were registered by using
1771 * ssl_sock_register_msg_callback().
1772 */
1773 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1774 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1775 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001776}
1777
Bernard Spil13c53f82018-02-15 13:34:58 +01001778#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001779static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1780 const unsigned char *in, unsigned int inlen,
1781 void *arg)
1782{
1783 struct server *srv = arg;
1784
1785 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1786 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1787 return SSL_TLSEXT_ERR_OK;
1788 return SSL_TLSEXT_ERR_NOACK;
1789}
1790#endif
1791
1792#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001793/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001794 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001795 */
1796static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1797 unsigned int *len, void *arg)
1798{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001799 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001800
1801 *data = (const unsigned char *)conf->npn_str;
1802 *len = conf->npn_len;
1803 return SSL_TLSEXT_ERR_OK;
1804}
1805#endif
1806
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001807#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001808/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001809 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001810 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001811static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1812 unsigned char *outlen,
1813 const unsigned char *server,
1814 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001815{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001816 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001817
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001818 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1819 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1820 return SSL_TLSEXT_ERR_NOACK;
1821 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001822 return SSL_TLSEXT_ERR_OK;
1823}
1824#endif
1825
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001826#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001827#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001828
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001829/* Configure a DNS SAN extenion on a certificate. */
1830int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1831 int failure = 0;
1832 X509_EXTENSION *san_ext = NULL;
1833 CONF *conf = NULL;
1834 struct buffer *san_name = get_trash_chunk();
1835
1836 conf = NCONF_new(NULL);
1837 if (!conf) {
1838 failure = 1;
1839 goto cleanup;
1840 }
1841
1842 /* Build an extension based on the DNS entry above */
1843 chunk_appendf(san_name, "DNS:%s", servername);
1844 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1845 if (!san_ext) {
1846 failure = 1;
1847 goto cleanup;
1848 }
1849
1850 /* Add the extension */
1851 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1852 failure = 1;
1853 goto cleanup;
1854 }
1855
1856 /* Success */
1857 failure = 0;
1858
1859cleanup:
1860 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1861 if (NULL != conf) NCONF_free(conf);
1862
1863 return failure;
1864}
1865
Christopher Faulet30548802015-06-11 13:39:32 +02001866/* Create a X509 certificate with the specified servername and serial. This
1867 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001868static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001869ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001870{
Shimi Gersner5846c492020-08-23 13:58:12 +03001871 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1872 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001873 SSL_CTX *ssl_ctx = NULL;
1874 X509 *newcrt = NULL;
1875 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001876 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001877 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001878 X509_NAME *name;
1879 const EVP_MD *digest;
1880 X509V3_CTX ctx;
1881 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001882 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001883
Christopher Faulet48a83322017-07-28 16:56:09 +02001884 /* Get the private key of the default certificate and use it */
Ilya Shipitsin842976d2020-12-19 03:12:12 +05001885#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001886 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1887#else
1888 tmp_ssl = SSL_new(bind_conf->default_ctx);
1889 if (tmp_ssl)
1890 pkey = SSL_get_privatekey(tmp_ssl);
1891#endif
1892 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001893 goto mkcert_error;
1894
1895 /* Create the certificate */
1896 if (!(newcrt = X509_new()))
1897 goto mkcert_error;
1898
1899 /* Set version number for the certificate (X509v3) and the serial
1900 * number */
1901 if (X509_set_version(newcrt, 2L) != 1)
1902 goto mkcert_error;
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01001903 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001904
1905 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001906 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1907 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001908 goto mkcert_error;
1909
1910 /* set public key in the certificate */
1911 if (X509_set_pubkey(newcrt, pkey) != 1)
1912 goto mkcert_error;
1913
1914 /* Set issuer name from the CA */
1915 if (!(name = X509_get_subject_name(cacert)))
1916 goto mkcert_error;
1917 if (X509_set_issuer_name(newcrt, name) != 1)
1918 goto mkcert_error;
1919
1920 /* Set the subject name using the same, but the CN */
1921 name = X509_NAME_dup(name);
1922 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1923 (const unsigned char *)servername,
1924 -1, -1, 0) != 1) {
1925 X509_NAME_free(name);
1926 goto mkcert_error;
1927 }
1928 if (X509_set_subject_name(newcrt, name) != 1) {
1929 X509_NAME_free(name);
1930 goto mkcert_error;
1931 }
1932 X509_NAME_free(name);
1933
1934 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001935 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001936 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1937 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1938 X509_EXTENSION *ext;
1939
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001940 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001941 goto mkcert_error;
1942 if (!X509_add_ext(newcrt, ext, -1)) {
1943 X509_EXTENSION_free(ext);
1944 goto mkcert_error;
1945 }
1946 X509_EXTENSION_free(ext);
1947 }
1948
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001949 /* Add SAN extension */
1950 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
1951 goto mkcert_error;
1952 }
1953
Christopher Faulet31af49d2015-06-09 17:29:50 +02001954 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001955
1956 key_type = EVP_PKEY_base_id(capkey);
1957
1958 if (key_type == EVP_PKEY_DSA)
1959 digest = EVP_sha1();
1960 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001961 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001962 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001963 digest = EVP_sha256();
1964 else {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02001965#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000000fL) && !defined(OPENSSL_IS_BORINGSSL)
Christopher Faulet7969a332015-10-09 11:15:03 +02001966 int nid;
1967
1968 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1969 goto mkcert_error;
1970 if (!(digest = EVP_get_digestbynid(nid)))
1971 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02001972#else
1973 goto mkcert_error;
1974#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02001975 }
1976
Christopher Faulet31af49d2015-06-09 17:29:50 +02001977 if (!(X509_sign(newcrt, capkey, digest)))
1978 goto mkcert_error;
1979
1980 /* Create and set the new SSL_CTX */
1981 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
1982 goto mkcert_error;
1983 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1984 goto mkcert_error;
1985 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
1986 goto mkcert_error;
1987 if (!SSL_CTX_check_private_key(ssl_ctx))
1988 goto mkcert_error;
1989
Shimi Gersner5846c492020-08-23 13:58:12 +03001990 /* Build chaining the CA cert and the rest of the chain, keep these order */
1991#if defined(SSL_CTX_add1_chain_cert)
1992 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
1993 goto mkcert_error;
1994 }
1995
1996 if (bind_conf->ca_sign_ckch->chain) {
1997 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
1998 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
1999 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2000 goto mkcert_error;
2001 }
2002 }
2003 }
2004#endif
2005
Christopher Faulet31af49d2015-06-09 17:29:50 +02002006 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002007
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002008#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002009 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002010#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002011#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2012 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002013 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002014 EC_KEY *ecc;
2015 int nid;
2016
2017 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2018 goto end;
2019 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2020 goto end;
2021 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2022 EC_KEY_free(ecc);
2023 }
2024#endif
2025 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002026 return ssl_ctx;
2027
2028 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002029 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002030 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002031 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2032 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002033 return NULL;
2034}
2035
Christopher Faulet7969a332015-10-09 11:15:03 +02002036SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002037ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02002038{
Willy Tarreau07d94e42018-09-20 10:57:52 +02002039 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01002040 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002041
Olivier Houchard66ab4982019-02-26 18:37:15 +01002042 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02002043}
2044
Christopher Faulet30548802015-06-11 13:39:32 +02002045/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002046 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002047SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002048ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002049{
2050 struct lru64 *lru = NULL;
2051
2052 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002053 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002054 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002055 if (lru && lru->domain) {
2056 if (ssl)
2057 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002058 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002059 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002060 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002061 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002062 }
2063 return NULL;
2064}
2065
Emeric Brun821bb9b2017-06-15 16:37:39 +02002066/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2067 * function is not thread-safe, it should only be used to check if a certificate
2068 * exists in the lru cache (with no warranty it will not be removed by another
2069 * thread). It is kept for backward compatibility. */
2070SSL_CTX *
2071ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2072{
2073 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2074}
2075
Christopher Fauletd2cab922015-07-28 16:03:47 +02002076/* Set a certificate int the LRU cache used to store generated
2077 * certificate. Return 0 on success, otherwise -1 */
2078int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002079ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002080{
2081 struct lru64 *lru = NULL;
2082
2083 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002084 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002085 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002086 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002087 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002088 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002089 }
Christopher Faulet30548802015-06-11 13:39:32 +02002090 if (lru->domain && lru->data)
2091 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002092 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002093 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002094 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002095 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002096 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002097}
2098
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002099/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002100unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002101ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002102{
2103 return XXH32(data, len, ssl_ctx_lru_seed);
2104}
2105
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002106/* Generate a cert and immediately assign it to the SSL session so that the cert's
2107 * refcount is maintained regardless of the cert's presence in the LRU cache.
2108 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002109static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002110ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002111{
Shimi Gersner5846c492020-08-23 13:58:12 +03002112 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002113 SSL_CTX *ssl_ctx = NULL;
2114 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002115 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002116
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002117 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002118 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002119 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002120 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002121 if (lru && lru->domain)
2122 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002123 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002124 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002125 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002126 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002127 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002128 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002129 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002130 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002131 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002132 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002133 SSL_set_SSL_CTX(ssl, ssl_ctx);
2134 /* No LRU cache, this CTX will be released as soon as the session dies */
2135 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002136 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002137 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002138 return 0;
2139}
2140static int
2141ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2142{
2143 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002144 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002145
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002146 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002147 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002148 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002149 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002150 }
2151 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002152}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002153#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002154
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002155#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002156
2157static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002158{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002159#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002160 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002161 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2162#endif
2163}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002164static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2165 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002166 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2167}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002168static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002169#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002170 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002171 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2172#endif
2173}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002174static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002175#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002176 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002177 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2178#endif
2179}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002180/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002181static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2182/* Unusable in this context. */
2183static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2184static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2185static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2186static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2187static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002188#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002189
2190static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2191 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002192 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2193}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002194static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2195 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2196 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2197}
2198static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2199 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002200 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2201}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002202static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2203 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2204 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2205}
2206static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2207 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002208 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2209}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002210static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2211 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2212 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2213}
2214static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2215 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002216 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2217}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002218static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2219 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2220 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2221}
2222static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002223#if SSL_OP_NO_TLSv1_3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002224 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002225 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2226#endif
2227}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002228static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
2229#if SSL_OP_NO_TLSv1_3
2230 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2231 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002232#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002233}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002234#endif
2235static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2236static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002237
William Lallemand7fd8b452020-05-07 15:20:43 +02002238struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002239 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2240 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2241 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2242 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2243 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2244 {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 +02002245};
2246
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002247static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2248{
2249 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2250 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2251 SSL_set_SSL_CTX(ssl, ctx);
2252}
2253
Willy Tarreau5db847a2019-05-09 14:13:35 +02002254#if ((HA_OPENSSL_VERSION_NUMBER >= 0x10101000L) || defined(OPENSSL_IS_BORINGSSL))
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002255
2256static int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
2257{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002258 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002259 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002260
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002261 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2262 return SSL_TLSEXT_ERR_OK;
2263 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002264}
2265
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002266#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002267static int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
2268{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002269 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002270#else
2271static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
2272{
2273#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002274 struct connection *conn;
2275 struct bind_conf *s;
2276 const uint8_t *extension_data;
2277 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002278 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002279
2280 char *wildp = NULL;
2281 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002282 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002283 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002284 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002285 int i;
2286
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002287 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002288 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002289
Olivier Houchard9679ac92017-10-27 14:58:08 +02002290 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002291 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002292#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002293 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2294 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002295#else
2296 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2297#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002298 /*
2299 * The server_name extension was given too much extensibility when it
2300 * was written, so parsing the normal case is a bit complex.
2301 */
2302 size_t len;
2303 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002304 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002305 /* Extract the length of the supplied list of names. */
2306 len = (*extension_data++) << 8;
2307 len |= *extension_data++;
2308 if (len + 2 != extension_len)
2309 goto abort;
2310 /*
2311 * The list in practice only has a single element, so we only consider
2312 * the first one.
2313 */
2314 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2315 goto abort;
2316 extension_len = len - 1;
2317 /* Now we can finally pull out the byte array with the actual hostname. */
2318 if (extension_len <= 2)
2319 goto abort;
2320 len = (*extension_data++) << 8;
2321 len |= *extension_data++;
2322 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2323 || memchr(extension_data, 0, len) != NULL)
2324 goto abort;
2325 servername = extension_data;
2326 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002327 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002328#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2329 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002330 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002331 }
2332#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002333 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002334 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002335 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002336 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002337 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002338 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002339 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002340 goto abort;
2341 }
2342
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002343 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002344#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002345 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002346#else
2347 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2348#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002349 uint8_t sign;
2350 size_t len;
2351 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002352 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002353 len = (*extension_data++) << 8;
2354 len |= *extension_data++;
2355 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002356 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002357 if (len % 2 != 0)
2358 goto abort;
2359 for (; len > 0; len -= 2) {
2360 extension_data++; /* hash */
2361 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002362 switch (sign) {
2363 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002364 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002365 break;
2366 case TLSEXT_signature_ecdsa:
2367 has_ecdsa_sig = 1;
2368 break;
2369 default:
2370 continue;
2371 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002372 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002373 break;
2374 }
2375 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002376 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002377 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002378 }
2379 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002380 const SSL_CIPHER *cipher;
2381 size_t len;
2382 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002383 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002384#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002385 len = ctx->cipher_suites_len;
2386 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002387#else
2388 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2389#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002390 if (len % 2 != 0)
2391 goto abort;
2392 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002393#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002394 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002395 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002396#else
2397 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2398#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002399 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002400 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002401 break;
2402 }
2403 }
2404 }
2405
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002406 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002407 trash.area[i] = tolower(servername[i]);
2408 if (!wildp && (trash.area[i] == '.'))
2409 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002410 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002411 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002412
William Lallemand150bfa82019-09-19 17:12:49 +02002413 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002414
William Lallemand94bd3192020-08-14 14:43:35 +02002415 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2416 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002417 for (i = 0; i < 2; i++) {
2418 if (i == 0) /* lookup in full qualified names */
2419 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002420 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002421 node = ebst_lookup(&s->sni_w_ctx, wildp);
2422 else
2423 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002424
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002425 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002426
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002427 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002428 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002429 struct sni_ctx *sni, *sni_tmp;
2430 int skip = 0;
2431
2432 if (i == 1 && wildp) { /* wildcard */
2433 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2434 sni = container_of(n, struct sni_ctx, name);
2435 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
2436 if (sni_tmp->neg && (!strcmp((const char *)sni_tmp->name.key, trash.area))) {
2437 skip = 1;
2438 break;
2439 }
2440 }
2441 if (skip)
2442 continue;
2443 }
2444
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002445 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002446 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002447 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002448 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002449 break;
2450 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002451 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002452 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002453 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002454 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002455 if (!node_anonymous)
2456 node_anonymous = n;
2457 break;
2458 }
2459 }
2460 }
William Lallemand94bd3192020-08-14 14:43:35 +02002461 }
2462 /* Once the certificates are found, select them depending on what is
2463 * supported in the client and by key_signature priority order: EDSA >
2464 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002465 if (has_ecdsa_sig && node_ecdsa)
2466 node = node_ecdsa;
2467 else if (has_rsa_sig && node_rsa)
2468 node = node_rsa;
2469 else if (node_anonymous)
2470 node = node_anonymous;
2471 else if (node_ecdsa)
2472 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2473 else
2474 node = node_rsa; /* no rsa signature case (far far away) */
2475
William Lallemand94bd3192020-08-14 14:43:35 +02002476 if (node) {
2477 /* switch ctx */
2478 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2479 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2480 if (conf) {
2481 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2482 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2483 if (conf->early_data)
2484 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002485 }
William Lallemand94bd3192020-08-14 14:43:35 +02002486 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2487 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002488 }
William Lallemand150bfa82019-09-19 17:12:49 +02002489
William Lallemand02010472019-10-18 11:02:19 +02002490 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002491#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002492 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002493 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002494 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002495 }
2496#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002497 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002498 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002499 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002500 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002501 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002502 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02002503allow_early:
2504#ifdef OPENSSL_IS_BORINGSSL
2505 if (allow_early)
2506 SSL_set_early_data_enabled(ssl, 1);
2507#else
2508 if (!allow_early)
2509 SSL_set_max_early_data(ssl, 0);
2510#endif
2511 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002512 abort:
2513 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2514 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002515#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002516 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002517#else
2518 *al = SSL_AD_UNRECOGNIZED_NAME;
2519 return 0;
2520#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002521}
2522
2523#else /* OPENSSL_IS_BORINGSSL */
2524
Emeric Brunfc0421f2012-09-07 17:30:07 +02002525/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2526 * warning when no match is found, which implies the default (first) cert
2527 * will keep being used.
2528 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002529static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002530{
2531 const char *servername;
2532 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002533 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002534 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002535 int i;
2536 (void)al; /* shut gcc stupid warning */
2537
2538 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002539 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002540#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002541 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2542 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002543#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002544 if (s->strict_sni)
2545 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002546 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002547 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002548 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002549 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002550 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002551
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002552 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002553 if (!servername[i])
2554 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002555 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002556 if (!wildp && (trash.area[i] == '.'))
2557 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002558 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002559 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002560
William Lallemand150bfa82019-09-19 17:12:49 +02002561 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002562 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002563 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002564 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2565 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002566 if (!container_of(n, struct sni_ctx, name)->neg) {
2567 node = n;
2568 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002569 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002570 }
2571 if (!node && wildp) {
2572 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002573 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2574 /* lookup a not neg filter */
2575 if (!container_of(n, struct sni_ctx, name)->neg) {
2576 node = n;
2577 break;
2578 }
2579 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002580 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002581 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002582#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002583 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2584 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002585 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002586 return SSL_TLSEXT_ERR_OK;
2587 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002588#endif
William Lallemand21724f02019-11-04 17:56:13 +01002589 if (s->strict_sni) {
2590 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002591 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002592 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002593 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002594 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002595 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002596 }
2597
2598 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002599 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002600 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002601 return SSL_TLSEXT_ERR_OK;
2602}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002603#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002604#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2605
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002606#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002607
2608static DH * ssl_get_dh_1024(void)
2609{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002610 static unsigned char dh1024_p[]={
2611 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2612 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2613 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2614 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2615 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2616 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2617 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2618 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2619 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2620 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2621 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2622 };
2623 static unsigned char dh1024_g[]={
2624 0x02,
2625 };
2626
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002627 BIGNUM *p;
2628 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002629 DH *dh = DH_new();
2630 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002631 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2632 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002633
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002634 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002635 DH_free(dh);
2636 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002637 } else {
2638 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002639 }
2640 }
2641 return dh;
2642}
2643
2644static DH *ssl_get_dh_2048(void)
2645{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002646 static unsigned char dh2048_p[]={
2647 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2648 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2649 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2650 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2651 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2652 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2653 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2654 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2655 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2656 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2657 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2658 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2659 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2660 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2661 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2662 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2663 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2664 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2665 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2666 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2667 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2668 0xB7,0x1F,0x77,0xF3,
2669 };
2670 static unsigned char dh2048_g[]={
2671 0x02,
2672 };
2673
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002674 BIGNUM *p;
2675 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002676 DH *dh = DH_new();
2677 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002678 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2679 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002680
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002681 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002682 DH_free(dh);
2683 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002684 } else {
2685 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002686 }
2687 }
2688 return dh;
2689}
2690
2691static DH *ssl_get_dh_4096(void)
2692{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002693 static unsigned char dh4096_p[]={
2694 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2695 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2696 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2697 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2698 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2699 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2700 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2701 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2702 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2703 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2704 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2705 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2706 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2707 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2708 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2709 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2710 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2711 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2712 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2713 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2714 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2715 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2716 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2717 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2718 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2719 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2720 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2721 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2722 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2723 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2724 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2725 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2726 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2727 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2728 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2729 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2730 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2731 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2732 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2733 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2734 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2735 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2736 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002737 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002738 static unsigned char dh4096_g[]={
2739 0x02,
2740 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002741
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002742 BIGNUM *p;
2743 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002744 DH *dh = DH_new();
2745 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002746 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2747 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002748
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002749 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002750 DH_free(dh);
2751 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002752 } else {
2753 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002754 }
2755 }
2756 return dh;
2757}
2758
2759/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002760 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002761static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2762{
2763 DH *dh = NULL;
2764 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002765 int type;
2766
2767 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002768
2769 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2770 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2771 */
2772 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2773 keylen = EVP_PKEY_bits(pkey);
2774 }
2775
Willy Tarreauef934602016-12-22 23:12:01 +01002776 if (keylen > global_ssl.default_dh_param) {
2777 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002778 }
2779
Remi Gacogned3a341a2015-05-29 16:26:17 +02002780 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002781 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002782 }
2783 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002784 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002785 }
2786 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002787 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002788 }
2789
2790 return dh;
2791}
2792
Remi Gacogne47783ef2015-05-29 15:53:22 +02002793static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002794{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002795 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002796 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002797
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002798 if (in == NULL)
2799 goto end;
2800
Remi Gacogne47783ef2015-05-29 15:53:22 +02002801 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002802 goto end;
2803
Remi Gacogne47783ef2015-05-29 15:53:22 +02002804 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2805
2806end:
2807 if (in)
2808 BIO_free(in);
2809
Emeric Brune1b4ed42018-08-16 15:14:12 +02002810 ERR_clear_error();
2811
Remi Gacogne47783ef2015-05-29 15:53:22 +02002812 return dh;
2813}
2814
2815int ssl_sock_load_global_dh_param_from_file(const char *filename)
2816{
2817 global_dh = ssl_sock_get_dh_from_file(filename);
2818
2819 if (global_dh) {
2820 return 0;
2821 }
2822
2823 return -1;
2824}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002825#endif
2826
William Lallemand9117de92019-10-04 00:29:42 +02002827/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002828static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002829 struct bind_conf *s, struct ssl_bind_conf *conf,
2830 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002831{
2832 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002833 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002834
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002835 if (*name == '!') {
2836 neg = 1;
2837 name++;
2838 }
2839 if (*name == '*') {
2840 wild = 1;
2841 name++;
2842 }
2843 /* !* filter is a nop */
2844 if (neg && wild)
2845 return order;
2846 if (*name) {
2847 int j, len;
2848 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002849 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02002850 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002851 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002852 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002853 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002854
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002855 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002856 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002857 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002858 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002859 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002860 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002861 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002862 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002863 sc->order = order++;
2864 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002865 sc->wild = wild;
2866 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002867 sc->ckch_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02002868 LIST_ADDQ(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002869 }
2870 return order;
2871}
2872
William Lallemand6af03992019-07-23 15:00:54 +02002873/*
William Lallemand1d29c742019-10-04 00:53:29 +02002874 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2875 * This function can't return an error.
2876 *
2877 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2878 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002879void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002880{
2881
2882 struct sni_ctx *sc0, *sc0b, *sc1;
2883 struct ebmb_node *node;
William Lallemand21724f02019-11-04 17:56:13 +01002884 int def = 0;
William Lallemand1d29c742019-10-04 00:53:29 +02002885
2886 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2887
2888 /* ignore if sc0 was already inserted in a tree */
2889 if (sc0->name.node.leaf_p)
2890 continue;
2891
2892 /* Check for duplicates. */
2893 if (sc0->wild)
2894 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2895 else
2896 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2897
2898 for (; node; node = ebmb_next_dup(node)) {
2899 sc1 = ebmb_entry(node, struct sni_ctx, name);
2900 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2901 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2902 /* it's a duplicate, we should remove and free it */
2903 LIST_DEL(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002904 SSL_CTX_free(sc0->ctx);
William Lallemand1d29c742019-10-04 00:53:29 +02002905 free(sc0);
2906 sc0 = NULL;
William Lallemande15029b2019-10-14 10:46:58 +02002907 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002908 }
2909 }
2910
2911 /* if duplicate, ignore the insertion */
2912 if (!sc0)
2913 continue;
2914
2915 if (sc0->wild)
2916 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
2917 else
2918 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
William Lallemand21724f02019-11-04 17:56:13 +01002919
2920 /* replace the default_ctx if required with the first ctx */
2921 if (ckch_inst->is_default && !def) {
William Lallemand02e19a52020-04-08 16:11:26 +02002922 SSL_CTX_free(bind_conf->default_ctx);
2923 SSL_CTX_up_ref(sc0->ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002924 bind_conf->default_ctx = sc0->ctx;
2925 def = 1;
2926 }
William Lallemand1d29c742019-10-04 00:53:29 +02002927 }
2928}
2929
2930/*
William Lallemande3af8fb2019-10-08 11:36:53 +02002931 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02002932 */
William Lallemande3af8fb2019-10-08 11:36:53 +02002933struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02002934
William Lallemand2954c472020-03-06 21:54:13 +01002935/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02002936struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02002937
Emeric Brun7a883362019-10-17 13:27:40 +02002938/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002939 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02002940 * DH parameter is loaded into the SSL_CTX and if there is no
2941 * DH parameter available in ckchs nor in global, the default
2942 * DH parameters are applied on the SSL_CTX.
2943 * Returns a bitfield containing the flags:
2944 * ERR_FATAL in any fatal error case
2945 * ERR_ALERT if a reason of the error is availabine in err
2946 * ERR_WARN if a warning is available into err
2947 * The value 0 means there is no error nor warning and
2948 * the operation succeed.
2949 */
William Lallemandfa892222019-07-23 16:06:08 +02002950#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02002951static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
2952 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02002953{
Emeric Brun7a883362019-10-17 13:27:40 +02002954 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02002955 DH *dh = NULL;
2956
William Lallemanda8c73742019-07-31 18:31:34 +02002957 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02002958 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02002959 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
2960 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
2961 err && *err ? *err : "", path);
2962#if defined(SSL_CTX_set_dh_auto)
2963 SSL_CTX_set_dh_auto(ctx, 1);
2964 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2965 err && *err ? *err : "");
2966#else
2967 memprintf(err, "%s, DH ciphers won't be available.\n",
2968 err && *err ? *err : "");
2969#endif
2970 ret |= ERR_WARN;
2971 goto end;
2972 }
William Lallemandfa892222019-07-23 16:06:08 +02002973
2974 if (ssl_dh_ptr_index >= 0) {
2975 /* store a pointer to the DH params to avoid complaining about
2976 ssl-default-dh-param not being set for this SSL_CTX */
2977 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
2978 }
2979 }
2980 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02002981 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
2982 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
2983 err && *err ? *err : "", path);
2984#if defined(SSL_CTX_set_dh_auto)
2985 SSL_CTX_set_dh_auto(ctx, 1);
2986 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2987 err && *err ? *err : "");
2988#else
2989 memprintf(err, "%s, DH ciphers won't be available.\n",
2990 err && *err ? *err : "");
2991#endif
2992 ret |= ERR_WARN;
2993 goto end;
2994 }
William Lallemandfa892222019-07-23 16:06:08 +02002995 }
2996 else {
2997 /* Clear openssl global errors stack */
2998 ERR_clear_error();
2999
Willy Tarreau58ee2312020-11-05 19:38:05 +01003000 if (global_ssl.default_dh_param && global_ssl.default_dh_param <= 1024) {
William Lallemandfa892222019-07-23 16:06:08 +02003001 /* we are limited to DH parameter of 1024 bits anyway */
3002 if (local_dh_1024 == NULL)
3003 local_dh_1024 = ssl_get_dh_1024();
3004
Emeric Brun7a883362019-10-17 13:27:40 +02003005 if (local_dh_1024 == NULL) {
3006 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3007 err && *err ? *err : "", path);
3008 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02003009 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02003010 }
William Lallemandfa892222019-07-23 16:06:08 +02003011
Emeric Bruna9363eb2019-10-17 14:53:03 +02003012 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
3013 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3014 err && *err ? *err : "", path);
3015#if defined(SSL_CTX_set_dh_auto)
3016 SSL_CTX_set_dh_auto(ctx, 1);
3017 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3018 err && *err ? *err : "");
3019#else
3020 memprintf(err, "%s, DH ciphers won't be available.\n",
3021 err && *err ? *err : "");
3022#endif
3023 ret |= ERR_WARN;
3024 goto end;
3025 }
William Lallemandfa892222019-07-23 16:06:08 +02003026 }
3027 else {
3028 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
3029 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003030 }
3031
William Lallemandf9568fc2019-10-16 18:27:58 +02003032end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003033 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003034 return ret;
3035}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003036#endif
William Lallemandfa892222019-07-23 16:06:08 +02003037
yanbzhu488a4d22015-12-01 15:16:07 -05003038/* Loads the info in ckch into ctx
Emeric Bruna96b5822019-10-17 13:25:14 +02003039 * Returns a bitfield containing the flags:
3040 * ERR_FATAL in any fatal error case
3041 * ERR_ALERT if the reason of the error is available in err
3042 * ERR_WARN if a warning is available into err
3043 * The value 0 means there is no error nor warning and
3044 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003045 */
3046static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3047{
Emeric Bruna96b5822019-10-17 13:25:14 +02003048 int errcode = 0;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003049 STACK_OF(X509) *find_chain = NULL;
Emeric Bruna96b5822019-10-17 13:25:14 +02003050
yanbzhu488a4d22015-12-01 15:16:07 -05003051 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3052 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3053 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003054 errcode |= ERR_ALERT | ERR_FATAL;
3055 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003056 }
3057
3058 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3059 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3060 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003061 errcode |= ERR_ALERT | ERR_FATAL;
3062 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003063 }
3064
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003065 if (ckch->chain) {
3066 find_chain = ckch->chain;
3067 } else {
3068 /* Find Certificate Chain in global */
3069 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003070 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003071 if (issuer)
3072 find_chain = issuer->chain;
3073 }
William Lallemand85888572020-02-27 14:48:35 +01003074
William Lallemand935d8292020-08-12 20:02:10 +02003075 if (!find_chain) {
3076 /* always put a null chain stack in the SSL_CTX so it does not
3077 * try to build the chain from the verify store */
3078 find_chain = sk_X509_new_null();
3079 }
3080
William Lallemandf187ce62020-06-02 18:27:20 +02003081 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003082#ifdef SSL_CTX_set1_chain
William Lallemand935d8292020-08-12 20:02:10 +02003083 if (!SSL_CTX_set1_chain(ctx, find_chain)) {
3084 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3085 err && *err ? *err : "", path);
3086 errcode |= ERR_ALERT | ERR_FATAL;
3087 goto end;
3088 }
William Lallemandf187ce62020-06-02 18:27:20 +02003089#else
3090 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003091 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02003092 STACK_OF(X509) *chain;
3093 chain = X509_chain_up_ref(find_chain);
3094 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003095 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003096 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3097 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003098 X509_free(ca);
3099 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003100 errcode |= ERR_ALERT | ERR_FATAL;
3101 goto end;
3102 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003103 }
William Lallemandf187ce62020-06-02 18:27:20 +02003104#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003105
William Lallemand9a1d8392020-08-10 17:28:23 +02003106#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003107 /* remove the Root CA from the SSL_CTX if the option is activated */
3108 if (global_ssl.skip_self_issued_ca) {
3109 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3110 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3111 err && *err ? *err : "", path);
3112 errcode |= ERR_ALERT | ERR_FATAL;
3113 goto end;
3114 }
3115 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003116#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003117
William Lallemandfa892222019-07-23 16:06:08 +02003118#ifndef OPENSSL_NO_DH
3119 /* store a NULL pointer to indicate we have not yet loaded
3120 a custom DH param file */
3121 if (ssl_dh_ptr_index >= 0) {
3122 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3123 }
3124
Emeric Brun7a883362019-10-17 13:27:40 +02003125 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3126 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003127 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3128 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003129 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003130 }
3131#endif
3132
Ilya Shipitsine4f38f92021-02-06 18:55:27 +05003133#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003134 if (sctl_ex_index >= 0 && ckch->sctl) {
3135 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3136 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003137 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003138 errcode |= ERR_ALERT | ERR_FATAL;
3139 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003140 }
3141 }
3142#endif
3143
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003144#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003145 /* Load OCSP Info into context */
3146 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003147 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003148 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",
3149 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003150 errcode |= ERR_ALERT | ERR_FATAL;
3151 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003152 }
3153 }
William Lallemand246c0242019-10-11 08:59:13 +02003154#endif
3155
Emeric Bruna96b5822019-10-17 13:25:14 +02003156 end:
3157 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003158}
3159
William Lallemand614ca0d2019-10-07 13:52:11 +02003160/*
3161 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003162 *
3163 * Returns a bitfield containing the flags:
3164 * ERR_FATAL in any fatal error case
3165 * ERR_ALERT if the reason of the error is available in err
3166 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003167 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003168int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003169 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003170{
William Lallemandc9402072019-05-15 15:33:54 +02003171 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003172 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003173 int order = 0;
3174 X509_NAME *xname;
3175 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003176 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003177 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003178#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3179 STACK_OF(GENERAL_NAME) *names;
3180#endif
William Lallemand36b84632019-07-18 19:28:17 +02003181 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003182 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003183 int errcode = 0;
3184
3185 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003186
William Lallemande3af8fb2019-10-08 11:36:53 +02003187 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003188 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003189
William Lallemande3af8fb2019-10-08 11:36:53 +02003190 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003191
William Lallemandc9402072019-05-15 15:33:54 +02003192 ctx = SSL_CTX_new(SSLv23_server_method());
3193 if (!ctx) {
3194 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3195 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003196 errcode |= ERR_ALERT | ERR_FATAL;
3197 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003198 }
3199
Emeric Bruna96b5822019-10-17 13:25:14 +02003200 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3201 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003202 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003203
3204 ckch_inst = ckch_inst_new();
3205 if (!ckch_inst) {
3206 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3207 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003208 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003209 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003210 }
3211
William Lallemand36b84632019-07-18 19:28:17 +02003212 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003213 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003214 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003215 switch(EVP_PKEY_base_id(pkey)) {
3216 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003217 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003218 break;
3219 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003220 kinfo.sig = TLSEXT_signature_ecdsa;
3221 break;
3222 case EVP_PKEY_DSA:
3223 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003224 break;
3225 }
3226 EVP_PKEY_free(pkey);
3227 }
3228
Emeric Brun50bcecc2013-04-22 13:05:23 +02003229 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003230 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003231 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 +02003232 if (order < 0) {
3233 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003234 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003235 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003236 }
3237 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003238 }
3239 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003240#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003241 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003242 if (names) {
3243 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3244 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3245 if (name->type == GEN_DNS) {
3246 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003247 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003248 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003249 if (order < 0) {
3250 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003251 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003252 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003253 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003254 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003255 }
3256 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003257 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003258 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003259#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003260 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003261 i = -1;
3262 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3263 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003264 ASN1_STRING *value;
3265
3266 value = X509_NAME_ENTRY_get_data(entry);
3267 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003268 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003269 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003270 if (order < 0) {
3271 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003272 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003273 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003274 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003275 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003276 }
3277 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003278 /* we must not free the SSL_CTX anymore below, since it's already in
3279 * the tree, so it will be discovered and cleaned in time.
3280 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003281
Emeric Brunfc0421f2012-09-07 17:30:07 +02003282#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003283 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003284 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3285 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003286 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003287 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003288 }
3289#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003290 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003291 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003292 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003293 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003294 SSL_CTX_up_ref(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003295 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003296
William Lallemand9117de92019-10-04 00:29:42 +02003297 /* everything succeed, the ckch instance can be used */
3298 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003299 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003300 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003301
William Lallemand02e19a52020-04-08 16:11:26 +02003302 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3303
Emeric Brun054563d2019-10-17 13:16:58 +02003304 *ckchi = ckch_inst;
3305 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003306
3307error:
3308 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003309 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003310 if (ckch_inst->is_default)
3311 SSL_CTX_free(ctx);
3312
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003313 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003314 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003315 }
William Lallemandd9199372019-10-04 15:37:05 +02003316 SSL_CTX_free(ctx);
3317
Emeric Brun054563d2019-10-17 13:16:58 +02003318 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003319}
3320
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003321/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003322static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3323 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003324 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003325{
Emeric Brun054563d2019-10-17 13:16:58 +02003326 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003327
3328 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003329 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 +02003330
Emeric Brun054563d2019-10-17 13:16:58 +02003331 if (errcode & ERR_CODE)
3332 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003333
William Lallemand24bde432020-03-09 16:48:43 +01003334 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003335
3336 /* succeed, add the instance to the ckch_store's list of instance */
William Lallemand24bde432020-03-09 16:48:43 +01003337 LIST_ADDQ(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003338 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003339}
3340
William Lallemand6be66ec2020-03-06 22:26:32 +01003341
William Lallemand4c68bba2020-03-30 18:45:10 +02003342
3343
3344/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3345 * done once. Zero is returned if the operation fails. No error is returned
3346 * if the random is said as not implemented, because we expect that openssl
3347 * will use another method once needed.
3348 */
3349static int ssl_initialize_random()
3350{
3351 unsigned char random;
3352 static int random_initialized = 0;
3353
3354 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3355 random_initialized = 1;
3356
3357 return random_initialized;
3358}
3359
William Lallemand2954c472020-03-06 21:54:13 +01003360/* Load a crt-list file, this is done in 2 parts:
3361 * - store the content of the file in a crtlist structure with crtlist_entry structures
3362 * - generate the instances by iterating on entries in the crtlist struct
3363 *
3364 * Nothing is locked there, this function is used in the configuration parser.
3365 *
3366 * Returns a set of ERR_* flags possibly with an error in <err>.
3367 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003368int 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 +01003369{
3370 struct crtlist *crtlist = NULL;
3371 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003372 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003373 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003374 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003375 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003376
William Lallemand79d31ec2020-03-25 15:10:49 +01003377 bind_conf_node = malloc(sizeof(*bind_conf_node));
3378 if (!bind_conf_node) {
3379 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3380 cfgerr |= ERR_FATAL | ERR_ALERT;
3381 goto error;
3382 }
3383 bind_conf_node->next = NULL;
3384 bind_conf_node->bind_conf = bind_conf;
3385
William Lallemand41ca9302020-04-08 13:15:18 +02003386 /* strip trailing slashes, including first one */
3387 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3388 *end = 0;
3389
William Lallemand2954c472020-03-06 21:54:13 +01003390 /* look for an existing crtlist or create one */
3391 eb = ebst_lookup(&crtlists_tree, file);
3392 if (eb) {
3393 crtlist = ebmb_entry(eb, struct crtlist, node);
3394 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003395 /* load a crt-list OR a directory */
3396 if (dir)
3397 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3398 else
3399 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3400
William Lallemand2954c472020-03-06 21:54:13 +01003401 if (!(cfgerr & ERR_CODE))
3402 ebst_insert(&crtlists_tree, &crtlist->node);
3403 }
3404
3405 if (cfgerr & ERR_CODE) {
3406 cfgerr |= ERR_FATAL | ERR_ALERT;
3407 goto error;
3408 }
3409
3410 /* generates ckch instance from the crtlist_entry */
3411 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3412 struct ckch_store *store;
3413 struct ckch_inst *ckch_inst = NULL;
3414
3415 store = entry->node.key;
3416 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3417 if (cfgerr & ERR_CODE) {
3418 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3419 goto error;
3420 }
William Lallemand49398312020-03-30 17:01:33 +02003421 LIST_ADDQ(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003422 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003423 }
William Lallemand2954c472020-03-06 21:54:13 +01003424
William Lallemand79d31ec2020-03-25 15:10:49 +01003425 /* add the bind_conf to the list */
3426 bind_conf_node->next = crtlist->bind_conf;
3427 crtlist->bind_conf = bind_conf_node;
3428
William Lallemand2954c472020-03-06 21:54:13 +01003429 return cfgerr;
3430error:
3431 {
William Lallemand49398312020-03-30 17:01:33 +02003432 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003433 struct ckch_inst *inst, *s_inst;
3434
William Lallemand49398312020-03-30 17:01:33 +02003435 lastentry = entry; /* which entry we tried to generate last */
3436 if (lastentry) {
3437 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3438 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3439 break;
3440
3441 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003442
William Lallemand49398312020-03-30 17:01:33 +02003443 /* this was not generated for this bind_conf, skip */
3444 if (inst->bind_conf != bind_conf)
3445 continue;
3446
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003447 /* free the sni_ctx and instance */
3448 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003449 }
William Lallemand2954c472020-03-06 21:54:13 +01003450 }
William Lallemand2954c472020-03-06 21:54:13 +01003451 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003452 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003453 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003454 return cfgerr;
3455}
3456
William Lallemand06b22a82020-03-16 14:45:55 +01003457/* Returns a set of ERR_* flags possibly with an error in <err>. */
3458int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3459{
3460 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003461 int cfgerr = 0;
3462 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003463 struct ckch_inst *ckch_inst = NULL;
William Lallemand7efbaf12020-11-20 15:36:13 +01003464 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003465
3466 if ((ckchs = ckchs_lookup(path))) {
3467 /* we found the ckchs in the tree, we can use it directly */
William Lallemand7efbaf12020-11-20 15:36:13 +01003468 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3469 found++;
3470 } else if (stat(path, &buf) == 0) {
3471 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003472 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003473 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003474 if (!ckchs)
William Lallemand7efbaf12020-11-20 15:36:13 +01003475 cfgerr |= ERR_ALERT | ERR_FATAL;
3476 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003477 } else {
William Lallemand7efbaf12020-11-20 15:36:13 +01003478 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003479 }
3480 } else {
3481 /* stat failed, could be a bundle */
3482 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003483 char fp[MAXPATHLEN+1] = {0};
3484 int n = 0;
3485
3486 /* Load all possible certs and keys in separate ckch_store */
3487 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3488 struct stat buf;
3489 int ret;
3490
3491 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3492 if (ret > sizeof(fp))
3493 continue;
3494
3495 if ((ckchs = ckchs_lookup(fp))) {
3496 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand7efbaf12020-11-20 15:36:13 +01003497 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003498 } else {
3499 if (stat(fp, &buf) == 0) {
William Lallemand7efbaf12020-11-20 15:36:13 +01003500 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003501 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003502 if (!ckchs)
William Lallemand7efbaf12020-11-20 15:36:13 +01003503 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003504 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3505 }
3506 }
3507 }
William Lallemand00b831e2020-12-04 15:45:02 +01003508#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3509 if (found) {
3510 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3511 err && *err ? *err : "", path);
3512 cfgerr |= ERR_ALERT | ERR_FATAL;
3513 }
3514#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003515 }
3516 }
William Lallemand7efbaf12020-11-20 15:36:13 +01003517 if (!found) {
3518 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3519 err && *err ? *err : "", path, strerror(errno));
3520 cfgerr |= ERR_ALERT | ERR_FATAL;
3521 }
William Lallemand06b22a82020-03-16 14:45:55 +01003522
3523 return cfgerr;
3524}
3525
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003526/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003527static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003528ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003529{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003530 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003531 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003532 SSL_OP_ALL | /* all known workarounds for bugs */
3533 SSL_OP_NO_SSLv2 |
3534 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003535 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003536 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003537 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003538 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003539 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003540 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003541 SSL_MODE_ENABLE_PARTIAL_WRITE |
3542 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003543 SSL_MODE_RELEASE_BUFFERS |
3544 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003545 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003546 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003547 int flags = MC_SSL_O_ALL;
3548 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003549 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003550
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003551 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003552 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003553
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003554 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003555 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3556 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3557 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003558 else
3559 flags = conf_ssl_methods->flags;
3560
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003561 min = conf_ssl_methods->min;
3562 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003563
3564 /* default minimum is TLSV12, */
3565 if (!min) {
3566 if (!max || (max >= default_min_ver)) {
3567 min = default_min_ver;
3568 } else {
3569 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). "
3570 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3571 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3572 min = max;
3573 }
3574 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003575 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003576 if (min)
3577 flags |= (methodVersions[min].flag - 1);
3578 if (max)
3579 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003580 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003581 min = max = CONF_TLSV_NONE;
3582 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003583 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003584 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003585 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003586 if (min) {
3587 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003588 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3589 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3590 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3591 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003592 hole = 0;
3593 }
3594 max = i;
3595 }
3596 else {
3597 min = max = i;
3598 }
3599 }
3600 else {
3601 if (min)
3602 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003603 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003604 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003605 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3606 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003607 cfgerr += 1;
3608 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003609 /* save real min/max in bind_conf */
3610 conf_ssl_methods->min = min;
3611 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003612
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003613#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003614 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003615 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003616 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003617 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003618 else
William Lallemandd0712f32020-06-11 17:34:00 +02003619 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
3620 /* clear every version flags in case SSL_CTX_new()
3621 * returns an SSL_CTX with disabled versions */
3622 SSL_CTX_clear_options(ctx, methodVersions[i].option);
3623
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003624 if (flags & methodVersions[i].flag)
3625 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02003626
3627 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003628#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003629 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003630 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3631 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003632#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003633
3634 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3635 options |= SSL_OP_NO_TICKET;
3636 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3637 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003638
3639#ifdef SSL_OP_NO_RENEGOTIATION
3640 options |= SSL_OP_NO_RENEGOTIATION;
3641#endif
3642
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003643 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003644
Willy Tarreau5db847a2019-05-09 14:13:35 +02003645#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003646 if (global_ssl.async)
3647 mode |= SSL_MODE_ASYNC;
3648#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003649 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003650 if (global_ssl.life_time)
3651 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003652
3653#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3654#ifdef OPENSSL_IS_BORINGSSL
3655 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3656 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003657#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003658 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003659 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003660 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3661 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003662#else
3663 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003664#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003665 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003666#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003667 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003668}
3669
William Lallemand4f45bb92017-10-30 20:08:51 +01003670
3671static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3672{
3673 if (first == block) {
3674 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3675 if (first->len > 0)
3676 sh_ssl_sess_tree_delete(sh_ssl_sess);
3677 }
3678}
3679
3680/* return first block from sh_ssl_sess */
3681static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3682{
3683 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3684
3685}
3686
3687/* store a session into the cache
3688 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3689 * data: asn1 encoded session
3690 * data_len: asn1 encoded session length
3691 * Returns 1 id session was stored (else 0)
3692 */
3693static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3694{
3695 struct shared_block *first;
3696 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3697
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003698 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003699 if (!first) {
3700 /* Could not retrieve enough free blocks to store that session */
3701 return 0;
3702 }
3703
3704 /* STORE the key in the first elem */
3705 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3706 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3707 first->len = sizeof(struct sh_ssl_sess_hdr);
3708
3709 /* it returns the already existing node
3710 or current node if none, never returns null */
3711 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3712 if (oldsh_ssl_sess != sh_ssl_sess) {
3713 /* NOTE: Row couldn't be in use because we lock read & write function */
3714 /* release the reserved row */
3715 shctx_row_dec_hot(ssl_shctx, first);
3716 /* replace the previous session already in the tree */
3717 sh_ssl_sess = oldsh_ssl_sess;
3718 /* ignore the previous session data, only use the header */
3719 first = sh_ssl_sess_first_block(sh_ssl_sess);
3720 shctx_row_inc_hot(ssl_shctx, first);
3721 first->len = sizeof(struct sh_ssl_sess_hdr);
3722 }
3723
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003724 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01003725 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003726 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01003727 }
3728
3729 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003730
3731 return 1;
3732}
William Lallemanded0b5ad2017-10-30 19:36:36 +01003733
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003734/* SSL callback used when a new session is created while connecting to a server */
3735static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
3736{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02003737 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003738 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003739
Willy Tarreau07d94e42018-09-20 10:57:52 +02003740 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003741
Olivier Houcharde6060c52017-11-16 17:42:52 +01003742 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
3743 int len;
3744 unsigned char *ptr;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003745
Olivier Houcharde6060c52017-11-16 17:42:52 +01003746 len = i2d_SSL_SESSION(sess, NULL);
3747 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
3748 ptr = s->ssl_ctx.reused_sess[tid].ptr;
3749 } else {
3750 free(s->ssl_ctx.reused_sess[tid].ptr);
3751 ptr = s->ssl_ctx.reused_sess[tid].ptr = malloc(len);
3752 s->ssl_ctx.reused_sess[tid].allocated_size = len;
3753 }
3754 if (s->ssl_ctx.reused_sess[tid].ptr) {
3755 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
3756 &ptr);
3757 }
3758 } else {
3759 free(s->ssl_ctx.reused_sess[tid].ptr);
3760 s->ssl_ctx.reused_sess[tid].ptr = NULL;
3761 }
3762
3763 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003764}
3765
Olivier Houcharde6060c52017-11-16 17:42:52 +01003766
William Lallemanded0b5ad2017-10-30 19:36:36 +01003767/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01003768int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003769{
3770 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
3771 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
3772 unsigned char *p;
3773 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02003774 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003775 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003776
3777 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003778 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02003779 * note: SSL_SESSION_set1_id is using
3780 * a memcpy so we need to use a different pointer
3781 * than sid_data or sid_ctx_data to avoid valgrind
3782 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01003783 */
3784
3785 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02003786
3787 /* copy value in an other buffer */
3788 memcpy(encid, sid_data, sid_length);
3789
3790 /* pad with 0 */
3791 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
3792 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
3793
3794 /* force length to zero to avoid ASN1 encoding */
3795 SSL_SESSION_set1_id(sess, encid, 0);
3796
3797 /* force length to zero to avoid ASN1 encoding */
3798 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003799
3800 /* check if buffer is large enough for the ASN1 encoded session */
3801 data_len = i2d_SSL_SESSION(sess, NULL);
3802 if (data_len > SHSESS_MAX_DATA_LEN)
3803 goto err;
3804
3805 p = encsess;
3806
3807 /* process ASN1 session encoding before the lock */
3808 i2d_SSL_SESSION(sess, &p);
3809
William Lallemanded0b5ad2017-10-30 19:36:36 +01003810
William Lallemanda3c77cf2017-10-30 23:44:40 +01003811 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003812 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003813 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01003814 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003815err:
3816 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02003817 SSL_SESSION_set1_id(sess, encid, sid_length);
3818 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003819
3820 return 0; /* do not increment session reference count */
3821}
3822
3823/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003824SSL_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 +01003825{
William Lallemand4f45bb92017-10-30 20:08:51 +01003826 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003827 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
3828 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01003829 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01003830 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003831
3832 global.shctx_lookups++;
3833
3834 /* allow the session to be freed automatically by openssl */
3835 *do_copy = 0;
3836
3837 /* tree key is zeros padded sessionid */
3838 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3839 memcpy(tmpkey, key, key_len);
3840 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
3841 key = tmpkey;
3842 }
3843
3844 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003845 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003846
3847 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003848 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
3849 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003850 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003851 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003852 global.shctx_misses++;
3853 return NULL;
3854 }
3855
William Lallemand4f45bb92017-10-30 20:08:51 +01003856 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
3857 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003858
William Lallemand4f45bb92017-10-30 20:08:51 +01003859 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 +01003860
William Lallemanda3c77cf2017-10-30 23:44:40 +01003861 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003862
3863 /* decode ASN1 session */
3864 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01003865 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003866 /* Reset session id and session id contenxt */
3867 if (sess) {
3868 SSL_SESSION_set1_id(sess, key, key_len);
3869 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
3870 }
3871
3872 return sess;
3873}
3874
William Lallemand4f45bb92017-10-30 20:08:51 +01003875
William Lallemanded0b5ad2017-10-30 19:36:36 +01003876/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003877void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003878{
William Lallemand4f45bb92017-10-30 20:08:51 +01003879 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003880 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
3881 unsigned int sid_length;
3882 const unsigned char *sid_data;
3883 (void)ctx;
3884
3885 sid_data = SSL_SESSION_get_id(sess, &sid_length);
3886 /* tree key is zeros padded sessionid */
3887 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3888 memcpy(tmpkey, sid_data, sid_length);
3889 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
3890 sid_data = tmpkey;
3891 }
3892
William Lallemanda3c77cf2017-10-30 23:44:40 +01003893 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003894
3895 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003896 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
3897 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003898 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003899 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003900 }
3901
3902 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003903 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003904}
3905
3906/* Set session cache mode to server and disable openssl internal cache.
3907 * Set shared cache callbacks on an ssl context.
3908 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01003909void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003910{
3911 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
3912
3913 if (!ssl_shctx) {
3914 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
3915 return;
3916 }
3917
3918 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
3919 SSL_SESS_CACHE_NO_INTERNAL |
3920 SSL_SESS_CACHE_NO_AUTO_CLEAR);
3921
3922 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01003923 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
3924 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
3925 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003926}
William Lallemand7d42ef52020-07-06 11:41:30 +02003927
3928/*
3929 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
3930 *
3931 * The format is:
3932 * * <Label> <space> <ClientRandom> <space> <Secret>
3933 * We only need to copy the secret as there is a sample fetch for the ClientRandom
3934 */
3935
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05003936#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02003937void SSL_CTX_keylog(const SSL *ssl, const char *line)
3938{
3939 struct ssl_keylog *keylog;
3940 char *lastarg = NULL;
3941 char *dst = NULL;
3942
3943 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
3944 if (!keylog)
3945 return;
3946
3947 lastarg = strrchr(line, ' ');
3948 if (lastarg == NULL || ++lastarg == NULL)
3949 return;
3950
3951 dst = pool_alloc(pool_head_ssl_keylog_str);
3952 if (!dst)
3953 return;
3954
3955 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
3956 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
3957
3958 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
3959 if (keylog->client_random)
3960 goto error;
3961 keylog->client_random = dst;
3962
3963 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
3964 if (keylog->client_early_traffic_secret)
3965 goto error;
3966 keylog->client_early_traffic_secret = dst;
3967
3968 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
3969 if(keylog->client_handshake_traffic_secret)
3970 goto error;
3971 keylog->client_handshake_traffic_secret = dst;
3972
3973 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
3974 if (keylog->server_handshake_traffic_secret)
3975 goto error;
3976 keylog->server_handshake_traffic_secret = dst;
3977
3978 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
3979 if (keylog->client_traffic_secret_0)
3980 goto error;
3981 keylog->client_traffic_secret_0 = dst;
3982
3983 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
3984 if (keylog->server_traffic_secret_0)
3985 goto error;
3986 keylog->server_traffic_secret_0 = dst;
3987
3988 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
3989 if (keylog->early_exporter_secret)
3990 goto error;
3991 keylog->early_exporter_secret = dst;
3992
3993 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
3994 if (keylog->exporter_secret)
3995 goto error;
3996 keylog->exporter_secret = dst;
3997 } else {
3998 goto error;
3999 }
4000
4001 return;
4002
4003error:
4004 pool_free(pool_head_ssl_keylog_str, dst);
4005
4006 return;
4007}
4008#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004009
William Lallemand8b453912019-11-21 15:48:10 +01004010/*
4011 * This function applies the SSL configuration on a SSL_CTX
4012 * It returns an error code and fills the <err> buffer
4013 */
4014int 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 +01004015{
4016 struct proxy *curproxy = bind_conf->frontend;
4017 int cfgerr = 0;
4018 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004019 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004020 const char *conf_ciphers;
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004021#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004022 const char *conf_ciphersuites;
4023#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004024 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004025
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004026 if (ssl_conf) {
4027 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4028 int i, min, max;
4029 int flags = MC_SSL_O_ALL;
4030
4031 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004032 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4033 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004034 if (min)
4035 flags |= (methodVersions[min].flag - 1);
4036 if (max)
4037 flags |= ~((methodVersions[max].flag << 1) - 1);
4038 min = max = CONF_TLSV_NONE;
4039 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4040 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4041 if (min)
4042 max = i;
4043 else
4044 min = max = i;
4045 }
4046 /* save real min/max */
4047 conf_ssl_methods->min = min;
4048 conf_ssl_methods->max = max;
4049 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004050 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4051 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004052 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004053 }
4054 }
4055
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004056 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004057 case SSL_SOCK_VERIFY_NONE:
4058 verify = SSL_VERIFY_NONE;
4059 break;
4060 case SSL_SOCK_VERIFY_OPTIONAL:
4061 verify = SSL_VERIFY_PEER;
4062 break;
4063 case SSL_SOCK_VERIFY_REQUIRED:
4064 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4065 break;
4066 }
4067 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4068 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004069 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 +01004070 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 +01004071 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 +01004072 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004073 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004074 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004075 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004076 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004077 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004078 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004079 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4080 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4081 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4082 cfgerr |= ERR_ALERT | ERR_FATAL;
4083 }
4084 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004085 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004086 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 +02004087 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004088 }
Emeric Brun850efd52014-01-29 12:24:34 +01004089 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004090 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4091 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004092 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004093 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004094#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004095 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004096 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4097
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004098 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004099 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4100 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004101 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004102 }
Emeric Brun561e5742012-10-02 15:20:55 +02004103 else {
4104 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4105 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004106 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004107#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004108 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004109 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004110#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004111 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004112 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004113 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4114 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004115 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004116 }
4117 }
4118#endif
4119
William Lallemand4f45bb92017-10-30 20:08:51 +01004120 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004121 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4122 if (conf_ciphers &&
4123 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004124 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4125 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004126 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004127 }
4128
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004129#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004130 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4131 if (conf_ciphersuites &&
4132 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004133 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4134 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004135 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004136 }
4137#endif
4138
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004139#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004140 /* If tune.ssl.default-dh-param has not been set,
4141 neither has ssl-default-dh-file and no static DH
4142 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004143 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004144 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004145 (ssl_dh_ptr_index == -1 ||
4146 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004147 /* default to dh-param 2048 */
4148 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004149 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004150
Willy Tarreauef934602016-12-22 23:12:01 +01004151 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004152 if (local_dh_1024 == NULL) {
4153 local_dh_1024 = ssl_get_dh_1024();
4154 }
Willy Tarreauef934602016-12-22 23:12:01 +01004155 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004156 if (local_dh_2048 == NULL) {
4157 local_dh_2048 = ssl_get_dh_2048();
4158 }
Willy Tarreauef934602016-12-22 23:12:01 +01004159 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004160 if (local_dh_4096 == NULL) {
4161 local_dh_4096 = ssl_get_dh_4096();
4162 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004163 }
4164 }
4165 }
4166#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004167
Emeric Brunfc0421f2012-09-07 17:30:07 +02004168 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004169#if HA_OPENSSL_VERSION_NUMBER >= 0x00907000L
Emeric Brun29f037d2014-04-25 19:05:36 +02004170 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004171#endif
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05004172#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004173 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
4174#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004175
Bernard Spil13c53f82018-02-15 13:34:58 +01004176#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004177 ssl_conf_cur = NULL;
4178 if (ssl_conf && ssl_conf->npn_str)
4179 ssl_conf_cur = ssl_conf;
4180 else if (bind_conf->ssl_conf.npn_str)
4181 ssl_conf_cur = &bind_conf->ssl_conf;
4182 if (ssl_conf_cur)
4183 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004184#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004185#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004186 ssl_conf_cur = NULL;
4187 if (ssl_conf && ssl_conf->alpn_str)
4188 ssl_conf_cur = ssl_conf;
4189 else if (bind_conf->ssl_conf.alpn_str)
4190 ssl_conf_cur = &bind_conf->ssl_conf;
4191 if (ssl_conf_cur)
4192 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004193#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004194#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004195 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4196 if (conf_curves) {
4197 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004198 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4199 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004200 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004201 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004202 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004203 }
4204#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004205#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004206 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004207 int i;
4208 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004209#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004210 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004211 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4212 NULL);
4213
4214 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004215 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004216 return cfgerr;
4217 }
4218#else
4219 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4220 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4221 ECDHE_DEFAULT_CURVE);
4222#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004223
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004224 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004225 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004226 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4227 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004228 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004229 }
4230 else {
4231 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4232 EC_KEY_free(ecdh);
4233 }
4234 }
4235#endif
4236
Emeric Brunfc0421f2012-09-07 17:30:07 +02004237 return cfgerr;
4238}
4239
Evan Broderbe554312013-06-27 00:05:25 -07004240static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4241{
4242 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4243 size_t prefixlen, suffixlen;
4244
4245 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004246 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004247 return 1;
4248
Evan Broderbe554312013-06-27 00:05:25 -07004249 /* The rest of this logic is based on RFC 6125, section 6.4.3
4250 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4251
Emeric Bruna848dae2013-10-08 11:27:28 +02004252 pattern_wildcard = NULL;
4253 pattern_left_label_end = pattern;
4254 while (*pattern_left_label_end != '.') {
4255 switch (*pattern_left_label_end) {
4256 case 0:
4257 /* End of label not found */
4258 return 0;
4259 case '*':
4260 /* If there is more than one wildcards */
4261 if (pattern_wildcard)
4262 return 0;
4263 pattern_wildcard = pattern_left_label_end;
4264 break;
4265 }
4266 pattern_left_label_end++;
4267 }
4268
4269 /* If it's not trivial and there is no wildcard, it can't
4270 * match */
4271 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004272 return 0;
4273
4274 /* Make sure all labels match except the leftmost */
4275 hostname_left_label_end = strchr(hostname, '.');
4276 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004277 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004278 return 0;
4279
4280 /* Make sure the leftmost label of the hostname is long enough
4281 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004282 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004283 return 0;
4284
4285 /* Finally compare the string on either side of the
4286 * wildcard */
4287 prefixlen = pattern_wildcard - pattern;
4288 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004289 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4290 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004291 return 0;
4292
4293 return 1;
4294}
4295
4296static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4297{
4298 SSL *ssl;
4299 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004300 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004301 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004302 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004303
4304 int depth;
4305 X509 *cert;
4306 STACK_OF(GENERAL_NAME) *alt_names;
4307 int i;
4308 X509_NAME *cert_subject;
4309 char *str;
4310
4311 if (ok == 0)
4312 return ok;
4313
4314 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004315 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004316 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004317
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004318 /* We're checking if the provided hostnames match the desired one. The
4319 * desired hostname comes from the SNI we presented if any, or if not
4320 * provided then it may have been explicitly stated using a "verifyhost"
4321 * directive. If neither is set, we don't care about the name so the
4322 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004323 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004324 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004325 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004326 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004327 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004328 if (!servername)
4329 return ok;
4330 }
Evan Broderbe554312013-06-27 00:05:25 -07004331
4332 /* We only need to verify the CN on the actual server cert,
4333 * not the indirect CAs */
4334 depth = X509_STORE_CTX_get_error_depth(ctx);
4335 if (depth != 0)
4336 return ok;
4337
4338 /* At this point, the cert is *not* OK unless we can find a
4339 * hostname match */
4340 ok = 0;
4341
4342 cert = X509_STORE_CTX_get_current_cert(ctx);
4343 /* It seems like this might happen if verify peer isn't set */
4344 if (!cert)
4345 return ok;
4346
4347 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4348 if (alt_names) {
4349 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4350 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4351 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004352#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004353 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4354#else
Evan Broderbe554312013-06-27 00:05:25 -07004355 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004356#endif
Evan Broderbe554312013-06-27 00:05:25 -07004357 ok = ssl_sock_srv_hostcheck(str, servername);
4358 OPENSSL_free(str);
4359 }
4360 }
4361 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004362 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004363 }
4364
4365 cert_subject = X509_get_subject_name(cert);
4366 i = -1;
4367 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4368 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004369 ASN1_STRING *value;
4370 value = X509_NAME_ENTRY_get_data(entry);
4371 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004372 ok = ssl_sock_srv_hostcheck(str, servername);
4373 OPENSSL_free(str);
4374 }
4375 }
4376
Willy Tarreau71d058c2017-07-26 20:09:56 +02004377 /* report the mismatch and indicate if SNI was used or not */
4378 if (!ok && !conn->err_code)
4379 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004380 return ok;
4381}
4382
Emeric Brun94324a42012-10-11 14:00:19 +02004383/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004384int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004385{
Willy Tarreau03209342016-12-22 17:08:28 +01004386 struct proxy *curproxy = srv->proxy;
Emeric Brun94324a42012-10-11 14:00:19 +02004387 int cfgerr = 0;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004388 long options =
Emeric Brun94324a42012-10-11 14:00:19 +02004389 SSL_OP_ALL | /* all known workarounds for bugs */
4390 SSL_OP_NO_SSLv2 |
4391 SSL_OP_NO_COMPRESSION;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004392 long mode =
Emeric Brun94324a42012-10-11 14:00:19 +02004393 SSL_MODE_ENABLE_PARTIAL_WRITE |
4394 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004395 SSL_MODE_RELEASE_BUFFERS |
4396 SSL_MODE_SMALL_BUFFERS;
Emeric Brun850efd52014-01-29 12:24:34 +01004397 int verify = SSL_VERIFY_NONE;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004398 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004399 struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004400 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004401 int flags = MC_SSL_O_ALL;
Emeric Brun94324a42012-10-11 14:00:19 +02004402
Thierry Fournier383085f2013-01-24 14:15:43 +01004403 /* Make sure openssl opens /dev/urandom before the chroot */
4404 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004405 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004406 cfgerr++;
4407 }
4408
Willy Tarreaufce03112015-01-15 21:32:40 +01004409 /* Automatic memory computations need to know we use SSL there */
4410 global.ssl_used_backend = 1;
4411
4412 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004413 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004414 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004415 ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4416 curproxy->id, srv->id,
4417 srv->conf.file, srv->conf.line);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004418 cfgerr++;
4419 return cfgerr;
4420 }
4421 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004422 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004423 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004424
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004425 ctx = SSL_CTX_new(SSLv23_client_method());
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004426 if (!ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004427 ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4428 proxy_type_str(curproxy), curproxy->id,
4429 srv->id);
Emeric Brun94324a42012-10-11 14:00:19 +02004430 cfgerr++;
4431 return cfgerr;
4432 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004433
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004434 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004435 ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4436 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4437 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004438 else
4439 flags = conf_ssl_methods->flags;
4440
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004441 /* Real min and max should be determinate with configuration and openssl's capabilities */
4442 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004443 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004444 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004445 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004446
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004447 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004448 min = max = CONF_TLSV_NONE;
4449 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004450 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004451 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004452 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004453 if (min) {
4454 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004455 ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4456 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4457 proxy_type_str(curproxy), curproxy->id, srv->id,
4458 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004459 hole = 0;
4460 }
4461 max = i;
4462 }
4463 else {
4464 min = max = i;
4465 }
4466 }
4467 else {
4468 if (min)
4469 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004470 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004471 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004472 ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4473 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004474 cfgerr += 1;
4475 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004476
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004477#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004478 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004479 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004480 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004481 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004482 else
4483 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4484 if (flags & methodVersions[i].flag)
4485 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004486#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004487 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004488 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4489 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004490#endif
4491
4492 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4493 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004494 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004495
Willy Tarreau5db847a2019-05-09 14:13:35 +02004496#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004497 if (global_ssl.async)
4498 mode |= SSL_MODE_ASYNC;
4499#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004500 SSL_CTX_set_mode(ctx, mode);
4501 srv->ssl_ctx.ctx = ctx;
4502
Emeric Bruna7aa3092012-10-26 12:58:00 +02004503 if (srv->ssl_ctx.client_crt) {
4504 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 +01004505 ha_alert("config : %s '%s', server '%s': unable to load SSL private key from PEM file '%s'.\n",
4506 proxy_type_str(curproxy), curproxy->id,
4507 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004508 cfgerr++;
4509 }
4510 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 +01004511 ha_alert("config : %s '%s', server '%s': unable to load ssl certificate from PEM file '%s'.\n",
4512 proxy_type_str(curproxy), curproxy->id,
4513 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004514 cfgerr++;
4515 }
4516 else if (SSL_CTX_check_private_key(srv->ssl_ctx.ctx) <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004517 ha_alert("config : %s '%s', server '%s': inconsistencies between private key and certificate loaded from PEM file '%s'.\n",
4518 proxy_type_str(curproxy), curproxy->id,
4519 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004520 cfgerr++;
4521 }
4522 }
Emeric Brun94324a42012-10-11 14:00:19 +02004523
Emeric Brun850efd52014-01-29 12:24:34 +01004524 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4525 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004526 switch (srv->ssl_ctx.verify) {
4527 case SSL_SOCK_VERIFY_NONE:
4528 verify = SSL_VERIFY_NONE;
4529 break;
4530 case SSL_SOCK_VERIFY_REQUIRED:
4531 verify = SSL_VERIFY_PEER;
4532 break;
4533 }
Evan Broderbe554312013-06-27 00:05:25 -07004534 SSL_CTX_set_verify(srv->ssl_ctx.ctx,
Emeric Brun850efd52014-01-29 12:24:34 +01004535 verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004536 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004537 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004538 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004539 /* set CAfile to verify */
4540 if (!ssl_set_verify_locations_file(srv->ssl_ctx.ctx, srv->ssl_ctx.ca_file)) {
4541 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to set CA file '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004542 curproxy->id, srv->id,
4543 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004544 cfgerr++;
4545 }
4546 }
Emeric Brun850efd52014-01-29 12:24:34 +01004547 else {
4548 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Christopher Faulet767a84b2017-11-24 16:50:31 +01004549 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",
4550 curproxy->id, srv->id,
4551 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004552 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01004553 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4554 curproxy->id, srv->id,
4555 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004556 cfgerr++;
4557 }
Emeric Brunef42d922012-10-11 16:11:36 +02004558#ifdef X509_V_FLAG_CRL_CHECK
4559 if (srv->ssl_ctx.crl_file) {
4560 X509_STORE *store = SSL_CTX_get_cert_store(srv->ssl_ctx.ctx);
4561
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004562 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004563 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4564 curproxy->id, srv->id,
4565 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004566 cfgerr++;
4567 }
4568 else {
4569 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4570 }
4571 }
4572#endif
4573 }
4574
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004575 SSL_CTX_set_session_cache_mode(srv->ssl_ctx.ctx, SSL_SESS_CACHE_CLIENT |
4576 SSL_SESS_CACHE_NO_INTERNAL_STORE);
4577 SSL_CTX_sess_set_new_cb(srv->ssl_ctx.ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004578 if (srv->ssl_ctx.ciphers &&
4579 !SSL_CTX_set_cipher_list(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphers)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004580 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4581 curproxy->id, srv->id,
4582 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004583 cfgerr++;
4584 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004585
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004586#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004587 if (srv->ssl_ctx.ciphersuites &&
Pierre Cheynierbc34cd12019-03-21 16:15:47 +00004588 !SSL_CTX_set_ciphersuites(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphersuites)) {
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004589 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4590 curproxy->id, srv->id,
4591 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4592 cfgerr++;
4593 }
4594#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004595#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4596 if (srv->ssl_ctx.npn_str)
4597 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, srv);
4598#endif
4599#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4600 if (srv->ssl_ctx.alpn_str)
4601 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4602#endif
4603
Emeric Brun94324a42012-10-11 14:00:19 +02004604
4605 return cfgerr;
4606}
4607
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004608/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004609 * be NULL, in which case nothing is done. Returns the number of errors
4610 * encountered.
4611 */
Willy Tarreau03209342016-12-22 17:08:28 +01004612int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004613{
4614 struct ebmb_node *node;
4615 struct sni_ctx *sni;
4616 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004617 int errcode = 0;
4618 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004619
Willy Tarreaufce03112015-01-15 21:32:40 +01004620 /* Automatic memory computations need to know we use SSL there */
4621 global.ssl_used_frontend = 1;
4622
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004623 /* Make sure openssl opens /dev/urandom before the chroot */
4624 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004625 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004626 err++;
4627 }
4628 /* Create initial_ctx used to start the ssl connection before do switchctx */
4629 if (!bind_conf->initial_ctx) {
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004630 err += ssl_sock_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004631 /* It should not be necessary to call this function, but it's
4632 necessary first to check and move all initialisation related
4633 to initial_ctx in ssl_sock_initial_ctx. */
William Lallemand8b453912019-11-21 15:48:10 +01004634 errcode |= ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004635 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004636 if (bind_conf->default_ctx)
William Lallemand8b453912019-11-21 15:48:10 +01004637 errcode |= ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, &errmsg);
Emeric Brun0bed9942014-10-30 19:25:24 +01004638
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004639 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004640 while (node) {
4641 sni = ebmb_entry(node, struct sni_ctx, name);
Emeric Brun0bed9942014-10-30 19:25:24 +01004642 if (!sni->order && sni->ctx != bind_conf->default_ctx)
4643 /* only initialize the CTX on its first occurrence and
4644 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004645 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004646 node = ebmb_next(node);
4647 }
4648
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004649 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004650 while (node) {
4651 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004652 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004653 /* only initialize the CTX on its first occurrence and
4654 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004655 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
4656 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004657 node = ebmb_next(node);
4658 }
William Lallemand8b453912019-11-21 15:48:10 +01004659
4660 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004661 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004662 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004663 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004664 err++;
4665 }
4666
4667 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004668 return err;
4669}
4670
Willy Tarreau55d37912016-12-21 23:38:39 +01004671/* Prepares all the contexts for a bind_conf and allocates the shared SSL
4672 * context if needed. Returns < 0 on error, 0 on success. The warnings and
4673 * alerts are directly emitted since the rest of the stack does it below.
4674 */
4675int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
4676{
4677 struct proxy *px = bind_conf->frontend;
4678 int alloc_ctx;
4679 int err;
4680
4681 if (!bind_conf->is_ssl) {
4682 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004683 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
4684 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01004685 }
4686 return 0;
4687 }
4688 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004689 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004690 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
4691 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004692 }
4693 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004694 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
4695 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004696 return -1;
4697 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004698 }
William Lallemandc61c0b32017-12-04 18:46:39 +01004699 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004700 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02004701 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01004702 sizeof(*sh_ssl_sess_tree),
4703 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02004704 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004705 if (alloc_ctx == SHCTX_E_INIT_LOCK)
4706 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");
4707 else
4708 ha_alert("Unable to allocate SSL session cache.\n");
4709 return -1;
4710 }
4711 /* free block callback */
4712 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
4713 /* init the root tree within the extra space */
4714 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
4715 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01004716 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004717 err = 0;
4718 /* initialize all certificate contexts */
4719 err += ssl_sock_prepare_all_ctx(bind_conf);
4720
4721 /* initialize CA variables if the certificates generation is enabled */
4722 err += ssl_sock_load_ca(bind_conf);
4723
4724 return -err;
4725}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004726
4727/* release ssl context allocated for servers. */
4728void ssl_sock_free_srv_ctx(struct server *srv)
4729{
Olivier Houchardc7566002018-11-20 23:33:50 +01004730#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4731 if (srv->ssl_ctx.alpn_str)
4732 free(srv->ssl_ctx.alpn_str);
4733#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01004734#ifdef OPENSSL_NPN_NEGOTIATED
Olivier Houchardc7566002018-11-20 23:33:50 +01004735 if (srv->ssl_ctx.npn_str)
4736 free(srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01004737#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02004738 if (srv->ssl_ctx.reused_sess) {
4739 int i;
4740
4741 for (i = 0; i < global.nbthread; i++)
4742 free(srv->ssl_ctx.reused_sess[i].ptr);
4743 free(srv->ssl_ctx.reused_sess);
4744 }
4745
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004746 if (srv->ssl_ctx.ctx)
4747 SSL_CTX_free(srv->ssl_ctx.ctx);
4748}
4749
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004750/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004751 * be NULL, in which case nothing is done. The default_ctx is nullified too.
4752 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004753void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004754{
4755 struct ebmb_node *node, *back;
4756 struct sni_ctx *sni;
4757
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004758 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004759 while (node) {
4760 sni = ebmb_entry(node, struct sni_ctx, name);
4761 back = ebmb_next(node);
4762 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004763 SSL_CTX_free(sni->ctx);
William Lallemandb2408692020-06-24 09:54:29 +02004764 LIST_DEL(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004765 free(sni);
4766 node = back;
4767 }
4768
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004769 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004770 while (node) {
4771 sni = ebmb_entry(node, struct sni_ctx, name);
4772 back = ebmb_next(node);
4773 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004774 SSL_CTX_free(sni->ctx);
William Lallemandb2408692020-06-24 09:54:29 +02004775 LIST_DEL(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004776 free(sni);
4777 node = back;
4778 }
William Lallemandb2408692020-06-24 09:54:29 +02004779
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004780 SSL_CTX_free(bind_conf->initial_ctx);
4781 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02004782 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004783 bind_conf->default_ctx = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004784 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02004785}
William Lallemandb2408692020-06-24 09:54:29 +02004786
4787
4788void ssl_sock_deinit()
4789{
4790 crtlist_deinit(); /* must be free'd before the ckchs */
4791 ckch_deinit();
4792}
4793REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02004794
Willy Tarreau795cdab2016-12-22 17:30:54 +01004795/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
4796void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
4797{
4798 ssl_sock_free_ca(bind_conf);
4799 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004800 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01004801 free(bind_conf->ca_sign_file);
4802 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02004803 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01004804 free(bind_conf->keys_ref->filename);
4805 free(bind_conf->keys_ref->tlskeys);
4806 LIST_DEL(&bind_conf->keys_ref->list);
4807 free(bind_conf->keys_ref);
4808 }
4809 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004810 bind_conf->ca_sign_pass = NULL;
4811 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004812}
4813
Christopher Faulet31af49d2015-06-09 17:29:50 +02004814/* Load CA cert file and private key used to generate certificates */
4815int
Willy Tarreau03209342016-12-22 17:08:28 +01004816ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02004817{
Willy Tarreau03209342016-12-22 17:08:28 +01004818 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03004819 struct cert_key_and_chain *ckch = NULL;
4820 int ret = 0;
4821 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004822
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02004823 if (!bind_conf->generate_certs)
Shimi Gersner5846c492020-08-23 13:58:12 +03004824 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004825
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01004826#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02004827 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01004828 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004829 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02004830 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004831 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02004832#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02004833
Christopher Faulet31af49d2015-06-09 17:29:50 +02004834 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004835 ha_alert("Proxy '%s': cannot enable certificate generation, "
4836 "no CA certificate File configured at [%s:%d].\n",
4837 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03004838 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004839 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004840
Shimi Gersner5846c492020-08-23 13:58:12 +03004841 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02004842 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03004843 if (!ckch) {
4844 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
4845 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
4846 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004847 }
Shimi Gersner5846c492020-08-23 13:58:12 +03004848
4849 /* Try to parse file */
4850 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
4851 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
4852 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
4853 if (err) free(err);
4854 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004855 }
Shimi Gersner5846c492020-08-23 13:58:12 +03004856
4857 /* Fail if missing cert or pkey */
4858 if ((!ckch->cert) || (!ckch->key)) {
4859 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
4860 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
4861 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004862 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004863
Shimi Gersner5846c492020-08-23 13:58:12 +03004864 /* Final assignment to bind */
4865 bind_conf->ca_sign_ckch = ckch;
4866 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004867
Shimi Gersner5846c492020-08-23 13:58:12 +03004868 failed:
4869 if (ckch) {
4870 ssl_sock_free_cert_key_and_chain_contents(ckch);
4871 free(ckch);
4872 }
4873
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004874 bind_conf->generate_certs = 0;
Shimi Gersner5846c492020-08-23 13:58:12 +03004875 ret++;
4876 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004877}
4878
4879/* Release CA cert and private key used to generate certificated */
4880void
4881ssl_sock_free_ca(struct bind_conf *bind_conf)
4882{
Shimi Gersner5846c492020-08-23 13:58:12 +03004883 if (bind_conf->ca_sign_ckch) {
4884 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
4885 free(bind_conf->ca_sign_ckch);
4886 bind_conf->ca_sign_ckch = NULL;
4887 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004888}
4889
Emeric Brun46591952012-05-18 15:47:34 +02004890/*
4891 * This function is called if SSL * context is not yet allocated. The function
4892 * is designed to be called before any other data-layer operation and sets the
4893 * handshake flag on the connection. It is safe to call it multiple times.
4894 * It returns 0 on success and -1 in error case.
4895 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004896static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004897{
Olivier Houchard66ab4982019-02-26 18:37:15 +01004898 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02004899 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004900 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004901 return 0;
4902
Willy Tarreau3c728722014-01-23 13:50:42 +01004903 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02004904 return 0;
4905
Olivier Houchard66ab4982019-02-26 18:37:15 +01004906 ctx = pool_alloc(ssl_sock_ctx_pool);
4907 if (!ctx) {
4908 conn->err_code = CO_ER_SSL_NO_MEM;
4909 return -1;
4910 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004911 ctx->wait_event.tasklet = tasklet_new();
4912 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004913 conn->err_code = CO_ER_SSL_NO_MEM;
4914 pool_free(ssl_sock_ctx_pool, ctx);
4915 return -1;
4916 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004917 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
4918 ctx->wait_event.tasklet->context = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004919 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01004920 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01004921 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004922 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01004923 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02004924 ctx->xprt_st = 0;
4925 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004926
4927 /* Only work with sockets for now, this should be adapted when we'll
4928 * add QUIC support.
4929 */
4930 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02004931 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004932 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
4933 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02004934 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01004935
Willy Tarreau20879a02012-12-03 16:32:10 +01004936 if (global.maxsslconn && sslconns >= global.maxsslconn) {
4937 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004938 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004939 }
Willy Tarreau403edff2012-09-06 11:58:37 +02004940
Emeric Brun46591952012-05-18 15:47:34 +02004941 /* If it is in client mode initiate SSL session
4942 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01004943 if (objt_server(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004944 int may_retry = 1;
4945
4946 retry_connect:
Emeric Brun46591952012-05-18 15:47:34 +02004947 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004948 ctx->ssl = SSL_new(__objt_server(conn->target)->ssl_ctx.ctx);
4949 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004950 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004951 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004952 goto retry_connect;
4953 }
Willy Tarreau20879a02012-12-03 16:32:10 +01004954 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004955 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004956 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004957 ctx->bio = BIO_new(ha_meth);
4958 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01004959 SSL_free(ctx->ssl);
4960 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004961 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004962 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004963 goto retry_connect;
4964 }
Emeric Brun55476152014-11-12 17:35:37 +01004965 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004966 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004967 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004968 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02004969 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02004970
Evan Broderbe554312013-06-27 00:05:25 -07004971 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004972 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
4973 SSL_free(ctx->ssl);
4974 ctx->ssl = NULL;
Emeric Brun55476152014-11-12 17:35:37 +01004975 conn->xprt_ctx = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004976 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004977 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004978 goto retry_connect;
4979 }
Emeric Brun55476152014-11-12 17:35:37 +01004980 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004981 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004982 }
4983
Olivier Houchard66ab4982019-02-26 18:37:15 +01004984 SSL_set_connect_state(ctx->ssl);
Willy Tarreau07d94e42018-09-20 10:57:52 +02004985 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
4986 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
4987 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 +01004988 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004989 SSL_SESSION_free(sess);
Willy Tarreau07d94e42018-09-20 10:57:52 +02004990 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
4991 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004992 } else if (sess) {
4993 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01004994 }
4995 }
Evan Broderbe554312013-06-27 00:05:25 -07004996
Emeric Brun46591952012-05-18 15:47:34 +02004997 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02004998 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02004999
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005000 _HA_ATOMIC_ADD(&sslconns, 1);
5001 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005002 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005003 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005004 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005005 return 0;
5006 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005007 else if (objt_listener(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005008 int may_retry = 1;
5009
5010 retry_accept:
Emeric Brun46591952012-05-18 15:47:34 +02005011 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005012 ctx->ssl = SSL_new(__objt_listener(conn->target)->bind_conf->initial_ctx);
5013 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005014 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005015 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005016 goto retry_accept;
5017 }
Willy Tarreau20879a02012-12-03 16:32:10 +01005018 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005019 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005020 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005021 ctx->bio = BIO_new(ha_meth);
5022 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01005023 SSL_free(ctx->ssl);
5024 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005025 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005026 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005027 goto retry_accept;
5028 }
Emeric Brun55476152014-11-12 17:35:37 +01005029 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005030 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005031 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005032 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02005033 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02005034
Emeric Brune1f38db2012-09-03 20:36:47 +02005035 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005036 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
5037 SSL_free(ctx->ssl);
5038 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005039 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005040 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005041 goto retry_accept;
5042 }
Emeric Brun55476152014-11-12 17:35:37 +01005043 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005044 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005045 }
5046
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005047#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005048 if (__objt_listener(conn->target)->bind_conf->ssl_conf.early_data) {
5049 b_alloc(&ctx->early_buf);
5050 SSL_set_max_early_data(ctx->ssl,
5051 /* Only allow early data if we managed to allocate
5052 * a buffer.
5053 */
5054 (!b_is_null(&ctx->early_buf)) ?
5055 global.tune.bufsize - global.tune.maxrewrite : 0);
5056 }
5057#endif
5058
Olivier Houchard66ab4982019-02-26 18:37:15 +01005059 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005060
Emeric Brun46591952012-05-18 15:47:34 +02005061 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005062 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005063#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreau5c6176d2021-02-05 10:24:54 +01005064 if (__objt_listener(conn->target)->bind_conf->ssl_conf.early_data)
Willy Tarreau5930fb22021-02-03 11:21:38 +01005065 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005066#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005067
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005068 _HA_ATOMIC_ADD(&sslconns, 1);
5069 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005070 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005071 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005072 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005073 return 0;
5074 }
5075 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005076 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005077err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005078 if (ctx && ctx->wait_event.tasklet)
5079 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005080 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005081 return -1;
5082}
5083
5084
5085/* This is the callback which is used when an SSL handshake is pending. It
5086 * updates the FD status if it wants some polling before being called again.
5087 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5088 * otherwise it returns non-zero and removes itself from the connection's
5089 * flags (the bit is provided in <flag> by the caller).
5090 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005091static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005092{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005093 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005094 int ret;
Willy Tarreaud2871402021-02-02 15:42:25 +01005095 socklen_t lskerr;
5096 int skerr;
5097
Emeric Brun46591952012-05-18 15:47:34 +02005098
Willy Tarreau3c728722014-01-23 13:50:42 +01005099 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005100 return 0;
5101
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005102 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005103 goto out_error;
5104
Willy Tarreaud2871402021-02-02 15:42:25 +01005105 /* don't start calculating a handshake on a dead connection */
5106 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5107 goto out_error;
5108
5109 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5110 * status from the lower layers, so let's check the FD directly. Ideally
5111 * the xprt layers should provide some status indicating their knowledge
5112 * of shutdowns or error.
5113 */
5114 skerr = 0;
5115 lskerr = sizeof(skerr);
5116 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5117 skerr != 0)
5118 goto out_error;
5119
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005120#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005121 /*
5122 * Check if we have early data. If we do, we have to read them
5123 * before SSL_do_handshake() is called, And there's no way to
5124 * detect early data, except to try to read them
5125 */
5126 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005127 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005128
Olivier Houchard54907bb2019-12-19 15:02:39 +01005129 while (1) {
5130 ret = SSL_read_early_data(ctx->ssl,
5131 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5132 &read_data);
5133 if (ret == SSL_READ_EARLY_DATA_ERROR)
5134 goto check_error;
5135 if (read_data > 0) {
5136 conn->flags |= CO_FL_EARLY_DATA;
5137 b_add(&ctx->early_buf, read_data);
5138 }
5139 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5140 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5141 if (!b_data(&ctx->early_buf))
5142 b_free(&ctx->early_buf);
5143 break;
5144 }
5145 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005146 }
5147#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005148 /* If we use SSL_do_handshake to process a reneg initiated by
5149 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5150 * Usually SSL_write and SSL_read are used and process implicitly
5151 * the reneg handshake.
5152 * Here we use SSL_peek as a workaround for reneg.
5153 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005154 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005155 char c;
5156
Olivier Houchard66ab4982019-02-26 18:37:15 +01005157 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005158 if (ret <= 0) {
5159 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005160 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005161
Emeric Brun674b7432012-11-08 19:21:55 +01005162 if (ret == SSL_ERROR_WANT_WRITE) {
5163 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005164 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005165 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005166 return 0;
5167 }
5168 else if (ret == SSL_ERROR_WANT_READ) {
5169 /* handshake may have been completed but we have
5170 * no more data to read.
5171 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005172 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005173 ret = 1;
5174 goto reneg_ok;
5175 }
5176 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005177 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005178 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005179 return 0;
5180 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005181#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005182 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005183 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005184 return 0;
5185 }
5186#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005187 else if (ret == SSL_ERROR_SYSCALL) {
5188 /* if errno is null, then connection was successfully established */
5189 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5190 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005191 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005192#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5193 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005194 conn->err_code = CO_ER_SSL_HANDSHAKE;
5195#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005196 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005197#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005198 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005199 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005200 empty_handshake = state == TLS_ST_BEFORE;
5201#else
Lukas Tribus49799162019-07-08 14:29:15 +02005202 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5203 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005204#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005205 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005206 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005207 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005208 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5209 else
5210 conn->err_code = CO_ER_SSL_EMPTY;
5211 }
5212 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005213 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005214 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5215 else
5216 conn->err_code = CO_ER_SSL_ABORT;
5217 }
5218 }
5219 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005220 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005221 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005222 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005223 conn->err_code = CO_ER_SSL_HANDSHAKE;
5224 }
Lukas Tribus49799162019-07-08 14:29:15 +02005225#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005226 }
Emeric Brun674b7432012-11-08 19:21:55 +01005227 goto out_error;
5228 }
5229 else {
5230 /* Fail on all other handshake errors */
5231 /* Note: OpenSSL may leave unread bytes in the socket's
5232 * buffer, causing an RST to be emitted upon close() on
5233 * TCP sockets. We first try to drain possibly pending
5234 * data to avoid this as much as possible.
5235 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005236 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005237 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005238 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005239 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005240 goto out_error;
5241 }
5242 }
5243 /* read some data: consider handshake completed */
5244 goto reneg_ok;
5245 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005246 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005247check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005248 if (ret != 1) {
5249 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005250 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005251
5252 if (ret == SSL_ERROR_WANT_WRITE) {
5253 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005254 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005255 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005256 return 0;
5257 }
5258 else if (ret == SSL_ERROR_WANT_READ) {
5259 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005260 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005261 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5262 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005263 return 0;
5264 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005265#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005266 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005267 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005268 return 0;
5269 }
5270#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005271 else if (ret == SSL_ERROR_SYSCALL) {
5272 /* if errno is null, then connection was successfully established */
5273 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5274 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005275 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005276#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5277 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005278 conn->err_code = CO_ER_SSL_HANDSHAKE;
5279#else
5280 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005281#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005282 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005283 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005284 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005285#else
Lukas Tribus49799162019-07-08 14:29:15 +02005286 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5287 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005288#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005289 if (empty_handshake) {
5290 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005291 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005292 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5293 else
5294 conn->err_code = CO_ER_SSL_EMPTY;
5295 }
5296 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005297 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005298 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5299 else
5300 conn->err_code = CO_ER_SSL_ABORT;
5301 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005302 }
5303 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005304 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005305 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5306 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005307 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005308 }
Lukas Tribus49799162019-07-08 14:29:15 +02005309#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005310 }
Willy Tarreau89230192012-09-28 20:22:13 +02005311 goto out_error;
5312 }
Emeric Brun46591952012-05-18 15:47:34 +02005313 else {
5314 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005315 /* Note: OpenSSL may leave unread bytes in the socket's
5316 * buffer, causing an RST to be emitted upon close() on
5317 * TCP sockets. We first try to drain possibly pending
5318 * data to avoid this as much as possible.
5319 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005320 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005321 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005322 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005323 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005324 goto out_error;
5325 }
5326 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005327#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005328 else {
5329 /*
5330 * If the server refused the early data, we have to send a
5331 * 425 to the client, as we no longer have the data to sent
5332 * them again.
5333 */
5334 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005335 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005336 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5337 goto out_error;
5338 }
5339 }
5340 }
5341#endif
5342
Emeric Brun46591952012-05-18 15:47:34 +02005343
Emeric Brun674b7432012-11-08 19:21:55 +01005344reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005345
Willy Tarreau5db847a2019-05-09 14:13:35 +02005346#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005347 /* ASYNC engine API doesn't support moving read/write
5348 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005349 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005350 */
5351 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005352 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005353#endif
Emeric Brun46591952012-05-18 15:47:34 +02005354 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005355 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005356 if (objt_server(conn->target)) {
5357 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5358 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5359 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005360 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005361 else {
5362 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5363 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5364 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5365 }
Emeric Brun46591952012-05-18 15:47:34 +02005366 }
5367
5368 /* The connection is now established at both layers, it's time to leave */
5369 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5370 return 1;
5371
5372 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005373 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005374 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005375 ERR_clear_error();
5376
Emeric Brun9fa89732012-10-04 17:09:56 +02005377 /* free resumed session if exists */
Willy Tarreau07d94e42018-09-20 10:57:52 +02005378 if (objt_server(conn->target) && __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5379 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
5380 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Emeric Brun9fa89732012-10-04 17:09:56 +02005381 }
5382
Emeric Brun46591952012-05-18 15:47:34 +02005383 /* Fail on all other handshake errors */
5384 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005385 if (!conn->err_code)
5386 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005387 return 0;
5388}
5389
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005390/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5391 * event subscriber <es> is not allowed to change from a previous call as long
5392 * as at least one event is still subscribed. The <event_type> must only be a
5393 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5394 * unless the transport layer was already released.
5395 */
5396static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005397{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005398 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005399
Olivier Houchard0ff28652019-06-24 18:57:39 +02005400 if (!ctx)
5401 return -1;
5402
Willy Tarreau113d52b2020-01-10 09:20:26 +01005403 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005404 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005405
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005406 ctx->subs = es;
5407 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005408
5409 /* we may have to subscribe to lower layers for new events */
5410 event_type &= ~ctx->wait_event.events;
5411 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5412 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005413 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005414}
5415
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005416/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5417 * The <es> pointer is not allowed to differ from the one passed to the
5418 * subscribe() call. It always returns zero.
5419 */
5420static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005421{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005422 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005423
Willy Tarreau113d52b2020-01-10 09:20:26 +01005424 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005425 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005426
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005427 es->events &= ~event_type;
5428 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005429 ctx->subs = NULL;
5430
5431 /* If we subscribed, and we're not doing the handshake,
5432 * then we subscribed because the upper layer asked for it,
5433 * as the upper layer is no longer interested, we can
5434 * unsubscribe too.
5435 */
5436 event_type &= ctx->wait_event.events;
5437 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5438 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005439
5440 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005441}
5442
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005443/* The connection has been taken over, so destroy the old tasklet and create
5444 * a new one. The original thread ID must be passed into orig_tid
5445 * It should be called with the takeover lock for the old thread held.
5446 * Returns 0 on success, and -1 on failure
5447 */
5448static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
5449{
5450 struct ssl_sock_ctx *ctx = xprt_ctx;
5451 struct tasklet *tl = tasklet_new();
5452
5453 if (!tl)
5454 return -1;
5455
5456 ctx->wait_event.tasklet->context = NULL;
5457 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
5458 ctx->wait_event.tasklet = tl;
5459 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5460 ctx->wait_event.tasklet->context = ctx;
5461 return 0;
5462}
5463
Olivier Houchard2e055482019-05-27 19:50:12 +02005464/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5465 * Returns 0 on success, and non-zero on failure.
5466 */
5467static 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)
5468{
5469 struct ssl_sock_ctx *ctx = xprt_ctx;
5470
5471 if (oldxprt_ops != NULL)
5472 *oldxprt_ops = ctx->xprt;
5473 if (oldxprt_ctx != NULL)
5474 *oldxprt_ctx = ctx->xprt_ctx;
5475 ctx->xprt = toadd_ops;
5476 ctx->xprt_ctx = toadd_ctx;
5477 return 0;
5478}
5479
Olivier Houchard5149b592019-05-23 17:47:36 +02005480/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5481 * return 0, otherwise just call the remove_xprt method from the underlying
5482 * XPRT.
5483 */
5484static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5485{
5486 struct ssl_sock_ctx *ctx = xprt_ctx;
5487
5488 if (ctx->xprt_ctx == toremove_ctx) {
5489 ctx->xprt_ctx = newctx;
5490 ctx->xprt = newops;
5491 return 0;
5492 }
5493 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5494}
5495
Willy Tarreau9a5a0e02021-01-20 14:55:01 +01005496struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned short state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02005497{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005498 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005499 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005500 struct connection *conn;
5501 int conn_in_list;
5502 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005503
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005504 HA_SPIN_LOCK(OTHER_LOCK, &idle_conns[tid].takeover_lock);
5505 if (tl->context == NULL) {
5506 HA_SPIN_UNLOCK(OTHER_LOCK, &idle_conns[tid].takeover_lock);
5507 tasklet_free(tl);
5508 return NULL;
5509 }
5510 conn = ctx->conn;
5511 conn_in_list = conn->flags & CO_FL_LIST_MASK;
5512 if (conn_in_list)
5513 MT_LIST_DEL(&conn->list);
5514 HA_SPIN_UNLOCK(OTHER_LOCK, &idle_conns[tid].takeover_lock);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005515 /* First if we're doing an handshake, try that */
5516 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS)
5517 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
5518 /* If we had an error, or the handshake is done and I/O is available,
5519 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005520 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005521 * we can't be sure conn_fd_handler() will be called again.
5522 */
5523 if ((ctx->conn->flags & CO_FL_ERROR) ||
5524 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005525 int woke = 0;
5526
5527 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005528 if (ctx->subs) {
5529 tasklet_wakeup(ctx->subs->tasklet);
5530 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005531 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005532 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005533 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005534
Olivier Houchardea8dd942019-05-20 14:02:16 +02005535 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005536 * upper layers know. If we have no mux, create it,
5537 * and once we have a mux, call its wake method if we didn't
5538 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005539 */
5540 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005541 if (!ctx->conn->mux)
5542 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005543 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005544 ret = ctx->conn->mux->wake(ctx->conn);
5545 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005546 }
5547 }
Olivier Houchard54907bb2019-12-19 15:02:39 +01005548#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5549 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005550 else if (b_data(&ctx->early_buf) && ctx->subs &&
5551 ctx->subs->events & SUB_RETRY_RECV) {
5552 tasklet_wakeup(ctx->subs->tasklet);
5553 ctx->subs->events &= ~SUB_RETRY_RECV;
5554 if (!ctx->subs->events)
5555 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005556 }
5557#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005558leave:
5559 if (!ret && conn_in_list) {
5560 struct server *srv = objt_server(conn->target);
5561
5562 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreaua9d7b762020-07-10 08:28:20 +02005563 MT_LIST_ADDQ(&srv->safe_conns[tid], &conn->list);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005564 else
Willy Tarreaua9d7b762020-07-10 08:28:20 +02005565 MT_LIST_ADDQ(&srv->idle_conns[tid], &conn->list);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005566 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005567 return NULL;
5568}
5569
Emeric Brun46591952012-05-18 15:47:34 +02005570/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01005571 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02005572 * buffer wraps, in which case a second call may be performed. The connection's
5573 * flags are updated with whatever special event is detected (error, read0,
5574 * empty). The caller is responsible for taking care of those events and
5575 * avoiding the call if inappropriate. The function does not call the
5576 * connection's polling update function, so the caller is responsible for this.
5577 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005578static 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 +02005579{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005580 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02005581 ssize_t ret;
5582 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02005583
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005584 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005585 goto out_error;
5586
Olivier Houchard54907bb2019-12-19 15:02:39 +01005587#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5588 if (b_data(&ctx->early_buf)) {
5589 try = b_contig_space(buf);
5590 if (try > b_data(&ctx->early_buf))
5591 try = b_data(&ctx->early_buf);
5592 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
5593 b_add(buf, try);
5594 b_del(&ctx->early_buf, try);
5595 if (b_data(&ctx->early_buf) == 0)
5596 b_free(&ctx->early_buf);
5597 return try;
5598 }
5599#endif
5600
Willy Tarreau911db9b2020-01-23 16:27:54 +01005601 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005602 /* a handshake was requested */
5603 return 0;
5604
Emeric Brun46591952012-05-18 15:47:34 +02005605 /* read the largest possible block. For this, we perform only one call
5606 * to recv() unless the buffer wraps and we exactly fill the first hunk,
5607 * in which case we accept to do it once again. A new attempt is made on
5608 * EINTR too.
5609 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01005610 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005611
Willy Tarreau591d4452018-06-15 17:21:00 +02005612 try = b_contig_space(buf);
5613 if (!try)
5614 break;
5615
Willy Tarreauabf08d92014-01-14 11:31:27 +01005616 if (try > count)
5617 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02005618
Olivier Houchard66ab4982019-02-26 18:37:15 +01005619 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005620
Emeric Brune1f38db2012-09-03 20:36:47 +02005621 if (conn->flags & CO_FL_ERROR) {
5622 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005623 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005624 }
Emeric Brun46591952012-05-18 15:47:34 +02005625 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02005626 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005627 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005628 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005629 }
Emeric Brun46591952012-05-18 15:47:34 +02005630 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005631 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005632 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005633 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02005634 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005635 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005636#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005637 /* Async mode can be re-enabled, because we're leaving data state.*/
5638 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005639 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005640#endif
Emeric Brun46591952012-05-18 15:47:34 +02005641 break;
5642 }
5643 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005644 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005645 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5646 SUB_RETRY_RECV,
5647 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01005648 /* handshake is running, and it may need to re-enable read */
5649 conn->flags |= CO_FL_SSL_WAIT_HS;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005650#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005651 /* Async mode can be re-enabled, because we're leaving data state.*/
5652 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005653 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005654#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005655 break;
5656 }
Emeric Brun46591952012-05-18 15:47:34 +02005657 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005658 } else if (ret == SSL_ERROR_ZERO_RETURN)
5659 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005660 /* For SSL_ERROR_SYSCALL, make sure to clear the error
5661 * stack before shutting down the connection for
5662 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005663 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
5664 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02005665 /* otherwise it's a real error */
5666 goto out_error;
5667 }
5668 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005669 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005670 return done;
5671
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005672 clear_ssl_error:
5673 /* Clear openssl global errors stack */
5674 ssl_sock_dump_errors(conn);
5675 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02005676 read0:
5677 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005678 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005679
Emeric Brun46591952012-05-18 15:47:34 +02005680 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005681 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01005682 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005683 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005684 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005685 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005686}
5687
5688
Willy Tarreau787db9a2018-06-14 18:31:46 +02005689/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
5690 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
5691 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02005692 * Only one call to send() is performed, unless the buffer wraps, in which case
5693 * a second call may be performed. The connection's flags are updated with
5694 * whatever special event is detected (error, empty). The caller is responsible
5695 * for taking care of those events and avoiding the call if inappropriate. The
5696 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02005697 * is responsible for this. The buffer's output is not adjusted, it's up to the
5698 * caller to take care of this. It's up to the caller to update the buffer's
5699 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02005700 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005701static 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 +02005702{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005703 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005704 ssize_t ret;
5705 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02005706
5707 done = 0;
5708
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005709 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005710 goto out_error;
5711
Willy Tarreau911db9b2020-01-23 16:27:54 +01005712 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005713 /* a handshake was requested */
5714 return 0;
5715
5716 /* send the largest possible block. For this we perform only one call
5717 * to send() unless the buffer wraps and we exactly fill the first hunk,
5718 * in which case we accept to do it once again.
5719 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02005720 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005721#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005722 size_t written_data;
5723#endif
5724
Willy Tarreau787db9a2018-06-14 18:31:46 +02005725 try = b_contig_data(buf, done);
5726 if (try > count)
5727 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01005728
Willy Tarreau7bed9452014-02-02 02:00:24 +01005729 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005730 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01005731 global_ssl.max_record && try > global_ssl.max_record) {
5732 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005733 }
5734 else {
5735 /* we need to keep the information about the fact that
5736 * we're not limiting the upcoming send(), because if it
5737 * fails, we'll have to retry with at least as many data.
5738 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005739 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005740 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01005741
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005742#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02005743 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005744 unsigned int max_early;
5745
Olivier Houchard522eea72017-11-03 16:27:47 +01005746 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01005747 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01005748 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005749 if (SSL_get0_session(ctx->ssl))
5750 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01005751 else
5752 max_early = 0;
5753 }
5754
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005755 if (try + ctx->sent_early_data > max_early) {
5756 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01005757 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02005758 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005759 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005760 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01005761 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005762 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005763 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005764 if (ret == 1) {
5765 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005766 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005767 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005768 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005769 /* Initiate the handshake, now */
5770 tasklet_wakeup(ctx->wait_event.tasklet);
5771 }
Olivier Houchard522eea72017-11-03 16:27:47 +01005772
Olivier Houchardc2aae742017-09-22 18:26:28 +02005773 }
5774
5775 } else
5776#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005777 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01005778
Emeric Brune1f38db2012-09-03 20:36:47 +02005779 if (conn->flags & CO_FL_ERROR) {
5780 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005781 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005782 }
Emeric Brun46591952012-05-18 15:47:34 +02005783 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005784 /* A send succeeded, so we can consider ourself connected */
5785 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005786 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005787 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005788 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005789 }
5790 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005791 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005792
Emeric Brun46591952012-05-18 15:47:34 +02005793 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005794 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01005795 /* handshake is running, and it may need to re-enable write */
5796 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005797 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005798#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005799 /* Async mode can be re-enabled, because we're leaving data state.*/
5800 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005801 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005802#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005803 break;
5804 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005805
Emeric Brun46591952012-05-18 15:47:34 +02005806 break;
5807 }
5808 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005809 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02005810 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005811 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5812 SUB_RETRY_RECV,
5813 &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005814#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005815 /* Async mode can be re-enabled, because we're leaving data state.*/
5816 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005817 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005818#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005819 break;
5820 }
Emeric Brun46591952012-05-18 15:47:34 +02005821 goto out_error;
5822 }
5823 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005824 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005825 return done;
5826
5827 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005828 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005829 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005830 ERR_clear_error();
5831
Emeric Brun46591952012-05-18 15:47:34 +02005832 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005833 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005834}
5835
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005836static void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02005837
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005838 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005839
Olivier Houchardea8dd942019-05-20 14:02:16 +02005840
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005841 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005842 if (ctx->wait_event.events != 0)
5843 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
5844 ctx->wait_event.events,
5845 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01005846 if (ctx->subs) {
5847 ctx->subs->events = 0;
5848 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005849 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005850
Olivier Houchard692c1d02019-05-23 18:41:47 +02005851 if (ctx->xprt->close)
5852 ctx->xprt->close(conn, ctx->xprt_ctx);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005853#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +02005854 if (global_ssl.async) {
5855 OSSL_ASYNC_FD all_fd[32], afd;
5856 size_t num_all_fds = 0;
5857 int i;
5858
Olivier Houchard66ab4982019-02-26 18:37:15 +01005859 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005860 if (num_all_fds > 32) {
5861 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
5862 return;
5863 }
5864
Olivier Houchard66ab4982019-02-26 18:37:15 +01005865 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005866
5867 /* If an async job is pending, we must try to
5868 to catch the end using polling before calling
5869 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005870 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02005871 for (i=0 ; i < num_all_fds ; i++) {
5872 /* switch on an handler designed to
5873 * handle the SSL_free
5874 */
5875 afd = all_fd[i];
5876 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005877 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02005878 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00005879 /* To ensure that the fd cache won't be used
5880 * and we'll catch a real RD event.
5881 */
5882 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02005883 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005884 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005885 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005886 _HA_ATOMIC_ADD(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005887 return;
5888 }
Emeric Brun3854e012017-05-17 20:42:48 +02005889 /* Else we can remove the fds from the fdtab
5890 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02005891 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02005892 * because the fd is owned by the engine.
5893 * the engine is responsible to close
5894 */
5895 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +02005896 fd_stop_both(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005897 }
5898#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005899 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01005900 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005901 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005902 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005903 _HA_ATOMIC_SUB(&sslconns, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005904 }
Emeric Brun46591952012-05-18 15:47:34 +02005905}
5906
5907/* This function tries to perform a clean shutdown on an SSL connection, and in
5908 * any case, flags the connection as reusable if no handshake was in progress.
5909 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005910static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02005911{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005912 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005913
Willy Tarreau911db9b2020-01-23 16:27:54 +01005914 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005915 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01005916 if (!clean)
5917 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005918 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005919 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005920 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01005921 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005922 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005923 ERR_clear_error();
5924 }
Emeric Brun46591952012-05-18 15:47:34 +02005925}
5926
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01005927
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005928/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01005929int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
5930{
5931 struct ssl_sock_ctx *ctx;
5932 X509 *crt;
5933
5934 if (!ssl_sock_is_ssl(conn))
5935 return 0;
5936
5937 ctx = conn->xprt_ctx;
5938
5939 crt = SSL_get_certificate(ctx->ssl);
5940 if (!crt)
5941 return 0;
5942
5943 return cert_get_pkey_algo(crt, out);
5944}
5945
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005946/* used for ppv2 cert signature (can be used for logging) */
5947const char *ssl_sock_get_cert_sig(struct connection *conn)
5948{
Christopher Faulet82004142019-09-10 10:12:03 +02005949 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005950
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005951 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
5952 X509 *crt;
5953
5954 if (!ssl_sock_is_ssl(conn))
5955 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005956 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005957 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005958 if (!crt)
5959 return NULL;
5960 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
5961 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
5962}
5963
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005964/* used for ppv2 authority */
5965const char *ssl_sock_get_sni(struct connection *conn)
5966{
5967#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02005968 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005969
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005970 if (!ssl_sock_is_ssl(conn))
5971 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005972 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005973 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005974#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01005975 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005976#endif
5977}
5978
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005979/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005980const char *ssl_sock_get_cipher_name(struct connection *conn)
5981{
Christopher Faulet82004142019-09-10 10:12:03 +02005982 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005983
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005984 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005985 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005986 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005987 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005988}
5989
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005990/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005991const char *ssl_sock_get_proto_version(struct connection *conn)
5992{
Christopher Faulet82004142019-09-10 10:12:03 +02005993 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005994
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005995 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005996 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005997 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005998 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005999}
6000
Olivier Houchardab28a322018-12-21 19:45:40 +01006001void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6002{
6003#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02006004 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006005
Olivier Houcharde488ea82019-06-28 14:10:33 +02006006 if (!ssl_sock_is_ssl(conn))
6007 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006008 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006009 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006010#endif
6011}
6012
Willy Tarreau119a4082016-12-22 21:58:38 +01006013/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6014 * to disable SNI.
6015 */
Willy Tarreau63076412015-07-10 11:33:32 +02006016void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6017{
6018#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006019 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006020
Willy Tarreau119a4082016-12-22 21:58:38 +01006021 char *prev_name;
6022
Willy Tarreau63076412015-07-10 11:33:32 +02006023 if (!ssl_sock_is_ssl(conn))
6024 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006025 ctx = conn->xprt_ctx;
Willy Tarreau63076412015-07-10 11:33:32 +02006026
Willy Tarreau119a4082016-12-22 21:58:38 +01006027 /* if the SNI changes, we must destroy the reusable context so that a
6028 * new connection will present a new SNI. As an optimization we could
6029 * later imagine having a small cache of ssl_ctx to hold a few SNI per
6030 * server.
6031 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006032 prev_name = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau119a4082016-12-22 21:58:38 +01006033 if ((!prev_name && hostname) ||
6034 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006035 SSL_set_session(ctx->ssl, NULL);
Willy Tarreau119a4082016-12-22 21:58:38 +01006036
Olivier Houchard66ab4982019-02-26 18:37:15 +01006037 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006038#endif
6039}
6040
Emeric Brun0abf8362014-06-24 18:26:41 +02006041/* Extract peer certificate's common name into the chunk dest
6042 * Returns
6043 * the len of the extracted common name
6044 * or 0 if no CN found in DN
6045 * or -1 on error case (i.e. no peer certificate)
6046 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006047int ssl_sock_get_remote_common_name(struct connection *conn,
6048 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006049{
Christopher Faulet82004142019-09-10 10:12:03 +02006050 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04006051 X509 *crt = NULL;
6052 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006053 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006054 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006055 .area = (char *)&find_cn,
6056 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006057 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006058 int result = -1;
David Safb76832014-05-08 23:42:08 -04006059
6060 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02006061 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02006062 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006063
6064 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006065 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006066 if (!crt)
6067 goto out;
6068
6069 name = X509_get_subject_name(crt);
6070 if (!name)
6071 goto out;
David Safb76832014-05-08 23:42:08 -04006072
Emeric Brun0abf8362014-06-24 18:26:41 +02006073 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6074out:
David Safb76832014-05-08 23:42:08 -04006075 if (crt)
6076 X509_free(crt);
6077
6078 return result;
6079}
6080
Dave McCowan328fb582014-07-30 10:39:13 -04006081/* returns 1 if client passed a certificate for this session, 0 if not */
6082int ssl_sock_get_cert_used_sess(struct connection *conn)
6083{
Christopher Faulet82004142019-09-10 10:12:03 +02006084 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006085 X509 *crt = NULL;
6086
6087 if (!ssl_sock_is_ssl(conn))
6088 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006089 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006090
6091 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006092 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006093 if (!crt)
6094 return 0;
6095
6096 X509_free(crt);
6097 return 1;
6098}
6099
6100/* returns 1 if client passed a certificate for this connection, 0 if not */
6101int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006102{
Christopher Faulet82004142019-09-10 10:12:03 +02006103 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006104
David Safb76832014-05-08 23:42:08 -04006105 if (!ssl_sock_is_ssl(conn))
6106 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006107 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006108 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006109}
6110
6111/* returns result from SSL verify */
6112unsigned int ssl_sock_get_verify_result(struct connection *conn)
6113{
Christopher Faulet82004142019-09-10 10:12:03 +02006114 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006115
David Safb76832014-05-08 23:42:08 -04006116 if (!ssl_sock_is_ssl(conn))
6117 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006118 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006119 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006120}
6121
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006122/* Returns the application layer protocol name in <str> and <len> when known.
6123 * Zero is returned if the protocol name was not found, otherwise non-zero is
6124 * returned. The string is allocated in the SSL context and doesn't have to be
6125 * freed by the caller. NPN is also checked if available since older versions
6126 * of openssl (1.0.1) which are more common in field only support this one.
6127 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006128static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006129{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006130#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6131 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006132 struct ssl_sock_ctx *ctx = xprt_ctx;
6133 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006134 return 0;
6135
6136 *str = NULL;
6137
6138#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006139 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006140 if (*str)
6141 return 1;
6142#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006143#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006144 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006145 if (*str)
6146 return 1;
6147#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006148#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006149 return 0;
6150}
6151
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006152/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006153int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006154{
6155 X509 *ca;
6156 X509_NAME *name = NULL;
6157 ASN1_OCTET_STRING *skid = NULL;
6158 STACK_OF(X509) *chain = NULL;
6159 struct issuer_chain *issuer;
6160 struct eb64_node *node;
6161 char *path;
6162 u64 key;
6163 int ret = 0;
6164
6165 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6166 if (chain == NULL) {
6167 chain = sk_X509_new_null();
6168 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6169 name = X509_get_subject_name(ca);
6170 }
6171 if (!sk_X509_push(chain, ca)) {
6172 X509_free(ca);
6173 goto end;
6174 }
6175 }
6176 if (!chain) {
6177 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6178 goto end;
6179 }
6180 if (!skid) {
6181 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6182 goto end;
6183 }
6184 if (!name) {
6185 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6186 goto end;
6187 }
6188 key = XXH64(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006189 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006190 issuer = container_of(node, typeof(*issuer), node);
6191 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6192 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6193 goto end;
6194 }
6195 }
6196 issuer = calloc(1, sizeof *issuer);
6197 path = strdup(fp);
6198 if (!issuer || !path) {
6199 free(issuer);
6200 free(path);
6201 goto end;
6202 }
6203 issuer->node.key = key;
6204 issuer->path = path;
6205 issuer->chain = chain;
6206 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006207 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006208 ret = 1;
6209 end:
6210 if (skid)
6211 ASN1_OCTET_STRING_free(skid);
6212 if (chain)
6213 sk_X509_pop_free(chain, X509_free);
6214 return ret;
6215}
6216
William Lallemandda8584c2020-05-14 10:14:37 +02006217 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006218{
6219 AUTHORITY_KEYID *akid;
6220 struct issuer_chain *issuer = NULL;
6221
6222 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemand829d0712020-11-19 16:24:13 +01006223 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006224 struct eb64_node *node;
6225 u64 hk;
6226 hk = XXH64(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
6227 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6228 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6229 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6230 issuer = ti;
6231 break;
6232 }
6233 }
6234 AUTHORITY_KEYID_free(akid);
6235 }
6236 return issuer;
6237}
6238
William Lallemanddad31052020-05-14 17:47:32 +02006239void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006240{
6241 struct eb64_node *node, *back;
6242 struct issuer_chain *issuer;
6243
William Lallemande0f3fd52020-02-25 14:53:06 +01006244 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006245 while (node) {
6246 issuer = container_of(node, typeof(*issuer), node);
6247 back = eb64_next(node);
6248 eb64_delete(node);
6249 free(issuer->path);
6250 sk_X509_pop_free(issuer->chain, X509_free);
6251 free(issuer);
6252 node = back;
6253 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006254}
6255
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006256#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006257static int ssl_check_async_engine_count(void) {
6258 int err_code = 0;
6259
Emeric Brun3854e012017-05-17 20:42:48 +02006260 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006261 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006262 err_code = ERR_ABORT;
6263 }
6264 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006265}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006266#endif
6267
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006268/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau767dedd2021-01-21 08:53:50 +01006269 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006270 */
Willy Tarreau6cb467e2021-01-21 08:26:06 +01006271static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006272{
6273 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau767dedd2021-01-21 08:53:50 +01006274 int ret = 0;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006275
6276 if (!sctx)
Willy Tarreau767dedd2021-01-21 08:53:50 +01006277 return ret;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006278
Willy Tarreau767dedd2021-01-21 08:53:50 +01006279 if (sctx->conn != conn) {
6280 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6281 ret = 1;
6282 }
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006283 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6284
6285 if (sctx->xprt) {
6286 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6287 if (sctx->xprt_ctx)
6288 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6289 }
6290
6291 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau767dedd2021-01-21 08:53:50 +01006292
6293 /* as soon as a shutdown is reported the lower layer unregisters its
6294 * subscriber, so the situations below are transient and rare enough to
6295 * be reported as suspicious. In any case they shouldn't last.
6296 */
6297 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
6298 ret = 1;
6299 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
6300 ret = 1;
6301
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006302 chunk_appendf(&trash, " .subs=%p", sctx->subs);
6303 if (sctx->subs) {
6304 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau767dedd2021-01-21 08:53:50 +01006305 if (sctx->subs->tasklet->calls >= 1000000)
6306 ret = 1;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006307 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
6308 sctx->subs->tasklet->calls,
6309 sctx->subs->tasklet->context);
6310 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
6311 chunk_appendf(&trash, ")");
6312 }
6313 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
6314 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau767dedd2021-01-21 08:53:50 +01006315 return ret;
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006316}
6317
William Lallemand32af2032016-10-29 18:09:35 +02006318/* This function is used with TLS ticket keys management. It permits to browse
6319 * each reference. The variable <getnext> must contain the current node,
6320 * <end> point to the root node.
6321 */
6322#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6323static inline
6324struct tls_keys_ref *tlskeys_list_get_next(struct tls_keys_ref *getnext, struct list *end)
6325{
6326 struct tls_keys_ref *ref = getnext;
6327
6328 while (1) {
6329
6330 /* Get next list entry. */
6331 ref = LIST_NEXT(&ref->list, struct tls_keys_ref *, list);
6332
6333 /* If the entry is the last of the list, return NULL. */
6334 if (&ref->list == end)
6335 return NULL;
6336
6337 return ref;
6338 }
6339}
6340
6341static inline
6342struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6343{
6344 int id;
6345 char *error;
6346
6347 /* If the reference starts by a '#', this is numeric id. */
6348 if (reference[0] == '#') {
6349 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6350 id = strtol(reference + 1, &error, 10);
6351 if (*error != '\0')
6352 return NULL;
6353
6354 /* Perform the unique id lookup. */
6355 return tlskeys_ref_lookupid(id);
6356 }
6357
6358 /* Perform the string lookup. */
6359 return tlskeys_ref_lookup(reference);
6360}
6361#endif
6362
6363
6364#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6365
6366static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6367
6368static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6369 return cli_io_handler_tlskeys_files(appctx);
6370}
6371
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006372/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6373 * (next index to be dumped), and cli.p0 (next key reference).
6374 */
William Lallemand32af2032016-10-29 18:09:35 +02006375static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6376
6377 struct stream_interface *si = appctx->owner;
6378
6379 switch (appctx->st2) {
6380 case STAT_ST_INIT:
6381 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006382 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006383 * later and restart at the state "STAT_ST_INIT".
6384 */
6385 chunk_reset(&trash);
6386
6387 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6388 chunk_appendf(&trash, "# id secret\n");
6389 else
6390 chunk_appendf(&trash, "# id (file)\n");
6391
Willy Tarreau06d80a92017-10-19 14:32:15 +02006392 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006393 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006394 return 0;
6395 }
6396
William Lallemand32af2032016-10-29 18:09:35 +02006397 /* Now, we start the browsing of the references lists.
6398 * Note that the following call to LIST_ELEM return bad pointer. The only
6399 * available field of this pointer is <list>. It is used with the function
6400 * tlskeys_list_get_next() for retruning the first available entry
6401 */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006402 if (appctx->ctx.cli.p0 == NULL) {
6403 appctx->ctx.cli.p0 = LIST_ELEM(&tlskeys_reference, struct tls_keys_ref *, list);
6404 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006405 }
6406
6407 appctx->st2 = STAT_ST_LIST;
6408 /* fall through */
6409
6410 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006411 while (appctx->ctx.cli.p0) {
6412 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006413
6414 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006415 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006416 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006417
6418 if (appctx->ctx.cli.i1 == 0)
6419 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6420
William Lallemand32af2032016-10-29 18:09:35 +02006421 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006422 int head;
6423
6424 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6425 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006426 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006427 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006428
6429 chunk_reset(t2);
6430 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006431 if (ref->key_size_bits == 128) {
6432 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6433 sizeof(struct tls_sess_key_128),
6434 t2->area, t2->size);
6435 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6436 t2->area);
6437 }
6438 else if (ref->key_size_bits == 256) {
6439 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6440 sizeof(struct tls_sess_key_256),
6441 t2->area, t2->size);
6442 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6443 t2->area);
6444 }
6445 else {
6446 /* This case should never happen */
6447 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6448 }
William Lallemand32af2032016-10-29 18:09:35 +02006449
Willy Tarreau06d80a92017-10-19 14:32:15 +02006450 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006451 /* let's try again later from this stream. We add ourselves into
6452 * this stream's users so that it can remove us upon termination.
6453 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006454 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006455 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006456 return 0;
6457 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006458 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006459 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006460 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006461 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006462 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006463 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006464 /* let's try again later from this stream. We add ourselves into
6465 * this stream's users so that it can remove us upon termination.
6466 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006467 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006468 return 0;
6469 }
6470
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006471 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006472 break;
6473
6474 /* get next list entry and check the end of the list */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006475 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006476 }
6477
6478 appctx->st2 = STAT_ST_FIN;
6479 /* fall through */
6480
6481 default:
6482 appctx->st2 = STAT_ST_FIN;
6483 return 1;
6484 }
6485 return 0;
6486}
6487
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006488/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006489static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006490{
William Lallemand32af2032016-10-29 18:09:35 +02006491 /* no parameter, shows only file list */
6492 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006493 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006494 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006495 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006496 }
6497
6498 if (args[2][0] == '*') {
6499 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006500 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006501 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006502 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006503 if (!appctx->ctx.cli.p0)
6504 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006505 }
William Lallemand32af2032016-10-29 18:09:35 +02006506 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006507 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006508}
6509
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006510static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006511{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006512 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006513 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006514
William Lallemand32af2032016-10-29 18:09:35 +02006515 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006516 if (!*args[3] || !*args[4])
6517 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 +02006518
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006519 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006520 if (!ref)
6521 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006522
Willy Tarreau1c913e42018-08-22 05:26:57 +02006523 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006524 if (ret < 0)
6525 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006526
Willy Tarreau1c913e42018-08-22 05:26:57 +02006527 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006528 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6529 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006530
Willy Tarreau9d008692019-08-09 11:21:01 +02006531 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006532}
William Lallemandd4f946c2019-12-05 10:26:40 +01006533#endif
William Lallemand419e6342020-04-08 12:05:39 +02006534
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006535static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006536{
6537#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6538 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006539 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006540
6541 if (!payload)
6542 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006543
6544 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006545 if (!*payload)
6546 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006547
6548 /* remove \r and \n from the payload */
6549 for (i = 0, j = 0; payload[i]; i++) {
6550 if (payload[i] == '\r' || payload[i] == '\n')
6551 continue;
6552 payload[j++] = payload[i];
6553 }
6554 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006555
Willy Tarreau1c913e42018-08-22 05:26:57 +02006556 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006557 if (ret < 0)
6558 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006559
Willy Tarreau1c913e42018-08-22 05:26:57 +02006560 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02006561 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02006562 if (err)
6563 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
6564 else
6565 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006566 }
Willy Tarreau9d008692019-08-09 11:21:01 +02006567
6568 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006569#else
Willy Tarreau9d008692019-08-09 11:21:01 +02006570 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 +02006571#endif
6572
Elliot Otchet71f82972020-01-15 08:12:14 -05006573}
6574
William Lallemand32af2032016-10-29 18:09:35 +02006575/* register cli keywords */
6576static struct cli_kw_list cli_kws = {{ },{
6577#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6578 { { "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 +02006579 { { "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 +02006580#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006581 { { "set", "ssl", "ocsp-response", NULL }, NULL, cli_parse_set_ocspresponse, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02006582 { { NULL }, NULL, NULL, NULL }
6583}};
6584
Willy Tarreau0108d902018-11-25 19:14:37 +01006585INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02006586
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02006587/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02006588struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02006589 .snd_buf = ssl_sock_from_buf,
6590 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01006591 .subscribe = ssl_subscribe,
6592 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02006593 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02006594 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02006595 .rcv_pipe = NULL,
6596 .snd_pipe = NULL,
6597 .shutr = NULL,
6598 .shutw = ssl_sock_shutw,
6599 .close = ssl_sock_close,
6600 .init = ssl_sock_init,
Willy Tarreau55d37912016-12-21 23:38:39 +01006601 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01006602 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01006603 .prepare_srv = ssl_sock_prepare_srv_ctx,
6604 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006605 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006606 .takeover = ssl_takeover,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01006607 .name = "SSL",
Willy Tarreaudaad3c82021-01-20 14:41:29 +01006608 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02006609};
6610
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006611enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
6612 struct session *sess, struct stream *s, int flags)
6613{
6614 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006615 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006616
6617 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006618 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006619
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006620 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006621 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006622 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006623 s->req.flags |= CF_READ_NULL;
6624 return ACT_RET_YIELD;
6625 }
6626 }
6627 return (ACT_RET_CONT);
6628}
6629
6630static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
6631{
6632 rule->action_ptr = ssl_action_wait_for_hs;
6633
6634 return ACT_RET_PRS_OK;
6635}
6636
6637static struct action_kw_list http_req_actions = {ILH, {
6638 { "wait-for-handshake", ssl_parse_wait_for_hs },
6639 { /* END */ }
6640}};
6641
Willy Tarreau0108d902018-11-25 19:14:37 +01006642INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
6643
Ilya Shipitsin49bab752021-02-06 18:59:22 +05006644#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006645
6646static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6647{
6648 if (ptr) {
6649 chunk_destroy(ptr);
6650 free(ptr);
6651 }
6652}
6653
6654#endif
William Lallemand76b4a122020-08-04 17:41:39 +02006655
6656#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
6657static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6658{
6659 struct ocsp_cbk_arg *ocsp_arg;
6660
6661 if (ptr) {
6662 ocsp_arg = ptr;
6663
6664 if (ocsp_arg->is_single) {
6665 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
6666 ocsp_arg->s_ocsp = NULL;
6667 } else {
6668 int i;
6669
6670 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
6671 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
6672 ocsp_arg->m_ocsp[i] = NULL;
6673 }
6674 }
6675 free(ocsp_arg);
6676 }
6677}
6678#endif
6679
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006680static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6681{
Willy Tarreaubafbe012017-11-24 17:34:44 +01006682 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006683}
William Lallemand7d42ef52020-07-06 11:41:30 +02006684
Ilya Shipitsin04a5a442020-11-03 14:15:38 +05006685#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02006686static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6687{
6688 struct ssl_keylog *keylog;
6689
6690 if (!ptr)
6691 return;
6692
6693 keylog = ptr;
6694
6695 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
6696 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
6697 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
6698 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
6699 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
6700 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
6701 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
6702 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
6703
6704 pool_free(pool_head_ssl_keylog, ptr);
6705}
6706#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006707
Emeric Brun46591952012-05-18 15:47:34 +02006708__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02006709static void __ssl_sock_init(void)
6710{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006711#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006712 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006713 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006714#endif
Emeric Brun46591952012-05-18 15:47:34 +02006715
Willy Tarreauef934602016-12-22 23:12:01 +01006716 if (global_ssl.listen_default_ciphers)
6717 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
6718 if (global_ssl.connect_default_ciphers)
6719 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Emmanuel Hocdet839af572019-05-14 16:27:35 +02006720#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02006721 if (global_ssl.listen_default_ciphersuites)
6722 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
6723 if (global_ssl.connect_default_ciphersuites)
6724 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
6725#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01006726
Willy Tarreau13e14102016-12-22 20:25:26 +01006727 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006728#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02006729 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08006730#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006731#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006732 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006733 n = sk_SSL_COMP_num(cm);
6734 while (n--) {
6735 (void) sk_SSL_COMP_pop(cm);
6736 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006737#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006738
Willy Tarreau5db847a2019-05-09 14:13:35 +02006739#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006740 ssl_locking_init();
6741#endif
Ilya Shipitsin49bab752021-02-06 18:59:22 +05006742#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006743 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
6744#endif
William Lallemand76b4a122020-08-04 17:41:39 +02006745
6746#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
6747 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
6748#endif
6749
Thierry FOURNIER28962c92018-06-17 21:37:05 +02006750 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02006751 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 +05006752#ifdef HAVE_OPENSSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02006753 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
6754#endif
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006755#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006756 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006757 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006758#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01006759#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6760 hap_register_post_check(tlskeys_finalize_config);
6761#endif
Willy Tarreau80713382018-11-26 10:19:54 +01006762
6763 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
6764 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
6765
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006766 hap_register_post_deinit(ssl_free_global_issuers);
6767
Willy Tarreau80713382018-11-26 10:19:54 +01006768#ifndef OPENSSL_NO_DH
6769 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
6770 hap_register_post_deinit(ssl_free_dh);
6771#endif
6772#ifndef OPENSSL_NO_ENGINE
6773 hap_register_post_deinit(ssl_free_engines);
6774#endif
6775 /* Load SSL string for the verbose & debug mode. */
6776 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02006777 ha_meth = BIO_meth_new(0x666, "ha methods");
6778 BIO_meth_set_write(ha_meth, ha_ssl_write);
6779 BIO_meth_set_read(ha_meth, ha_ssl_read);
6780 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
6781 BIO_meth_set_create(ha_meth, ha_ssl_new);
6782 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
6783 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
6784 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02006785
6786 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006787
Dragan Dosen9ac98092020-05-11 15:51:45 +02006788 /* Try to register dedicated SSL/TLS protocol message callbacks for
6789 * heartbleed attack (CVE-2014-0160) and clienthello.
6790 */
6791 hap_register_post_check(ssl_sock_register_msg_callbacks);
6792
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006793 /* Try to free all callbacks that were registered by using
6794 * ssl_sock_register_msg_callback().
6795 */
6796 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01006797}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01006798
Willy Tarreau80713382018-11-26 10:19:54 +01006799/* Compute and register the version string */
6800static void ssl_register_build_options()
6801{
6802 char *ptr = NULL;
6803 int i;
6804
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006805 memprintf(&ptr, "Built with OpenSSL version : "
6806#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006807 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006808#else /* OPENSSL_IS_BORINGSSL */
6809 OPENSSL_VERSION_TEXT
6810 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08006811 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02006812 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006813#endif
6814 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006815#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006816 "no (library version too old)"
6817#elif defined(OPENSSL_NO_TLSEXT)
6818 "no (disabled via OPENSSL_NO_TLSEXT)"
6819#else
6820 "yes"
6821#endif
6822 "", ptr);
6823
6824 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
6825#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
6826 "yes"
6827#else
6828#ifdef OPENSSL_NO_TLSEXT
6829 "no (because of OPENSSL_NO_TLSEXT)"
6830#else
6831 "no (version might be too old, 0.9.8f min needed)"
6832#endif
6833#endif
6834 "", ptr);
6835
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02006836 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
6837 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
6838 if (methodVersions[i].option)
6839 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006840
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006841 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01006842}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006843
Willy Tarreau80713382018-11-26 10:19:54 +01006844INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02006845
Emeric Brun46591952012-05-18 15:47:34 +02006846
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006847#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006848void ssl_free_engines(void) {
6849 struct ssl_engine_list *wl, *wlb;
6850 /* free up engine list */
6851 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
6852 ENGINE_finish(wl->e);
6853 ENGINE_free(wl->e);
6854 LIST_DEL(&wl->list);
6855 free(wl);
6856 }
6857}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006858#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02006859
Remi Gacogned3a23c32015-05-28 16:39:47 +02006860#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00006861void ssl_free_dh(void) {
6862 if (local_dh_1024) {
6863 DH_free(local_dh_1024);
6864 local_dh_1024 = NULL;
6865 }
6866 if (local_dh_2048) {
6867 DH_free(local_dh_2048);
6868 local_dh_2048 = NULL;
6869 }
6870 if (local_dh_4096) {
6871 DH_free(local_dh_4096);
6872 local_dh_4096 = NULL;
6873 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02006874 if (global_dh) {
6875 DH_free(global_dh);
6876 global_dh = NULL;
6877 }
Grant Zhang872f9c22017-01-21 01:10:18 +00006878}
6879#endif
6880
6881__attribute__((destructor))
6882static void __ssl_sock_deinit(void)
6883{
6884#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006885 if (ssl_ctx_lru_tree) {
6886 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01006887 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02006888 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02006889#endif
6890
Willy Tarreau5db847a2019-05-09 14:13:35 +02006891#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006892 ERR_remove_state(0);
6893 ERR_free_strings();
6894
6895 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08006896#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02006897
Willy Tarreau5db847a2019-05-09 14:13:35 +02006898#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006899 CRYPTO_cleanup_all_ex_data();
6900#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02006901 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02006902}
6903
Emeric Brun46591952012-05-18 15:47:34 +02006904/*
6905 * Local variables:
6906 * c-indent-level: 8
6907 * c-basic-offset: 8
6908 * End:
6909 */