blob: 12e95758dd4a4979cc5db043dcfca2d5b6ab4d7c [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 Tarreau4c7e4b72020-05-27 12:58:42 +020043#include <haproxy/api.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020044#include <import/lru.h>
45#include <import/xxhash.h>
46
Willy Tarreau2741c8c2020-06-02 11:28:02 +020047#include <haproxy/dynbuf.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020048#include <haproxy/chunk.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020049#include <haproxy/connection.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020050#include <haproxy/errors.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020051#include <haproxy/frontend.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020052#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020053#include <haproxy/http_rules.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020054#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020055#include <haproxy/pattern-t.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020056#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020057#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020058#include <haproxy/ssl_crtlist.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020059#include <haproxy/ssl_utils.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020060#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020061#include <haproxy/tools.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020062#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020063#include <haproxy/time.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020064#include <haproxy/base64.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020065#include <haproxy/vars.h>
Emeric Brun46591952012-05-18 15:47:34 +020066
Willy Tarreau8d2b7772020-05-27 10:58:19 +020067#include <import/ebpttree.h>
68#include <import/ebsttree.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020069
William Lallemand32af2032016-10-29 18:09:35 +020070#include <types/applet.h>
71#include <types/cli.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020072#include <types/ssl_sock.h>
William Lallemand32af2032016-10-29 18:09:35 +020073#include <types/stats.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020074
Willy Tarreau7875d092012-09-10 08:20:03 +020075#include <proto/acl.h>
Willy Tarreauaa74c4e2020-06-04 10:19:23 +020076#include <haproxy/arg.h>
William Lallemand32af2032016-10-29 18:09:35 +020077#include <proto/channel.h>
William Lallemand32af2032016-10-29 18:09:35 +020078#include <proto/cli.h>
Willy Tarreau0f6ffd62020-06-03 19:33:00 +020079#include <haproxy/fd.h>
Willy Tarreau66347942020-06-01 12:18:08 +020080#include <haproxy/freq_ctr.h>
Willy Tarreaufc774542020-06-04 17:31:04 +020081#include <haproxy/proto_tcp.h>
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020082#include <proto/http_ana.h>
Willy Tarreau92faadf2012-10-10 23:04:25 +020083#include <proto/server.h>
William Lallemand32af2032016-10-29 18:09:35 +020084#include <proto/stream_interface.h>
Emeric Brun46591952012-05-18 15:47:34 +020085#include <proto/log.h>
Emeric Brun94324a42012-10-11 14:00:19 +020086#include <proto/proxy.h>
Emeric Brun46591952012-05-18 15:47:34 +020087#include <proto/ssl_sock.h>
Willy Tarreau9ad7bd42015-04-03 19:19:59 +020088#include <proto/stream.h>
Emeric Brun46591952012-05-18 15:47:34 +020089
Willy Tarreau9356dac2019-05-10 09:22:53 +020090/* ***** READ THIS before adding code here! *****
91 *
92 * Due to API incompatibilities between multiple OpenSSL versions and their
93 * derivatives, it's often tempting to add macros to (re-)define certain
94 * symbols. Please do not do this here, and do it in common/openssl-compat.h
95 * exclusively so that the whole code consistently uses the same macros.
96 *
97 * Whenever possible if a macro is missing in certain versions, it's better
98 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
99 */
100
Willy Tarreau71b734c2014-01-28 15:19:44 +0100101int sslconns = 0;
102int totalsslconns = 0;
Emeric Brunece0c332017-12-06 13:51:49 +0100103int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +0200104
William Lallemande0f3fd52020-02-25 14:53:06 +0100105static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
106
William Lallemand7fd8b452020-05-07 15:20:43 +0200107struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100108#ifdef LISTEN_DEFAULT_CIPHERS
109 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
110#endif
111#ifdef CONNECT_DEFAULT_CIPHERS
112 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
113#endif
Emmanuel Hocdet839af572019-05-14 16:27:35 +0200114#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200115#ifdef LISTEN_DEFAULT_CIPHERSUITES
116 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
117#endif
118#ifdef CONNECT_DEFAULT_CIPHERSUITES
119 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
120#endif
121#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100122 .listen_default_ssloptions = BC_SSL_O_NONE,
123 .connect_default_ssloptions = SRV_SSL_O_NONE,
124
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200125 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
126 .listen_default_sslmethods.min = CONF_TLSV_NONE,
127 .listen_default_sslmethods.max = CONF_TLSV_NONE,
128 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
129 .connect_default_sslmethods.min = CONF_TLSV_NONE,
130 .connect_default_sslmethods.max = CONF_TLSV_NONE,
131
Willy Tarreauef934602016-12-22 23:12:01 +0100132#ifdef DEFAULT_SSL_MAX_RECORD
133 .max_record = DEFAULT_SSL_MAX_RECORD,
134#endif
135 .default_dh_param = SSL_DEFAULT_DH_PARAM,
136 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Thierry FOURNIER5bf77322017-02-25 12:45:22 +0100137 .capture_cipherlist = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100138 .extra_files = SSL_GF_ALL,
Willy Tarreauef934602016-12-22 23:12:01 +0100139};
140
Olivier Houcharda8955d52019-04-07 22:00:38 +0200141static BIO_METHOD *ha_meth;
142
Olivier Houchard66ab4982019-02-26 18:37:15 +0100143DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
144
Olivier Houchardea8dd942019-05-20 14:02:16 +0200145static struct task *ssl_sock_io_cb(struct task *, void *, unsigned short);
Olivier Houchard000694c2019-05-23 14:45:12 +0200146static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200147
Olivier Houcharda8955d52019-04-07 22:00:38 +0200148/* Methods to implement OpenSSL BIO */
149static int ha_ssl_write(BIO *h, const char *buf, int num)
150{
151 struct buffer tmpbuf;
152 struct ssl_sock_ctx *ctx;
153 int ret;
154
155 ctx = BIO_get_data(h);
156 tmpbuf.size = num;
157 tmpbuf.area = (void *)(uintptr_t)buf;
158 tmpbuf.data = num;
159 tmpbuf.head = 0;
160 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200161 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200162 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200163 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200164 } else if (ret == 0)
165 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200166 return ret;
167}
168
169static int ha_ssl_gets(BIO *h, char *buf, int size)
170{
171
172 return 0;
173}
174
175static int ha_ssl_puts(BIO *h, const char *str)
176{
177
178 return ha_ssl_write(h, str, strlen(str));
179}
180
181static int ha_ssl_read(BIO *h, char *buf, int size)
182{
183 struct buffer tmpbuf;
184 struct ssl_sock_ctx *ctx;
185 int ret;
186
187 ctx = BIO_get_data(h);
188 tmpbuf.size = size;
189 tmpbuf.area = buf;
190 tmpbuf.data = 0;
191 tmpbuf.head = 0;
192 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200193 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200194 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200195 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200196 } else if (ret == 0)
197 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200198
199 return ret;
200}
201
202static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
203{
204 int ret = 0;
205 switch (cmd) {
206 case BIO_CTRL_DUP:
207 case BIO_CTRL_FLUSH:
208 ret = 1;
209 break;
210 }
211 return ret;
212}
213
214static int ha_ssl_new(BIO *h)
215{
216 BIO_set_init(h, 1);
217 BIO_set_data(h, NULL);
218 BIO_clear_flags(h, ~0);
219 return 1;
220}
221
222static int ha_ssl_free(BIO *data)
223{
224
225 return 1;
226}
227
228
Willy Tarreau5db847a2019-05-09 14:13:35 +0200229#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100230
Emeric Brun821bb9b2017-06-15 16:37:39 +0200231static HA_RWLOCK_T *ssl_rwlocks;
232
233
234unsigned long ssl_id_function(void)
235{
236 return (unsigned long)tid;
237}
238
239void ssl_locking_function(int mode, int n, const char * file, int line)
240{
241 if (mode & CRYPTO_LOCK) {
242 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100243 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200244 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100245 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200246 }
247 else {
248 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100249 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200250 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100251 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200252 }
253}
254
255static int ssl_locking_init(void)
256{
257 int i;
258
259 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
260 if (!ssl_rwlocks)
261 return -1;
262
263 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100264 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200265
266 CRYPTO_set_id_callback(ssl_id_function);
267 CRYPTO_set_locking_callback(ssl_locking_function);
268
269 return 0;
270}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100271
Emeric Brun821bb9b2017-06-15 16:37:39 +0200272#endif
273
Willy Tarreauaf613e82020-06-05 08:40:51 +0200274__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200275
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100276
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200277/*
Emmanuel Hocdetb270e812019-11-21 19:09:31 +0100278 * deduplicate cafile (and crlfile)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200279 */
280struct cafile_entry {
281 X509_STORE *ca_store;
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200282 STACK_OF(X509_NAME) *ca_list;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200283 struct ebmb_node node;
284 char path[0];
285};
286
287static struct eb_root cafile_tree = EB_ROOT_UNIQUE;
288
289static X509_STORE* ssl_store_get0_locations_file(char *path)
290{
291 struct ebmb_node *eb;
292
293 eb = ebst_lookup(&cafile_tree, path);
294 if (eb) {
295 struct cafile_entry *ca_e;
296 ca_e = ebmb_entry(eb, struct cafile_entry, node);
297 return ca_e->ca_store;
298 }
299 return NULL;
300}
301
William Lallemanddad31052020-05-14 17:47:32 +0200302int ssl_store_load_locations_file(char *path)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200303{
304 if (ssl_store_get0_locations_file(path) == NULL) {
305 struct cafile_entry *ca_e;
306 X509_STORE *store = X509_STORE_new();
307 if (X509_STORE_load_locations(store, path, NULL)) {
308 int pathlen;
309 pathlen = strlen(path);
310 ca_e = calloc(1, sizeof(*ca_e) + pathlen + 1);
311 if (ca_e) {
312 memcpy(ca_e->path, path, pathlen + 1);
313 ca_e->ca_store = store;
314 ebst_insert(&cafile_tree, &ca_e->node);
315 return 1;
316 }
317 }
318 X509_STORE_free(store);
319 return 0;
320 }
321 return 1;
322}
323
324/* mimic what X509_STORE_load_locations do with store_ctx */
325static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
326{
327 X509_STORE *store;
328 store = ssl_store_get0_locations_file(path);
329 if (store_ctx && store) {
330 int i;
331 X509_OBJECT *obj;
332 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
333 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
334 obj = sk_X509_OBJECT_value(objs, i);
335 switch (X509_OBJECT_get_type(obj)) {
336 case X509_LU_X509:
337 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
338 break;
339 case X509_LU_CRL:
340 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
341 break;
342 default:
343 break;
344 }
345 }
346 return 1;
347 }
348 return 0;
349}
350
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500351/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200352static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
353{
354 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
355 return ssl_set_cert_crl_file(store_ctx, path);
356}
357
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200358/*
359 Extract CA_list from CA_file already in tree.
360 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
361 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
362*/
363static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
364{
365 struct ebmb_node *eb;
366 struct cafile_entry *ca_e;
367
368 eb = ebst_lookup(&cafile_tree, path);
369 if (!eb)
370 return NULL;
371 ca_e = ebmb_entry(eb, struct cafile_entry, node);
372
373 if (ca_e->ca_list == NULL) {
374 int i;
375 unsigned long key;
376 struct eb_root ca_name_tree = EB_ROOT;
377 struct eb64_node *node, *back;
378 struct {
379 struct eb64_node node;
380 X509_NAME *xname;
381 } *ca_name;
382 STACK_OF(X509_OBJECT) *objs;
383 STACK_OF(X509_NAME) *skn;
384 X509 *x;
385 X509_NAME *xn;
386
387 skn = sk_X509_NAME_new_null();
388 /* take x509 from cafile_tree */
389 objs = X509_STORE_get0_objects(ca_e->ca_store);
390 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
391 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
392 if (!x)
393 continue;
394 xn = X509_get_subject_name(x);
395 if (!xn)
396 continue;
397 /* Check for duplicates. */
398 key = X509_NAME_hash(xn);
399 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
400 node && ca_name == NULL;
401 node = eb64_next(node)) {
402 ca_name = container_of(node, typeof(*ca_name), node);
403 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
404 ca_name = NULL;
405 }
406 /* find a duplicate */
407 if (ca_name)
408 continue;
409 ca_name = calloc(1, sizeof *ca_name);
410 xn = X509_NAME_dup(xn);
411 if (!ca_name ||
412 !xn ||
413 !sk_X509_NAME_push(skn, xn)) {
414 free(ca_name);
415 X509_NAME_free(xn);
416 sk_X509_NAME_pop_free(skn, X509_NAME_free);
417 sk_X509_NAME_free(skn);
418 skn = NULL;
419 break;
420 }
421 ca_name->node.key = key;
422 ca_name->xname = xn;
423 eb64_insert(&ca_name_tree, &ca_name->node);
424 }
425 ca_e->ca_list = skn;
426 /* remove temporary ca_name tree */
427 node = eb64_first(&ca_name_tree);
428 while (node) {
429 ca_name = container_of(node, typeof(*ca_name), node);
430 back = eb64_next(node);
431 eb64_delete(node);
432 free(ca_name);
433 node = back;
434 }
435 }
436 return ca_e->ca_list;
437}
438
Willy Tarreaubafbe012017-11-24 17:34:44 +0100439struct pool_head *pool_head_ssl_capture = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200440int ssl_capture_ptr_index = -1;
Thierry FOURNIER28962c92018-06-17 21:37:05 +0200441static int ssl_app_data_index = -1;
Willy Tarreauef934602016-12-22 23:12:01 +0100442
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200443#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
444struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
445#endif
446
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200447#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200448unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000449struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
450struct ssl_engine_list {
451 struct list list;
452 ENGINE *e;
453};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200454#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000455
Remi Gacogne8de54152014-07-15 11:36:40 +0200456#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200457static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200458static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200459static DH *local_dh_1024 = NULL;
460static DH *local_dh_2048 = NULL;
461static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100462static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200463#endif /* OPENSSL_NO_DH */
464
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100465#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200466/* X509V3 Extensions that will be added on generated certificates */
467#define X509V3_EXT_SIZE 5
468static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
469 "basicConstraints",
470 "nsComment",
471 "subjectKeyIdentifier",
472 "authorityKeyIdentifier",
473 "keyUsage",
474};
475static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
476 "CA:FALSE",
477 "\"OpenSSL Generated Certificate\"",
478 "hash",
479 "keyid,issuer:always",
480 "nonRepudiation,digitalSignature,keyEncipherment"
481};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200482/* LRU cache to store generated certificate */
483static struct lru64_head *ssl_ctx_lru_tree = NULL;
484static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200485static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100486__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200487
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200488#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
489
Willy Tarreau9a1ab082019-05-09 13:26:41 +0200490#if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
yanbzhube2774d2015-12-10 15:07:30 -0500491/* The order here matters for picking a default context,
492 * keep the most common keytype at the bottom of the list
493 */
494const char *SSL_SOCK_KEYTYPE_NAMES[] = {
495 "dsa",
496 "ecdsa",
497 "rsa"
498};
yanbzhube2774d2015-12-10 15:07:30 -0500499#endif
500
William Lallemandc3cd35f2017-11-28 11:04:43 +0100501static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100502static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
503
Dragan Dosen9ac98092020-05-11 15:51:45 +0200504/* Dedicated callback functions for heartbeat and clienthello.
505 */
506#ifdef TLS1_RT_HEARTBEAT
507static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
508 int content_type, const void *buf, size_t len,
509 SSL *ssl);
510#endif
511static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
512 int content_type, const void *buf, size_t len,
513 SSL *ssl);
514
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200515/* List head of all registered SSL/TLS protocol message callbacks. */
516struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
517
518/* Registers the function <func> in order to be called on SSL/TLS protocol
519 * message processing. It will return 0 if the function <func> is not set
520 * or if it fails to allocate memory.
521 */
522int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
523{
524 struct ssl_sock_msg_callback *cbk;
525
526 if (!func)
527 return 0;
528
529 cbk = calloc(1, sizeof(*cbk));
530 if (!cbk) {
531 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
532 return 0;
533 }
534
535 cbk->func = func;
536
537 LIST_ADDQ(&ssl_sock_msg_callbacks, &cbk->list);
538
539 return 1;
540}
541
Dragan Dosen9ac98092020-05-11 15:51:45 +0200542/* Used to register dedicated SSL/TLS protocol message callbacks.
543 */
544static int ssl_sock_register_msg_callbacks(void)
545{
546#ifdef TLS1_RT_HEARTBEAT
547 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
548 return ERR_ABORT;
549#endif
550 if (global_ssl.capture_cipherlist > 0) {
551 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
552 return ERR_ABORT;
553 }
554 return 0;
555}
556
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200557/* Used to free all SSL/TLS protocol message callbacks that were
558 * registered by using ssl_sock_register_msg_callback().
559 */
560static void ssl_sock_unregister_msg_callbacks(void)
561{
562 struct ssl_sock_msg_callback *cbk, *cbkback;
563
564 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
565 LIST_DEL(&cbk->list);
566 free(cbk);
567 }
568}
569
Dragan Doseneb607fe2020-05-11 17:17:06 +0200570SSL *ssl_sock_get_ssl_object(struct connection *conn)
571{
572 if (!ssl_sock_is_ssl(conn))
573 return NULL;
574
575 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
576}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100577/*
578 * This function gives the detail of the SSL error. It is used only
579 * if the debug mode and the verbose mode are activated. It dump all
580 * the SSL error until the stack was empty.
581 */
582static forceinline void ssl_sock_dump_errors(struct connection *conn)
583{
584 unsigned long ret;
585
586 if (unlikely(global.mode & MODE_DEBUG)) {
587 while(1) {
588 ret = ERR_get_error();
589 if (ret == 0)
590 return;
591 fprintf(stderr, "fd[%04x] OpenSSL error[0x%lx] %s: %s\n",
Willy Tarreau585744b2017-08-24 14:31:19 +0200592 (unsigned short)conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100593 ERR_func_error_string(ret), ERR_reason_error_string(ret));
594 }
595 }
596}
597
yanbzhube2774d2015-12-10 15:07:30 -0500598
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200599#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200600int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000601{
602 int err_code = ERR_ABORT;
603 ENGINE *engine;
604 struct ssl_engine_list *el;
605
606 /* grab the structural reference to the engine */
607 engine = ENGINE_by_id(engine_id);
608 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100609 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000610 goto fail_get;
611 }
612
613 if (!ENGINE_init(engine)) {
614 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100615 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000616 goto fail_init;
617 }
618
619 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100620 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000621 goto fail_set_method;
622 }
623
624 el = calloc(1, sizeof(*el));
625 el->e = engine;
626 LIST_ADD(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100627 nb_engines++;
628 if (global_ssl.async)
629 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000630 return 0;
631
632fail_set_method:
633 /* release the functional reference from ENGINE_init() */
634 ENGINE_finish(engine);
635
636fail_init:
637 /* release the structural reference from ENGINE_by_id() */
638 ENGINE_free(engine);
639
640fail_get:
641 return err_code;
642}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200643#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000644
Willy Tarreau5db847a2019-05-09 14:13:35 +0200645#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +0200646/*
647 * openssl async fd handler
648 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200649void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000650{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200651 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000652
Emeric Brun3854e012017-05-17 20:42:48 +0200653 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000654 * to poll this fd until it is requested
655 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000656 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000657 fd_cant_recv(fd);
658
659 /* crypto engine is available, let's notify the associated
660 * connection that it can pursue its processing.
661 */
Olivier Houchard03abf2d2019-05-28 10:12:02 +0200662 ssl_sock_io_cb(NULL, ctx, 0);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000663}
664
Emeric Brun3854e012017-05-17 20:42:48 +0200665/*
666 * openssl async delayed SSL_free handler
667 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200668void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000669{
670 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200671 OSSL_ASYNC_FD all_fd[32];
672 size_t num_all_fds = 0;
673 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000674
Emeric Brun3854e012017-05-17 20:42:48 +0200675 /* We suppose that the async job for a same SSL *
676 * are serialized. So if we are awake it is
677 * because the running job has just finished
678 * and we can remove all async fds safely
679 */
680 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
681 if (num_all_fds > 32) {
682 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
683 return;
684 }
685
686 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
687 for (i=0 ; i < num_all_fds ; i++)
688 fd_remove(all_fd[i]);
689
690 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000691 SSL_free(ssl);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +0100692 _HA_ATOMIC_SUB(&sslconns, 1);
693 _HA_ATOMIC_SUB(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000694}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000695/*
Emeric Brun3854e012017-05-17 20:42:48 +0200696 * function used to manage a returned SSL_ERROR_WANT_ASYNC
697 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000698 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200699static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000700{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100701 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200702 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200703 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000704 size_t num_add_fds = 0;
705 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200706 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000707
708 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
709 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200710 if (num_add_fds > 32 || num_del_fds > 32) {
711 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 +0000712 return;
713 }
714
Emeric Brun3854e012017-05-17 20:42:48 +0200715 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000716
Emeric Brun3854e012017-05-17 20:42:48 +0200717 /* We remove unused fds from the fdtab */
718 for (i=0 ; i < num_del_fds ; i++)
719 fd_remove(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000720
Emeric Brun3854e012017-05-17 20:42:48 +0200721 /* We add new fds to the fdtab */
722 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200723 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000724 }
725
Emeric Brun3854e012017-05-17 20:42:48 +0200726 num_add_fds = 0;
727 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
728 if (num_add_fds > 32) {
729 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
730 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000731 }
Emeric Brun3854e012017-05-17 20:42:48 +0200732
733 /* We activate the polling for all known async fds */
734 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000735 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200736 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000737 /* To ensure that the fd cache won't be used
738 * We'll prefer to catch a real RD event
739 * because handling an EAGAIN on this fd will
740 * result in a context switch and also
741 * some engines uses a fd in blocking mode.
742 */
743 fd_cant_recv(add_fd[i]);
744 }
Emeric Brun3854e012017-05-17 20:42:48 +0200745
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000746}
747#endif
748
William Lallemand104a7a62019-10-14 14:14:59 +0200749#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200750/*
751 * This function returns the number of seconds elapsed
752 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
753 * date presented un ASN1_GENERALIZEDTIME.
754 *
755 * In parsing error case, it returns -1.
756 */
757static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
758{
759 long epoch;
760 char *p, *end;
761 const unsigned short month_offset[12] = {
762 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
763 };
764 int year, month;
765
766 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
767
768 p = (char *)d->data;
769 end = p + d->length;
770
771 if (end - p < 4) return -1;
772 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
773 p += 4;
774 if (end - p < 2) return -1;
775 month = 10 * (p[0] - '0') + p[1] - '0';
776 if (month < 1 || month > 12) return -1;
777 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
778 We consider leap years and the current month (<marsh or not) */
779 epoch = ( ((year - 1970) * 365)
780 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
781 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
782 + month_offset[month-1]
783 ) * 24 * 60 * 60;
784 p += 2;
785 if (end - p < 2) return -1;
786 /* Add the number of seconds of completed days of current month */
787 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
788 p += 2;
789 if (end - p < 2) return -1;
790 /* Add the completed hours of the current day */
791 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
792 p += 2;
793 if (end - p < 2) return -1;
794 /* Add the completed minutes of the current hour */
795 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
796 p += 2;
797 if (p == end) return -1;
798 /* Test if there is available seconds */
799 if (p[0] < '0' || p[0] > '9')
800 goto nosec;
801 if (end - p < 2) return -1;
802 /* Add the seconds of the current minute */
803 epoch += 10 * (p[0] - '0') + p[1] - '0';
804 p += 2;
805 if (p == end) return -1;
806 /* Ignore seconds float part if present */
807 if (p[0] == '.') {
808 do {
809 if (++p == end) return -1;
810 } while (p[0] >= '0' && p[0] <= '9');
811 }
812
813nosec:
814 if (p[0] == 'Z') {
815 if (end - p != 1) return -1;
816 return epoch;
817 }
818 else if (p[0] == '+') {
819 if (end - p != 5) return -1;
820 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700821 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 +0200822 }
823 else if (p[0] == '-') {
824 if (end - p != 5) return -1;
825 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700826 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 +0200827 }
828
829 return -1;
830}
831
William Lallemand104a7a62019-10-14 14:14:59 +0200832/*
833 * struct alignment works here such that the key.key is the same as key_data
834 * Do not change the placement of key_data
835 */
836struct certificate_ocsp {
837 struct ebmb_node key;
838 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
839 struct buffer response;
840 long expire;
841};
842
843struct ocsp_cbk_arg {
844 int is_single;
845 int single_kt;
846 union {
847 struct certificate_ocsp *s_ocsp;
848 /*
849 * m_ocsp will have multiple entries dependent on key type
850 * Entry 0 - DSA
851 * Entry 1 - ECDSA
852 * Entry 2 - RSA
853 */
854 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
855 };
856};
857
Emeric Brun1d3865b2014-06-20 15:37:32 +0200858static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200859
860/* This function starts to check if the OCSP response (in DER format) contained
861 * in chunk 'ocsp_response' is valid (else exits on error).
862 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
863 * contained in the OCSP Response and exits on error if no match.
864 * If it's a valid OCSP Response:
865 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
866 * pointed by 'ocsp'.
867 * If 'ocsp' is NULL, the function looks up into the OCSP response's
868 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
869 * from the response) and exits on error if not found. Finally, If an OCSP response is
870 * already present in the container, it will be overwritten.
871 *
872 * Note: OCSP response containing more than one OCSP Single response is not
873 * considered valid.
874 *
875 * Returns 0 on success, 1 in error case.
876 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200877static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
878 struct certificate_ocsp *ocsp,
879 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200880{
881 OCSP_RESPONSE *resp;
882 OCSP_BASICRESP *bs = NULL;
883 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200884 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200885 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200886 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200887 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200888 int reason;
889 int ret = 1;
890
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200891 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
892 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200893 if (!resp) {
894 memprintf(err, "Unable to parse OCSP response");
895 goto out;
896 }
897
898 rc = OCSP_response_status(resp);
899 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
900 memprintf(err, "OCSP response status not successful");
901 goto out;
902 }
903
904 bs = OCSP_response_get1_basic(resp);
905 if (!bs) {
906 memprintf(err, "Failed to get basic response from OCSP Response");
907 goto out;
908 }
909
910 count_sr = OCSP_resp_count(bs);
911 if (count_sr > 1) {
912 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
913 goto out;
914 }
915
916 sr = OCSP_resp_get0(bs, 0);
917 if (!sr) {
918 memprintf(err, "Failed to get OCSP single response");
919 goto out;
920 }
921
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200922 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
923
Emeric Brun4147b2e2014-06-16 18:36:30 +0200924 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200925 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200926 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200927 goto out;
928 }
929
Emeric Brun13a6b482014-06-20 15:44:34 +0200930 if (!nextupd) {
931 memprintf(err, "OCSP single response: missing nextupdate");
932 goto out;
933 }
934
Emeric Brunc8b27b62014-06-19 14:16:17 +0200935 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200936 if (!rc) {
937 memprintf(err, "OCSP single response: no longer valid.");
938 goto out;
939 }
940
941 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200942 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +0200943 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
944 goto out;
945 }
946 }
947
948 if (!ocsp) {
949 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
950 unsigned char *p;
951
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200952 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200953 if (!rc) {
954 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
955 goto out;
956 }
957
958 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
959 memprintf(err, "OCSP single response: Certificate ID too long");
960 goto out;
961 }
962
963 p = key;
964 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200965 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200966 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
967 if (!ocsp) {
968 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
969 goto out;
970 }
971 }
972
973 /* According to comments on "chunk_dup", the
974 previous chunk buffer will be freed */
975 if (!chunk_dup(&ocsp->response, ocsp_response)) {
976 memprintf(err, "OCSP response: Memory allocation error");
977 goto out;
978 }
979
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200980 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
981
Emeric Brun4147b2e2014-06-16 18:36:30 +0200982 ret = 0;
983out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +0100984 ERR_clear_error();
985
Emeric Brun4147b2e2014-06-16 18:36:30 +0200986 if (bs)
987 OCSP_BASICRESP_free(bs);
988
989 if (resp)
990 OCSP_RESPONSE_free(resp);
991
992 return ret;
993}
994/*
995 * External function use to update the OCSP response in the OCSP response's
996 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
997 * to update in DER format.
998 *
999 * Returns 0 on success, 1 in error case.
1000 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001001int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001002{
1003 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1004}
1005
William Lallemand4a660132019-10-14 14:51:41 +02001006#endif
1007
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001008#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1009static 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)
1010{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001011 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001012 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001013 struct connection *conn;
1014 int head;
1015 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001016 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001017
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001018 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001019 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001020 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1021
1022 keys = ref->tlskeys;
1023 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001024
1025 if (enc) {
1026 memcpy(key_name, keys[head].name, 16);
1027
1028 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001029 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001030
Emeric Brun9e754772019-01-10 17:51:55 +01001031 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001032
Emeric Brun9e754772019-01-10 17:51:55 +01001033 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1034 goto end;
1035
Willy Tarreau9356dac2019-05-10 09:22:53 +02001036 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001037 ret = 1;
1038 }
1039 else if (ref->key_size_bits == 256 ) {
1040
1041 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1042 goto end;
1043
Willy Tarreau9356dac2019-05-10 09:22:53 +02001044 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001045 ret = 1;
1046 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001047 } else {
1048 for (i = 0; i < TLS_TICKETS_NO; i++) {
1049 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1050 goto found;
1051 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001052 ret = 0;
1053 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001054
Christopher Faulet16f45c82018-02-16 11:23:49 +01001055 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001056 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001057 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 +01001058 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1059 goto end;
1060 /* 2 for key renewal, 1 if current key is still valid */
1061 ret = i ? 2 : 1;
1062 }
1063 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001064 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 +01001065 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1066 goto end;
1067 /* 2 for key renewal, 1 if current key is still valid */
1068 ret = i ? 2 : 1;
1069 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001070 }
Emeric Brun9e754772019-01-10 17:51:55 +01001071
Christopher Faulet16f45c82018-02-16 11:23:49 +01001072 end:
1073 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1074 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001075}
1076
1077struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1078{
1079 struct tls_keys_ref *ref;
1080
1081 list_for_each_entry(ref, &tlskeys_reference, list)
1082 if (ref->filename && strcmp(filename, ref->filename) == 0)
1083 return ref;
1084 return NULL;
1085}
1086
1087struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1088{
1089 struct tls_keys_ref *ref;
1090
1091 list_for_each_entry(ref, &tlskeys_reference, list)
1092 if (ref->unique_id == unique_id)
1093 return ref;
1094 return NULL;
1095}
1096
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001097/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001098 * match existing ones, this function returns -1
1099 * else it returns 0 on success.
1100 */
1101int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001102 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001103{
Emeric Brun9e754772019-01-10 17:51:55 +01001104 if (ref->key_size_bits == 128) {
1105 if (tlskey->data != sizeof(struct tls_sess_key_128))
1106 return -1;
1107 }
1108 else if (ref->key_size_bits == 256) {
1109 if (tlskey->data != sizeof(struct tls_sess_key_256))
1110 return -1;
1111 }
1112 else
1113 return -1;
1114
Christopher Faulet16f45c82018-02-16 11:23:49 +01001115 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001116 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1117 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001118 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1119 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001120
1121 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001122}
1123
Willy Tarreau83061a82018-07-13 11:56:34 +02001124int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001125{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001126 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1127
1128 if(!ref) {
1129 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1130 return 1;
1131 }
Emeric Brun9e754772019-01-10 17:51:55 +01001132 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1133 memprintf(err, "Invalid key size");
1134 return 1;
1135 }
1136
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001137 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001138}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001139
1140/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001141 * automatic ids. It's called just after the basic checks. It returns
1142 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001143 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001144static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001145{
1146 int i = 0;
1147 struct tls_keys_ref *ref, *ref2, *ref3;
1148 struct list tkr = LIST_HEAD_INIT(tkr);
1149
1150 list_for_each_entry(ref, &tlskeys_reference, list) {
1151 if (ref->unique_id == -1) {
1152 /* Look for the first free id. */
1153 while (1) {
1154 list_for_each_entry(ref2, &tlskeys_reference, list) {
1155 if (ref2->unique_id == i) {
1156 i++;
1157 break;
1158 }
1159 }
1160 if (&ref2->list == &tlskeys_reference)
1161 break;
1162 }
1163
1164 /* Uses the unique id and increment it for the next entry. */
1165 ref->unique_id = i;
1166 i++;
1167 }
1168 }
1169
1170 /* This sort the reference list by id. */
1171 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
1172 LIST_DEL(&ref->list);
1173 list_for_each_entry(ref3, &tkr, list) {
1174 if (ref->unique_id < ref3->unique_id) {
1175 LIST_ADDQ(&ref3->list, &ref->list);
1176 break;
1177 }
1178 }
1179 if (&ref3->list == &tkr)
1180 LIST_ADDQ(&tkr, &ref->list);
1181 }
1182
1183 /* swap root */
1184 LIST_ADD(&tkr, &tlskeys_reference);
1185 LIST_DEL(&tkr);
Willy Tarreaud1c57502016-12-22 22:46:15 +01001186 return 0;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001187}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001188#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1189
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001190#ifndef OPENSSL_NO_OCSP
yanbzhube2774d2015-12-10 15:07:30 -05001191int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1192{
1193 switch (evp_keytype) {
1194 case EVP_PKEY_RSA:
1195 return 2;
1196 case EVP_PKEY_DSA:
1197 return 0;
1198 case EVP_PKEY_EC:
1199 return 1;
1200 }
1201
1202 return -1;
1203}
1204
Emeric Brun4147b2e2014-06-16 18:36:30 +02001205/*
1206 * Callback used to set OCSP status extension content in server hello.
1207 */
1208int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1209{
yanbzhube2774d2015-12-10 15:07:30 -05001210 struct certificate_ocsp *ocsp;
1211 struct ocsp_cbk_arg *ocsp_arg;
1212 char *ssl_buf;
1213 EVP_PKEY *ssl_pkey;
1214 int key_type;
1215 int index;
1216
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001217 ocsp_arg = arg;
yanbzhube2774d2015-12-10 15:07:30 -05001218
1219 ssl_pkey = SSL_get_privatekey(ssl);
1220 if (!ssl_pkey)
1221 return SSL_TLSEXT_ERR_NOACK;
1222
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001223 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001224
1225 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1226 ocsp = ocsp_arg->s_ocsp;
1227 else {
1228 /* For multiple certs per context, we have to find the correct OCSP response based on
1229 * the certificate type
1230 */
1231 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1232
1233 if (index < 0)
1234 return SSL_TLSEXT_ERR_NOACK;
1235
1236 ocsp = ocsp_arg->m_ocsp[index];
1237
1238 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001239
1240 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001241 !ocsp->response.area ||
1242 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001243 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001244 return SSL_TLSEXT_ERR_NOACK;
1245
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001246 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001247 if (!ssl_buf)
1248 return SSL_TLSEXT_ERR_NOACK;
1249
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001250 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1251 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001252
1253 return SSL_TLSEXT_ERR_OK;
1254}
1255
William Lallemand4a660132019-10-14 14:51:41 +02001256#endif
1257
1258#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001259/*
1260 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001261 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1262 * status extension, the issuer's certificate is mandatory. It should be
1263 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001264 *
William Lallemand246c0242019-10-11 08:59:13 +02001265 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1266 * OCSP response. If file is empty or content is not a valid OCSP response,
1267 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1268 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001269 *
1270 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001271 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001272 */
William Lallemand4a660132019-10-14 14:51:41 +02001273#ifndef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001274static 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 +02001275{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001276 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001277 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001278 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001279 struct certificate_ocsp *ocsp = NULL, *iocsp;
1280 char *warn = NULL;
1281 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001282 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001283
Emeric Brun4147b2e2014-06-16 18:36:30 +02001284
William Lallemand246c0242019-10-11 08:59:13 +02001285 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001286 if (!x)
1287 goto out;
1288
William Lallemand246c0242019-10-11 08:59:13 +02001289 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001290 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1291 if (chain) {
1292 /* check if one of the certificate of the chain is the issuer */
1293 for (i = 0; i < sk_X509_num(chain); i++) {
1294 X509 *ti = sk_X509_value(chain, i);
1295 if (X509_check_issued(ti, x) == X509_V_OK) {
1296 issuer = ti;
1297 break;
1298 }
1299 }
1300 }
William Lallemand246c0242019-10-11 08:59:13 +02001301 if (!issuer)
1302 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001303
1304 cid = OCSP_cert_to_id(0, x, issuer);
1305 if (!cid)
1306 goto out;
1307
1308 i = i2d_OCSP_CERTID(cid, NULL);
1309 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1310 goto out;
1311
Vincent Bernat02779b62016-04-03 13:48:43 +02001312 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001313 if (!ocsp)
1314 goto out;
1315
1316 p = ocsp->key_data;
1317 i2d_OCSP_CERTID(cid, &p);
1318
1319 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1320 if (iocsp == ocsp)
1321 ocsp = NULL;
1322
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001323#ifndef SSL_CTX_get_tlsext_status_cb
1324# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1325 *cb = (void (*) (void))ctx->tlsext_status_cb;
1326#endif
1327 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1328
1329 if (!callback) {
Vincent Bernat02779b62016-04-03 13:48:43 +02001330 struct ocsp_cbk_arg *cb_arg = calloc(1, sizeof(*cb_arg));
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001331 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001332
1333 cb_arg->is_single = 1;
1334 cb_arg->s_ocsp = iocsp;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001335
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001336 pkey = X509_get_pubkey(x);
1337 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1338 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001339
1340 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
1341 SSL_CTX_set_tlsext_status_arg(ctx, cb_arg);
1342 } else {
1343 /*
1344 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1345 * Update that cb_arg with the new cert's staple
1346 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001347 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001348 struct certificate_ocsp *tmp_ocsp;
1349 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001350 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001351 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001352
1353#ifdef SSL_CTX_get_tlsext_status_arg
1354 SSL_CTX_ctrl(ctx, SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG, 0, &cb_arg);
1355#else
1356 cb_arg = ctx->tlsext_status_arg;
1357#endif
yanbzhube2774d2015-12-10 15:07:30 -05001358
1359 /*
1360 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1361 * the order of operations below matter, take care when changing it
1362 */
1363 tmp_ocsp = cb_arg->s_ocsp;
1364 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1365 cb_arg->s_ocsp = NULL;
1366 cb_arg->m_ocsp[index] = tmp_ocsp;
1367 cb_arg->is_single = 0;
1368 cb_arg->single_kt = 0;
1369
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001370 pkey = X509_get_pubkey(x);
1371 key_type = EVP_PKEY_base_id(pkey);
1372 EVP_PKEY_free(pkey);
1373
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001374 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
yanbzhube2774d2015-12-10 15:07:30 -05001375 if (index >= 0 && !cb_arg->m_ocsp[index])
1376 cb_arg->m_ocsp[index] = iocsp;
1377
1378 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001379
1380 ret = 0;
1381
1382 warn = NULL;
William Lallemand246c0242019-10-11 08:59:13 +02001383 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, ocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001384 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001385 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001386 }
1387
1388out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001389 if (cid)
1390 OCSP_CERTID_free(cid);
1391
1392 if (ocsp)
1393 free(ocsp);
1394
1395 if (warn)
1396 free(warn);
1397
Emeric Brun4147b2e2014-06-16 18:36:30 +02001398 return ret;
1399}
William Lallemand4a660132019-10-14 14:51:41 +02001400#else /* OPENSSL_IS_BORINGSSL */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001401static 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 +02001402{
William Lallemand4a660132019-10-14 14:51:41 +02001403 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 +02001404}
1405#endif
1406
William Lallemand4a660132019-10-14 14:51:41 +02001407#endif
1408
1409
Willy Tarreau5db847a2019-05-09 14:13:35 +02001410#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001411
1412#define CT_EXTENSION_TYPE 18
1413
William Lallemand03c331c2020-05-13 10:10:01 +02001414int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001415
1416int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1417{
Willy Tarreau83061a82018-07-13 11:56:34 +02001418 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001419
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001420 *out = (unsigned char *) sctl->area;
1421 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001422
1423 return 1;
1424}
1425
1426int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1427{
1428 return 1;
1429}
1430
William Lallemanda17f4112019-10-10 15:16:44 +02001431static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001432{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001433 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001434
William Lallemanda17f4112019-10-10 15:16:44 +02001435 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 +01001436 goto out;
1437
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001438 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1439
1440 ret = 0;
1441
1442out:
1443 return ret;
1444}
1445
1446#endif
1447
Emeric Brune1f38db2012-09-03 20:36:47 +02001448void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1449{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001450 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001451 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001452 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001453 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001454
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001455#ifndef SSL_OP_NO_RENEGOTIATION
1456 /* Please note that BoringSSL defines this macro to zero so don't
1457 * change this to #if and do not assign a default value to this macro!
1458 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001459 if (where & SSL_CB_HANDSHAKE_START) {
1460 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001461 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 +02001462 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001463 conn->err_code = CO_ER_SSL_RENEG;
1464 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001465 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001466#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001467
1468 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001469 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001470 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001471 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001472 consider that the buffering was activated,
1473 so we rise the output buffer size from 4k
1474 to 16k */
1475 write_bio = SSL_get_wbio(ssl);
1476 if (write_bio != SSL_get_rbio(ssl)) {
1477 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001478 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001479 }
1480 }
1481 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001482}
1483
Emeric Brune64aef12012-09-21 13:15:06 +02001484/* Callback is called for each certificate of the chain during a verify
1485 ok is set to 1 if preverify detect no error on current certificate.
1486 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001487int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001488{
1489 SSL *ssl;
1490 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001491 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001492 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001493
1494 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001495 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001496
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001497 ctx = conn->xprt_ctx;
1498
1499 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001500
Emeric Brun81c00f02012-09-21 14:31:21 +02001501 if (ok) /* no errors */
1502 return ok;
1503
1504 depth = X509_STORE_CTX_get_error_depth(x_store);
1505 err = X509_STORE_CTX_get_error(x_store);
1506
1507 /* check if CA error needs to be ignored */
1508 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001509 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1510 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1511 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001512 }
1513
Willy Tarreau731248f2020-02-04 14:02:02 +01001514 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001515 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001516 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001517 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001518 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001519
Willy Tarreau20879a02012-12-03 16:32:10 +01001520 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001521 return 0;
1522 }
1523
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001524 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1525 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001526
Emeric Brun81c00f02012-09-21 14:31:21 +02001527 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001528 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001529 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001530 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001531 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001532 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001533
Willy Tarreau20879a02012-12-03 16:32:10 +01001534 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001535 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001536}
1537
Dragan Dosen9ac98092020-05-11 15:51:45 +02001538#ifdef TLS1_RT_HEARTBEAT
1539static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1540 int content_type, const void *buf, size_t len,
1541 SSL *ssl)
1542{
1543 /* test heartbeat received (write_p is set to 0
1544 for a received record) */
1545 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1546 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1547 const unsigned char *p = buf;
1548 unsigned int payload;
1549
1550 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1551
1552 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1553 if (*p != TLS1_HB_REQUEST)
1554 return;
1555
1556 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1557 goto kill_it;
1558
1559 payload = (p[1] * 256) + p[2];
1560 if (3 + payload + 16 <= len)
1561 return; /* OK no problem */
1562 kill_it:
1563 /* We have a clear heartbleed attack (CVE-2014-0160), the
1564 * advertised payload is larger than the advertised packet
1565 * length, so we have garbage in the buffer between the
1566 * payload and the end of the buffer (p+len). We can't know
1567 * if the SSL stack is patched, and we don't know if we can
1568 * safely wipe out the area between p+3+len and payload.
1569 * So instead, we prevent the response from being sent by
1570 * setting the max_send_fragment to 0 and we report an SSL
1571 * error, which will kill this connection. It will be reported
1572 * above as SSL_ERROR_SSL while an other handshake failure with
1573 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1574 */
1575 ssl->max_send_fragment = 0;
1576 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1577 }
1578}
1579#endif
1580
1581static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1582 int content_type, const void *buf, size_t len,
1583 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001584{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001585 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001586 unsigned char *msg;
1587 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001588 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001589
1590 /* This function is called for "from client" and "to server"
1591 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001592 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001593 */
1594
1595 /* "write_p" is set to 0 is the bytes are received messages,
1596 * otherwise it is set to 1.
1597 */
1598 if (write_p != 0)
1599 return;
1600
1601 /* content_type contains the type of message received or sent
1602 * according with the SSL/TLS protocol spec. This message is
1603 * encoded with one byte. The value 256 (two bytes) is used
1604 * for designing the SSL/TLS record layer. According with the
1605 * rfc6101, the expected message (other than 256) are:
1606 * - change_cipher_spec(20)
1607 * - alert(21)
1608 * - handshake(22)
1609 * - application_data(23)
1610 * - (255)
1611 * We are interessed by the handshake and specially the client
1612 * hello.
1613 */
1614 if (content_type != 22)
1615 return;
1616
1617 /* The message length is at least 4 bytes, containing the
1618 * message type and the message length.
1619 */
1620 if (len < 4)
1621 return;
1622
1623 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001624 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001625 * - hello_request(0)
1626 * - client_hello(1)
1627 * - server_hello(2)
1628 * - certificate(11)
1629 * - server_key_exchange (12)
1630 * - certificate_request(13)
1631 * - server_hello_done(14)
1632 * We are interested by the client hello.
1633 */
1634 msg = (unsigned char *)buf;
1635 if (msg[0] != 1)
1636 return;
1637
1638 /* Next three bytes are the length of the message. The total length
1639 * must be this decoded length + 4. If the length given as argument
1640 * is not the same, we abort the protocol dissector.
1641 */
1642 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1643 if (len < rec_len + 4)
1644 return;
1645 msg += 4;
1646 end = msg + rec_len;
1647 if (end < msg)
1648 return;
1649
1650 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1651 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001652 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1653 */
1654 msg += 1 + 1 + 4 + 28;
1655 if (msg > end)
1656 return;
1657
1658 /* Next, is session id:
1659 * if present, we have to jump by length + 1 for the size information
1660 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001661 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001662 if (msg[0] > 0)
1663 msg += msg[0];
1664 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001665 if (msg > end)
1666 return;
1667
1668 /* Next two bytes are the ciphersuite length. */
1669 if (msg + 2 > end)
1670 return;
1671 rec_len = (msg[0] << 8) + msg[1];
1672 msg += 2;
1673 if (msg + rec_len > end || msg + rec_len < msg)
1674 return;
1675
Willy Tarreaubafbe012017-11-24 17:34:44 +01001676 capture = pool_alloc_dirty(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001677 if (!capture)
1678 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001679 /* Compute the xxh64 of the ciphersuite. */
1680 capture->xxh64 = XXH64(msg, rec_len, 0);
1681
1682 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001683 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1684 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001685 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001686
1687 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001688}
1689
Emeric Brun29f037d2014-04-25 19:05:36 +02001690/* Callback is called for ssl protocol analyse */
1691void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1692{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001693 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1694 struct ssl_sock_msg_callback *cbk;
1695
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001696 /* Try to call all callback functions that were registered by using
1697 * ssl_sock_register_msg_callback().
1698 */
1699 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1700 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1701 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001702}
1703
Bernard Spil13c53f82018-02-15 13:34:58 +01001704#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001705static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1706 const unsigned char *in, unsigned int inlen,
1707 void *arg)
1708{
1709 struct server *srv = arg;
1710
1711 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1712 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1713 return SSL_TLSEXT_ERR_OK;
1714 return SSL_TLSEXT_ERR_NOACK;
1715}
1716#endif
1717
1718#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001719/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001720 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001721 */
1722static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1723 unsigned int *len, void *arg)
1724{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001725 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001726
1727 *data = (const unsigned char *)conf->npn_str;
1728 *len = conf->npn_len;
1729 return SSL_TLSEXT_ERR_OK;
1730}
1731#endif
1732
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001733#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001734/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001735 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001736 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001737static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1738 unsigned char *outlen,
1739 const unsigned char *server,
1740 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001741{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001742 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001743
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001744 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1745 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1746 return SSL_TLSEXT_ERR_NOACK;
1747 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001748 return SSL_TLSEXT_ERR_OK;
1749}
1750#endif
1751
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001752#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001753#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001754
Christopher Faulet30548802015-06-11 13:39:32 +02001755/* Create a X509 certificate with the specified servername and serial. This
1756 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001757static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001758ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001759{
Christopher Faulet7969a332015-10-09 11:15:03 +02001760 X509 *cacert = bind_conf->ca_sign_cert;
1761 EVP_PKEY *capkey = bind_conf->ca_sign_pkey;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001762 SSL_CTX *ssl_ctx = NULL;
1763 X509 *newcrt = NULL;
1764 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001765 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001766 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001767 X509_NAME *name;
1768 const EVP_MD *digest;
1769 X509V3_CTX ctx;
1770 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001771 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001772
Christopher Faulet48a83322017-07-28 16:56:09 +02001773 /* Get the private key of the default certificate and use it */
Willy Tarreau5db847a2019-05-09 14:13:35 +02001774#if (HA_OPENSSL_VERSION_NUMBER >= 0x10002000L)
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001775 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1776#else
1777 tmp_ssl = SSL_new(bind_conf->default_ctx);
1778 if (tmp_ssl)
1779 pkey = SSL_get_privatekey(tmp_ssl);
1780#endif
1781 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001782 goto mkcert_error;
1783
1784 /* Create the certificate */
1785 if (!(newcrt = X509_new()))
1786 goto mkcert_error;
1787
1788 /* Set version number for the certificate (X509v3) and the serial
1789 * number */
1790 if (X509_set_version(newcrt, 2L) != 1)
1791 goto mkcert_error;
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01001792 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001793
1794 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001795 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1796 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001797 goto mkcert_error;
1798
1799 /* set public key in the certificate */
1800 if (X509_set_pubkey(newcrt, pkey) != 1)
1801 goto mkcert_error;
1802
1803 /* Set issuer name from the CA */
1804 if (!(name = X509_get_subject_name(cacert)))
1805 goto mkcert_error;
1806 if (X509_set_issuer_name(newcrt, name) != 1)
1807 goto mkcert_error;
1808
1809 /* Set the subject name using the same, but the CN */
1810 name = X509_NAME_dup(name);
1811 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1812 (const unsigned char *)servername,
1813 -1, -1, 0) != 1) {
1814 X509_NAME_free(name);
1815 goto mkcert_error;
1816 }
1817 if (X509_set_subject_name(newcrt, name) != 1) {
1818 X509_NAME_free(name);
1819 goto mkcert_error;
1820 }
1821 X509_NAME_free(name);
1822
1823 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001824 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001825 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1826 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1827 X509_EXTENSION *ext;
1828
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001829 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001830 goto mkcert_error;
1831 if (!X509_add_ext(newcrt, ext, -1)) {
1832 X509_EXTENSION_free(ext);
1833 goto mkcert_error;
1834 }
1835 X509_EXTENSION_free(ext);
1836 }
1837
1838 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001839
1840 key_type = EVP_PKEY_base_id(capkey);
1841
1842 if (key_type == EVP_PKEY_DSA)
1843 digest = EVP_sha1();
1844 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001845 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001846 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001847 digest = EVP_sha256();
1848 else {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02001849#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000000fL) && !defined(OPENSSL_IS_BORINGSSL)
Christopher Faulet7969a332015-10-09 11:15:03 +02001850 int nid;
1851
1852 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1853 goto mkcert_error;
1854 if (!(digest = EVP_get_digestbynid(nid)))
1855 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02001856#else
1857 goto mkcert_error;
1858#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02001859 }
1860
Christopher Faulet31af49d2015-06-09 17:29:50 +02001861 if (!(X509_sign(newcrt, capkey, digest)))
1862 goto mkcert_error;
1863
1864 /* Create and set the new SSL_CTX */
1865 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
1866 goto mkcert_error;
1867 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1868 goto mkcert_error;
1869 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
1870 goto mkcert_error;
1871 if (!SSL_CTX_check_private_key(ssl_ctx))
1872 goto mkcert_error;
1873
1874 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02001875
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01001876#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001877 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01001878#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001879#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
1880 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001881 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001882 EC_KEY *ecc;
1883 int nid;
1884
1885 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
1886 goto end;
1887 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
1888 goto end;
1889 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
1890 EC_KEY_free(ecc);
1891 }
1892#endif
1893 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02001894 return ssl_ctx;
1895
1896 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001897 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001898 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001899 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
1900 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001901 return NULL;
1902}
1903
Christopher Faulet7969a332015-10-09 11:15:03 +02001904SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001905ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02001906{
Willy Tarreau07d94e42018-09-20 10:57:52 +02001907 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01001908 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001909
Olivier Houchard66ab4982019-02-26 18:37:15 +01001910 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02001911}
1912
Christopher Faulet30548802015-06-11 13:39:32 +02001913/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02001914 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02001915SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02001916ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02001917{
1918 struct lru64 *lru = NULL;
1919
1920 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001921 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001922 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02001923 if (lru && lru->domain) {
1924 if (ssl)
1925 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001926 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02001927 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02001928 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001929 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02001930 }
1931 return NULL;
1932}
1933
Emeric Brun821bb9b2017-06-15 16:37:39 +02001934/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
1935 * function is not thread-safe, it should only be used to check if a certificate
1936 * exists in the lru cache (with no warranty it will not be removed by another
1937 * thread). It is kept for backward compatibility. */
1938SSL_CTX *
1939ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
1940{
1941 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
1942}
1943
Christopher Fauletd2cab922015-07-28 16:03:47 +02001944/* Set a certificate int the LRU cache used to store generated
1945 * certificate. Return 0 on success, otherwise -1 */
1946int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001947ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02001948{
1949 struct lru64 *lru = NULL;
1950
1951 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001952 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001953 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02001954 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001955 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001956 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02001957 }
Christopher Faulet30548802015-06-11 13:39:32 +02001958 if (lru->domain && lru->data)
1959 lru->free((SSL_CTX *)lru->data);
Christopher Faulet7969a332015-10-09 11:15:03 +02001960 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001961 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001962 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02001963 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02001964 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02001965}
1966
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001967/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02001968unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001969ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02001970{
1971 return XXH32(data, len, ssl_ctx_lru_seed);
1972}
1973
Willy Tarreau2f63ef42015-10-20 15:16:01 +02001974/* Generate a cert and immediately assign it to the SSL session so that the cert's
1975 * refcount is maintained regardless of the cert's presence in the LRU cache.
1976 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02001977static int
Christopher Faulet7969a332015-10-09 11:15:03 +02001978ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001979{
1980 X509 *cacert = bind_conf->ca_sign_cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001981 SSL_CTX *ssl_ctx = NULL;
1982 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001983 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001984
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001985 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001986 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001987 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001988 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001989 if (lru && lru->domain)
1990 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02001991 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001992 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001993 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001994 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02001995 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001996 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02001997 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001998 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02001999 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002000 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002001 SSL_set_SSL_CTX(ssl, ssl_ctx);
2002 /* No LRU cache, this CTX will be released as soon as the session dies */
2003 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002004 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002005 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002006 return 0;
2007}
2008static int
2009ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2010{
2011 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002012 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002013
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002014 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002015 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002016 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002017 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002018 }
2019 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002020}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002021#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002022
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002023#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002024
2025static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002026{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002027#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002028 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002029 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2030#endif
2031}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002032static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2033 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002034 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2035}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002036static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002037#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002038 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002039 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2040#endif
2041}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002042static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002043#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002044 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002045 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2046#endif
2047}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002048/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002049static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2050/* Unusable in this context. */
2051static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2052static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2053static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2054static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2055static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002056#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002057
2058static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2059 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002060 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2061}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002062static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2063 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2064 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2065}
2066static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2067 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002068 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2069}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002070static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2071 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2072 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2073}
2074static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2075 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002076 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2077}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002078static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2079 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2080 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2081}
2082static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2083 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002084 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2085}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002086static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2087 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2088 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2089}
2090static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002091#if SSL_OP_NO_TLSv1_3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002092 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002093 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2094#endif
2095}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002096static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
2097#if SSL_OP_NO_TLSv1_3
2098 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2099 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002100#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002101}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002102#endif
2103static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2104static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002105
William Lallemand7fd8b452020-05-07 15:20:43 +02002106struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002107 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2108 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2109 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2110 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2111 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2112 {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 +02002113};
2114
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002115static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2116{
2117 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2118 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2119 SSL_set_SSL_CTX(ssl, ctx);
2120}
2121
Willy Tarreau5db847a2019-05-09 14:13:35 +02002122#if ((HA_OPENSSL_VERSION_NUMBER >= 0x10101000L) || defined(OPENSSL_IS_BORINGSSL))
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002123
2124static int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
2125{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002126 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002127 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002128
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002129 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2130 return SSL_TLSEXT_ERR_OK;
2131 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002132}
2133
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002134#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002135static int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
2136{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002137 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002138#else
2139static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
2140{
2141#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002142 struct connection *conn;
2143 struct bind_conf *s;
2144 const uint8_t *extension_data;
2145 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002146 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002147
2148 char *wildp = NULL;
2149 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002150 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002151 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002152 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002153 int i;
2154
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002155 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002156 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002157
Olivier Houchard9679ac92017-10-27 14:58:08 +02002158 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002159 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002160#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002161 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2162 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002163#else
2164 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2165#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002166 /*
2167 * The server_name extension was given too much extensibility when it
2168 * was written, so parsing the normal case is a bit complex.
2169 */
2170 size_t len;
2171 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002172 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002173 /* Extract the length of the supplied list of names. */
2174 len = (*extension_data++) << 8;
2175 len |= *extension_data++;
2176 if (len + 2 != extension_len)
2177 goto abort;
2178 /*
2179 * The list in practice only has a single element, so we only consider
2180 * the first one.
2181 */
2182 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2183 goto abort;
2184 extension_len = len - 1;
2185 /* Now we can finally pull out the byte array with the actual hostname. */
2186 if (extension_len <= 2)
2187 goto abort;
2188 len = (*extension_data++) << 8;
2189 len |= *extension_data++;
2190 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2191 || memchr(extension_data, 0, len) != NULL)
2192 goto abort;
2193 servername = extension_data;
2194 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002195 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002196#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2197 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002198 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002199 }
2200#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002201 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002202 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002203 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002204 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002205 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002206 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002207 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002208 goto abort;
2209 }
2210
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002211 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002212#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002213 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002214#else
2215 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2216#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002217 uint8_t sign;
2218 size_t len;
2219 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002220 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002221 len = (*extension_data++) << 8;
2222 len |= *extension_data++;
2223 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002224 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002225 if (len % 2 != 0)
2226 goto abort;
2227 for (; len > 0; len -= 2) {
2228 extension_data++; /* hash */
2229 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002230 switch (sign) {
2231 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002232 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002233 break;
2234 case TLSEXT_signature_ecdsa:
2235 has_ecdsa_sig = 1;
2236 break;
2237 default:
2238 continue;
2239 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002240 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002241 break;
2242 }
2243 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002244 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002245 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002246 }
2247 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002248 const SSL_CIPHER *cipher;
2249 size_t len;
2250 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002251 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002252#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002253 len = ctx->cipher_suites_len;
2254 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002255#else
2256 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2257#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002258 if (len % 2 != 0)
2259 goto abort;
2260 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002261#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002262 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002263 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002264#else
2265 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2266#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002267 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002268 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002269 break;
2270 }
2271 }
2272 }
2273
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002274 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002275 trash.area[i] = tolower(servername[i]);
2276 if (!wildp && (trash.area[i] == '.'))
2277 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002278 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002279 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002280
William Lallemand150bfa82019-09-19 17:12:49 +02002281 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002282
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002283 for (i = 0; i < 2; i++) {
2284 if (i == 0) /* lookup in full qualified names */
2285 node = ebst_lookup(&s->sni_ctx, trash.area);
2286 else if (i == 1 && wildp) /* lookup in wildcards names */
2287 node = ebst_lookup(&s->sni_w_ctx, wildp);
2288 else
2289 break;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002290 for (n = node; n; n = ebmb_next_dup(n)) {
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002291 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002292 if (!container_of(n, struct sni_ctx, name)->neg) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002293 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002294 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002295 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002296 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002297 break;
2298 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002299 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002300 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002301 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002302 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002303 if (!node_anonymous)
2304 node_anonymous = n;
2305 break;
2306 }
2307 }
2308 }
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002309 /* select by key_signature priority order */
2310 node = (has_ecdsa_sig && node_ecdsa) ? node_ecdsa
2311 : ((has_rsa_sig && node_rsa) ? node_rsa
2312 : (node_anonymous ? node_anonymous
2313 : (node_ecdsa ? node_ecdsa /* no ecdsa signature case (< TLSv1.2) */
2314 : node_rsa /* no rsa signature case (far far away) */
2315 )));
2316 if (node) {
2317 /* switch ctx */
2318 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2319 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
Olivier Houchard35a63cc2017-11-02 19:04:38 +01002320 if (conf) {
2321 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2322 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2323 if (conf->early_data)
2324 allow_early = 1;
2325 }
William Lallemand02010472019-10-18 11:02:19 +02002326 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchard35a63cc2017-11-02 19:04:38 +01002327 goto allow_early;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002328 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002329 }
William Lallemand150bfa82019-09-19 17:12:49 +02002330
William Lallemand02010472019-10-18 11:02:19 +02002331 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002332#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002333 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002334 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002335 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002336 }
2337#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002338 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002339 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002340 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002341 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002342 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002343 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02002344allow_early:
2345#ifdef OPENSSL_IS_BORINGSSL
2346 if (allow_early)
2347 SSL_set_early_data_enabled(ssl, 1);
2348#else
2349 if (!allow_early)
2350 SSL_set_max_early_data(ssl, 0);
2351#endif
2352 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002353 abort:
2354 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2355 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002356#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002357 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002358#else
2359 *al = SSL_AD_UNRECOGNIZED_NAME;
2360 return 0;
2361#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002362}
2363
2364#else /* OPENSSL_IS_BORINGSSL */
2365
Emeric Brunfc0421f2012-09-07 17:30:07 +02002366/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2367 * warning when no match is found, which implies the default (first) cert
2368 * will keep being used.
2369 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002370static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002371{
2372 const char *servername;
2373 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002374 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002375 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002376 int i;
2377 (void)al; /* shut gcc stupid warning */
2378
2379 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002380 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002381#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002382 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2383 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002384#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002385 if (s->strict_sni)
2386 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002387 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002388 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002389 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002390 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002391 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002392
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002393 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002394 if (!servername[i])
2395 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002396 trash.area[i] = tolower(servername[i]);
2397 if (!wildp && (trash.area[i] == '.'))
2398 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002399 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002400 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002401
William Lallemand150bfa82019-09-19 17:12:49 +02002402 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002403 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002404 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002405 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2406 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002407 if (!container_of(n, struct sni_ctx, name)->neg) {
2408 node = n;
2409 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002410 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002411 }
2412 if (!node && wildp) {
2413 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002414 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2415 /* lookup a not neg filter */
2416 if (!container_of(n, struct sni_ctx, name)->neg) {
2417 node = n;
2418 break;
2419 }
2420 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002421 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002422 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002423#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002424 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2425 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002426 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002427 return SSL_TLSEXT_ERR_OK;
2428 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002429#endif
William Lallemand21724f02019-11-04 17:56:13 +01002430 if (s->strict_sni) {
2431 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002432 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002433 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002434 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002435 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002436 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002437 }
2438
2439 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002440 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002441 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002442 return SSL_TLSEXT_ERR_OK;
2443}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002444#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002445#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2446
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002447#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002448
2449static DH * ssl_get_dh_1024(void)
2450{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002451 static unsigned char dh1024_p[]={
2452 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2453 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2454 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2455 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2456 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2457 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2458 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2459 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2460 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2461 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2462 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2463 };
2464 static unsigned char dh1024_g[]={
2465 0x02,
2466 };
2467
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002468 BIGNUM *p;
2469 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002470 DH *dh = DH_new();
2471 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002472 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2473 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002474
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002475 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002476 DH_free(dh);
2477 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002478 } else {
2479 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002480 }
2481 }
2482 return dh;
2483}
2484
2485static DH *ssl_get_dh_2048(void)
2486{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002487 static unsigned char dh2048_p[]={
2488 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2489 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2490 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2491 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2492 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2493 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2494 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2495 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2496 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2497 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2498 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2499 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2500 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2501 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2502 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2503 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2504 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2505 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2506 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2507 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2508 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2509 0xB7,0x1F,0x77,0xF3,
2510 };
2511 static unsigned char dh2048_g[]={
2512 0x02,
2513 };
2514
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002515 BIGNUM *p;
2516 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002517 DH *dh = DH_new();
2518 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002519 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2520 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002521
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002522 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002523 DH_free(dh);
2524 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002525 } else {
2526 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002527 }
2528 }
2529 return dh;
2530}
2531
2532static DH *ssl_get_dh_4096(void)
2533{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002534 static unsigned char dh4096_p[]={
2535 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2536 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2537 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2538 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2539 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2540 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2541 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2542 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2543 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2544 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2545 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2546 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2547 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2548 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2549 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2550 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2551 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2552 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2553 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2554 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2555 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2556 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2557 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2558 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2559 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2560 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2561 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2562 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2563 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2564 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2565 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2566 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2567 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2568 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2569 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2570 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2571 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2572 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2573 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2574 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2575 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2576 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2577 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002578 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002579 static unsigned char dh4096_g[]={
2580 0x02,
2581 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002582
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002583 BIGNUM *p;
2584 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002585 DH *dh = DH_new();
2586 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002587 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2588 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002589
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002590 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002591 DH_free(dh);
2592 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002593 } else {
2594 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002595 }
2596 }
2597 return dh;
2598}
2599
2600/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002601 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002602static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2603{
2604 DH *dh = NULL;
2605 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002606 int type;
2607
2608 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002609
2610 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2611 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2612 */
2613 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2614 keylen = EVP_PKEY_bits(pkey);
2615 }
2616
Willy Tarreauef934602016-12-22 23:12:01 +01002617 if (keylen > global_ssl.default_dh_param) {
2618 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002619 }
2620
Remi Gacogned3a341a2015-05-29 16:26:17 +02002621 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002622 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002623 }
2624 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002625 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002626 }
2627 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002628 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002629 }
2630
2631 return dh;
2632}
2633
Remi Gacogne47783ef2015-05-29 15:53:22 +02002634static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002635{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002636 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002637 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002638
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002639 if (in == NULL)
2640 goto end;
2641
Remi Gacogne47783ef2015-05-29 15:53:22 +02002642 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002643 goto end;
2644
Remi Gacogne47783ef2015-05-29 15:53:22 +02002645 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2646
2647end:
2648 if (in)
2649 BIO_free(in);
2650
Emeric Brune1b4ed42018-08-16 15:14:12 +02002651 ERR_clear_error();
2652
Remi Gacogne47783ef2015-05-29 15:53:22 +02002653 return dh;
2654}
2655
2656int ssl_sock_load_global_dh_param_from_file(const char *filename)
2657{
2658 global_dh = ssl_sock_get_dh_from_file(filename);
2659
2660 if (global_dh) {
2661 return 0;
2662 }
2663
2664 return -1;
2665}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002666#endif
2667
William Lallemand9117de92019-10-04 00:29:42 +02002668/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002669static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002670 struct bind_conf *s, struct ssl_bind_conf *conf,
2671 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002672{
2673 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002674 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002675
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002676 if (*name == '!') {
2677 neg = 1;
2678 name++;
2679 }
2680 if (*name == '*') {
2681 wild = 1;
2682 name++;
2683 }
2684 /* !* filter is a nop */
2685 if (neg && wild)
2686 return order;
2687 if (*name) {
2688 int j, len;
2689 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002690 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002691 trash.area[j] = tolower(name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002692 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002693 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002694 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002695
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002696 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002697 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002698 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002699 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002700 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002701 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002702 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002703 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002704 sc->order = order++;
2705 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002706 sc->wild = wild;
2707 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002708 sc->ckch_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02002709 LIST_ADDQ(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002710 }
2711 return order;
2712}
2713
William Lallemand6af03992019-07-23 15:00:54 +02002714/*
William Lallemand1d29c742019-10-04 00:53:29 +02002715 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2716 * This function can't return an error.
2717 *
2718 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2719 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002720void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002721{
2722
2723 struct sni_ctx *sc0, *sc0b, *sc1;
2724 struct ebmb_node *node;
William Lallemand21724f02019-11-04 17:56:13 +01002725 int def = 0;
William Lallemand1d29c742019-10-04 00:53:29 +02002726
2727 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2728
2729 /* ignore if sc0 was already inserted in a tree */
2730 if (sc0->name.node.leaf_p)
2731 continue;
2732
2733 /* Check for duplicates. */
2734 if (sc0->wild)
2735 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2736 else
2737 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2738
2739 for (; node; node = ebmb_next_dup(node)) {
2740 sc1 = ebmb_entry(node, struct sni_ctx, name);
2741 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2742 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2743 /* it's a duplicate, we should remove and free it */
2744 LIST_DEL(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002745 SSL_CTX_free(sc0->ctx);
William Lallemand1d29c742019-10-04 00:53:29 +02002746 free(sc0);
2747 sc0 = NULL;
William Lallemande15029b2019-10-14 10:46:58 +02002748 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002749 }
2750 }
2751
2752 /* if duplicate, ignore the insertion */
2753 if (!sc0)
2754 continue;
2755
2756 if (sc0->wild)
2757 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
2758 else
2759 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
William Lallemand21724f02019-11-04 17:56:13 +01002760
2761 /* replace the default_ctx if required with the first ctx */
2762 if (ckch_inst->is_default && !def) {
William Lallemand02e19a52020-04-08 16:11:26 +02002763 SSL_CTX_free(bind_conf->default_ctx);
2764 SSL_CTX_up_ref(sc0->ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002765 bind_conf->default_ctx = sc0->ctx;
2766 def = 1;
2767 }
William Lallemand1d29c742019-10-04 00:53:29 +02002768 }
2769}
2770
2771/*
William Lallemande3af8fb2019-10-08 11:36:53 +02002772 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02002773 */
William Lallemande3af8fb2019-10-08 11:36:53 +02002774struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02002775
William Lallemand2954c472020-03-06 21:54:13 +01002776/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02002777struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02002778
Emeric Brun7a883362019-10-17 13:27:40 +02002779/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002780 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02002781 * DH parameter is loaded into the SSL_CTX and if there is no
2782 * DH parameter available in ckchs nor in global, the default
2783 * DH parameters are applied on the SSL_CTX.
2784 * Returns a bitfield containing the flags:
2785 * ERR_FATAL in any fatal error case
2786 * ERR_ALERT if a reason of the error is availabine in err
2787 * ERR_WARN if a warning is available into err
2788 * The value 0 means there is no error nor warning and
2789 * the operation succeed.
2790 */
William Lallemandfa892222019-07-23 16:06:08 +02002791#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02002792static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
2793 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02002794{
Emeric Brun7a883362019-10-17 13:27:40 +02002795 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02002796 DH *dh = NULL;
2797
William Lallemanda8c73742019-07-31 18:31:34 +02002798 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02002799 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02002800 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
2801 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
2802 err && *err ? *err : "", path);
2803#if defined(SSL_CTX_set_dh_auto)
2804 SSL_CTX_set_dh_auto(ctx, 1);
2805 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2806 err && *err ? *err : "");
2807#else
2808 memprintf(err, "%s, DH ciphers won't be available.\n",
2809 err && *err ? *err : "");
2810#endif
2811 ret |= ERR_WARN;
2812 goto end;
2813 }
William Lallemandfa892222019-07-23 16:06:08 +02002814
2815 if (ssl_dh_ptr_index >= 0) {
2816 /* store a pointer to the DH params to avoid complaining about
2817 ssl-default-dh-param not being set for this SSL_CTX */
2818 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
2819 }
2820 }
2821 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02002822 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
2823 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
2824 err && *err ? *err : "", path);
2825#if defined(SSL_CTX_set_dh_auto)
2826 SSL_CTX_set_dh_auto(ctx, 1);
2827 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2828 err && *err ? *err : "");
2829#else
2830 memprintf(err, "%s, DH ciphers won't be available.\n",
2831 err && *err ? *err : "");
2832#endif
2833 ret |= ERR_WARN;
2834 goto end;
2835 }
William Lallemandfa892222019-07-23 16:06:08 +02002836 }
2837 else {
2838 /* Clear openssl global errors stack */
2839 ERR_clear_error();
2840
2841 if (global_ssl.default_dh_param <= 1024) {
2842 /* we are limited to DH parameter of 1024 bits anyway */
2843 if (local_dh_1024 == NULL)
2844 local_dh_1024 = ssl_get_dh_1024();
2845
Emeric Brun7a883362019-10-17 13:27:40 +02002846 if (local_dh_1024 == NULL) {
2847 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
2848 err && *err ? *err : "", path);
2849 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02002850 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02002851 }
William Lallemandfa892222019-07-23 16:06:08 +02002852
Emeric Bruna9363eb2019-10-17 14:53:03 +02002853 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
2854 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
2855 err && *err ? *err : "", path);
2856#if defined(SSL_CTX_set_dh_auto)
2857 SSL_CTX_set_dh_auto(ctx, 1);
2858 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2859 err && *err ? *err : "");
2860#else
2861 memprintf(err, "%s, DH ciphers won't be available.\n",
2862 err && *err ? *err : "");
2863#endif
2864 ret |= ERR_WARN;
2865 goto end;
2866 }
William Lallemandfa892222019-07-23 16:06:08 +02002867 }
2868 else {
2869 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
2870 }
William Lallemand8d0f8932019-10-17 18:03:58 +02002871 }
2872
William Lallemandf9568fc2019-10-16 18:27:58 +02002873end:
William Lallemandf9568fc2019-10-16 18:27:58 +02002874 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02002875 return ret;
2876}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02002877#endif
William Lallemandfa892222019-07-23 16:06:08 +02002878
yanbzhu488a4d22015-12-01 15:16:07 -05002879/* Loads the info in ckch into ctx
Emeric Bruna96b5822019-10-17 13:25:14 +02002880 * Returns a bitfield containing the flags:
2881 * ERR_FATAL in any fatal error case
2882 * ERR_ALERT if the reason of the error is available in err
2883 * ERR_WARN if a warning is available into err
2884 * The value 0 means there is no error nor warning and
2885 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05002886 */
2887static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
2888{
Emeric Bruna96b5822019-10-17 13:25:14 +02002889 int errcode = 0;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002890 STACK_OF(X509) *find_chain = NULL;
Emeric Bruna96b5822019-10-17 13:25:14 +02002891
yanbzhu488a4d22015-12-01 15:16:07 -05002892 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
2893 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
2894 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002895 errcode |= ERR_ALERT | ERR_FATAL;
2896 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05002897 }
2898
2899 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
2900 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
2901 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002902 errcode |= ERR_ALERT | ERR_FATAL;
2903 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05002904 }
2905
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002906 if (ckch->chain) {
2907 find_chain = ckch->chain;
2908 } else {
2909 /* Find Certificate Chain in global */
2910 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01002911 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002912 if (issuer)
2913 find_chain = issuer->chain;
2914 }
William Lallemand85888572020-02-27 14:48:35 +01002915
William Lallemandf187ce62020-06-02 18:27:20 +02002916 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
2917 if (find_chain)
2918#ifdef SSL_CTX_set1_chain
2919 if (!SSL_CTX_set1_chain(ctx, find_chain)) {
2920 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
2921 err && *err ? *err : "", path);
2922 errcode |= ERR_ALERT | ERR_FATAL;
2923 goto end;
2924 }
2925#else
2926 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002927 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02002928 STACK_OF(X509) *chain;
2929 chain = X509_chain_up_ref(find_chain);
2930 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002931 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002932 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
2933 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02002934 X509_free(ca);
2935 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002936 errcode |= ERR_ALERT | ERR_FATAL;
2937 goto end;
2938 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002939 }
William Lallemandf187ce62020-06-02 18:27:20 +02002940#endif
yanbzhu488a4d22015-12-01 15:16:07 -05002941
William Lallemandfa892222019-07-23 16:06:08 +02002942#ifndef OPENSSL_NO_DH
2943 /* store a NULL pointer to indicate we have not yet loaded
2944 a custom DH param file */
2945 if (ssl_dh_ptr_index >= 0) {
2946 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
2947 }
2948
Emeric Brun7a883362019-10-17 13:27:40 +02002949 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
2950 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02002951 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
2952 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002953 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02002954 }
2955#endif
2956
William Lallemanda17f4112019-10-10 15:16:44 +02002957#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
2958 if (sctl_ex_index >= 0 && ckch->sctl) {
2959 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
2960 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01002961 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002962 errcode |= ERR_ALERT | ERR_FATAL;
2963 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02002964 }
2965 }
2966#endif
2967
William Lallemand4a660132019-10-14 14:51:41 +02002968#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02002969 /* Load OCSP Info into context */
2970 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01002971 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01002972 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",
2973 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002974 errcode |= ERR_ALERT | ERR_FATAL;
2975 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02002976 }
2977 }
William Lallemand246c0242019-10-11 08:59:13 +02002978#endif
2979
Emeric Bruna96b5822019-10-17 13:25:14 +02002980 end:
2981 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05002982}
2983
William Lallemandc4ecddf2019-07-31 16:50:08 +02002984#if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
yanbzhu08ce6ab2015-12-02 13:01:29 -05002985
William Lallemand28a8fce2019-10-04 17:36:55 +02002986static int ssl_sock_populate_sni_keytypes_hplr(const char *str, struct eb_root *sni_keytypes, int key_index)
yanbzhu08ce6ab2015-12-02 13:01:29 -05002987{
2988 struct sni_keytype *s_kt = NULL;
2989 struct ebmb_node *node;
2990 int i;
2991
2992 for (i = 0; i < trash.size; i++) {
2993 if (!str[i])
2994 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002995 trash.area[i] = tolower(str[i]);
yanbzhu08ce6ab2015-12-02 13:01:29 -05002996 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002997 trash.area[i] = 0;
2998 node = ebst_lookup(sni_keytypes, trash.area);
yanbzhu08ce6ab2015-12-02 13:01:29 -05002999 if (!node) {
3000 /* CN not found in tree */
3001 s_kt = malloc(sizeof(struct sni_keytype) + i + 1);
3002 /* Using memcpy here instead of strncpy.
3003 * strncpy will cause sig_abrt errors under certain versions of gcc with -O2
3004 * See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60792
3005 */
William Lallemand28a8fce2019-10-04 17:36:55 +02003006 if (!s_kt)
3007 return -1;
3008
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003009 memcpy(s_kt->name.key, trash.area, i+1);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003010 s_kt->keytypes = 0;
3011 ebst_insert(sni_keytypes, &s_kt->name);
3012 } else {
3013 /* CN found in tree */
3014 s_kt = container_of(node, struct sni_keytype, name);
3015 }
3016
3017 /* Mark that this CN has the keytype of key_index via keytypes mask */
3018 s_kt->keytypes |= 1<<key_index;
3019
William Lallemand28a8fce2019-10-04 17:36:55 +02003020 return 0;
3021
William Lallemand6af03992019-07-23 15:00:54 +02003022}
3023
William Lallemandc4ecddf2019-07-31 16:50:08 +02003024#endif
William Lallemand36b84632019-07-18 19:28:17 +02003025
William Lallemandc4ecddf2019-07-31 16:50:08 +02003026#if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
3027
William Lallemand36b84632019-07-18 19:28:17 +02003028/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003029 * Take a ckch_store which contains a multi-certificate bundle.
William Lallemand36b84632019-07-18 19:28:17 +02003030 * Group these certificates into a set of SSL_CTX*
yanbzhu08ce6ab2015-12-02 13:01:29 -05003031 * based on shared and unique CN and SAN entries. Add these SSL_CTX* to the SNI tree.
3032 *
Joseph Herlant017b3da2018-11-15 09:07:59 -08003033 * This will allow the user to explicitly group multiple cert/keys for a single purpose
yanbzhu08ce6ab2015-12-02 13:01:29 -05003034 *
Emeric Brun054563d2019-10-17 13:16:58 +02003035 * Returns a bitfield containing the flags:
3036 * ERR_FATAL in any fatal error case
3037 * ERR_ALERT if the reason of the error is available in err
3038 * ERR_WARN if a warning is available into err
William Lallemand36b84632019-07-18 19:28:17 +02003039 *
yanbzhu08ce6ab2015-12-02 13:01:29 -05003040 */
William Lallemandda8584c2020-05-14 10:14:37 +02003041int ckch_inst_new_load_multi_store(const char *path, struct ckch_store *ckchs,
3042 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
3043 char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
yanbzhu08ce6ab2015-12-02 13:01:29 -05003044{
William Lallemand36b84632019-07-18 19:28:17 +02003045 int i = 0, n = 0;
3046 struct cert_key_and_chain *certs_and_keys;
William Lallemand4b989f22019-10-04 18:36:55 +02003047 struct eb_root sni_keytypes_map = EB_ROOT;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003048 struct ebmb_node *node;
3049 struct ebmb_node *next;
3050 /* Array of SSL_CTX pointers corresponding to each possible combo
3051 * of keytypes
3052 */
3053 struct key_combo_ctx key_combos[SSL_SOCK_POSSIBLE_KT_COMBOS] = { {0} };
Emeric Brun054563d2019-10-17 13:16:58 +02003054 int errcode = 0;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003055 X509_NAME *xname = NULL;
3056 char *str = NULL;
3057#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3058 STACK_OF(GENERAL_NAME) *names = NULL;
3059#endif
William Lallemand614ca0d2019-10-07 13:52:11 +02003060 struct ckch_inst *ckch_inst;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003061
Emeric Brun054563d2019-10-17 13:16:58 +02003062 *ckchi = NULL;
3063
William Lallemande3af8fb2019-10-08 11:36:53 +02003064 if (!ckchs || !ckchs->ckch || !ckchs->multi) {
William Lallemand36b84632019-07-18 19:28:17 +02003065 memprintf(err, "%sunable to load SSL certificate file '%s' file does not exist.\n",
3066 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003067 return ERR_ALERT | ERR_FATAL;
William Lallemand614ca0d2019-10-07 13:52:11 +02003068 }
3069
3070 ckch_inst = ckch_inst_new();
3071 if (!ckch_inst) {
3072 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3073 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003074 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand614ca0d2019-10-07 13:52:11 +02003075 goto end;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003076 }
3077
William Lallemande3af8fb2019-10-08 11:36:53 +02003078 certs_and_keys = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003079
yanbzhu08ce6ab2015-12-02 13:01:29 -05003080 /* Process each ckch and update keytypes for each CN/SAN
3081 * for example, if CN/SAN www.a.com is associated with
3082 * certs with keytype 0 and 2, then at the end of the loop,
3083 * www.a.com will have:
3084 * keyindex = 0 | 1 | 4 = 5
3085 */
3086 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
William Lallemand28a8fce2019-10-04 17:36:55 +02003087 int ret;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003088
3089 if (!ssl_sock_is_ckch_valid(&certs_and_keys[n]))
3090 continue;
3091
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003092 if (fcount) {
William Lallemand28a8fce2019-10-04 17:36:55 +02003093 for (i = 0; i < fcount; i++) {
3094 ret = ssl_sock_populate_sni_keytypes_hplr(sni_filter[i], &sni_keytypes_map, n);
3095 if (ret < 0) {
3096 memprintf(err, "%sunable to allocate SSL context.\n",
3097 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003098 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003099 goto end;
3100 }
3101 }
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003102 } else {
3103 /* A lot of the following code is OpenSSL boilerplate for processing CN's and SAN's,
3104 * so the line that contains logic is marked via comments
3105 */
3106 xname = X509_get_subject_name(certs_and_keys[n].cert);
3107 i = -1;
3108 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3109 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003110 ASN1_STRING *value;
3111 value = X509_NAME_ENTRY_get_data(entry);
3112 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003113 /* Important line is here */
William Lallemand28a8fce2019-10-04 17:36:55 +02003114 ret = ssl_sock_populate_sni_keytypes_hplr(str, &sni_keytypes_map, n);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003115
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003116 OPENSSL_free(str);
3117 str = NULL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003118 if (ret < 0) {
3119 memprintf(err, "%sunable to allocate SSL context.\n",
3120 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003121 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003122 goto end;
3123 }
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003124 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003125 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003126
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003127 /* Do the above logic for each SAN */
yanbzhu08ce6ab2015-12-02 13:01:29 -05003128#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003129 names = X509_get_ext_d2i(certs_and_keys[n].cert, NID_subject_alt_name, NULL, NULL);
3130 if (names) {
3131 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3132 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003133
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003134 if (name->type == GEN_DNS) {
3135 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
3136 /* Important line is here */
William Lallemand28a8fce2019-10-04 17:36:55 +02003137 ret = ssl_sock_populate_sni_keytypes_hplr(str, &sni_keytypes_map, n);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003138
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003139 OPENSSL_free(str);
3140 str = NULL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003141 if (ret < 0) {
3142 memprintf(err, "%sunable to allocate SSL context.\n",
3143 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003144 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003145 goto end;
3146 }
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003147 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003148 }
3149 }
3150 }
3151 }
3152#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
3153 }
3154
3155 /* If no files found, return error */
3156 if (eb_is_empty(&sni_keytypes_map)) {
3157 memprintf(err, "%sunable to load SSL certificate file '%s' file does not exist.\n",
3158 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003159 errcode |= ERR_ALERT | ERR_FATAL;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003160 goto end;
3161 }
3162
3163 /* We now have a map of CN/SAN to keytypes that are loaded in
3164 * Iterate through the map to create the SSL_CTX's (if needed)
3165 * and add each CTX to the SNI tree
3166 *
3167 * Some math here:
Joseph Herlant017b3da2018-11-15 09:07:59 -08003168 * There are 2^n - 1 possible combinations, each unique
yanbzhu08ce6ab2015-12-02 13:01:29 -05003169 * combination is denoted by the key in the map. Each key
3170 * has a value between 1 and 2^n - 1. Conveniently, the array
3171 * of SSL_CTX* is sized 2^n. So, we can simply use the i'th
3172 * entry in the array to correspond to the unique combo (key)
3173 * associated with i. This unique key combo (i) will be associated
3174 * with combos[i-1]
3175 */
3176
3177 node = ebmb_first(&sni_keytypes_map);
3178 while (node) {
3179 SSL_CTX *cur_ctx;
Bertrand Jacquin33423092016-11-13 16:37:13 +00003180 char cur_file[MAXPATHLEN+1];
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003181 const struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
yanbzhu08ce6ab2015-12-02 13:01:29 -05003182
3183 str = (char *)container_of(node, struct sni_keytype, name)->name.key;
3184 i = container_of(node, struct sni_keytype, name)->keytypes;
3185 cur_ctx = key_combos[i-1].ctx;
3186
3187 if (cur_ctx == NULL) {
3188 /* need to create SSL_CTX */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003189 cur_ctx = SSL_CTX_new(SSLv23_server_method());
yanbzhu08ce6ab2015-12-02 13:01:29 -05003190 if (cur_ctx == NULL) {
3191 memprintf(err, "%sunable to allocate SSL context.\n",
3192 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003193 errcode |= ERR_ALERT | ERR_FATAL;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003194 goto end;
3195 }
3196
yanbzhube2774d2015-12-10 15:07:30 -05003197 /* Load all required certs/keys/chains/OCSPs info into SSL_CTX */
yanbzhu08ce6ab2015-12-02 13:01:29 -05003198 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3199 if (i & (1<<n)) {
3200 /* Key combo contains ckch[n] */
Bertrand Jacquin33423092016-11-13 16:37:13 +00003201 snprintf(cur_file, MAXPATHLEN+1, "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
Emeric Bruna96b5822019-10-17 13:25:14 +02003202 errcode |= ssl_sock_put_ckch_into_ctx(cur_file, &certs_and_keys[n], cur_ctx, err);
3203 if (errcode & ERR_CODE)
yanbzhu08ce6ab2015-12-02 13:01:29 -05003204 goto end;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003205 }
3206 }
3207
yanbzhu08ce6ab2015-12-02 13:01:29 -05003208 /* Update key_combos */
3209 key_combos[i-1].ctx = cur_ctx;
3210 }
3211
3212 /* Update SNI Tree */
William Lallemand9117de92019-10-04 00:29:42 +02003213
William Lallemand1d29c742019-10-04 00:53:29 +02003214 key_combos[i-1].order = ckch_inst_add_cert_sni(cur_ctx, ckch_inst, bind_conf, ssl_conf,
William Lallemandfe49bb32019-10-03 23:46:33 +02003215 kinfo, str, key_combos[i-1].order);
3216 if (key_combos[i-1].order < 0) {
3217 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003218 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandfe49bb32019-10-03 23:46:33 +02003219 goto end;
3220 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003221 node = ebmb_next(node);
3222 }
3223
3224
3225 /* Mark a default context if none exists, using the ctx that has the most shared keys */
3226 if (!bind_conf->default_ctx) {
3227 for (i = SSL_SOCK_POSSIBLE_KT_COMBOS - 1; i >= 0; i--) {
3228 if (key_combos[i].ctx) {
3229 bind_conf->default_ctx = key_combos[i].ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003230 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003231 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003232 SSL_CTX_up_ref(bind_conf->default_ctx);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003233 break;
3234 }
3235 }
3236 }
3237
William Lallemand614ca0d2019-10-07 13:52:11 +02003238 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003239 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003240 ckch_inst->ckch_store = ckchs;
William Lallemand02e19a52020-04-08 16:11:26 +02003241
yanbzhu08ce6ab2015-12-02 13:01:29 -05003242end:
3243
3244 if (names)
3245 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
3246
yanbzhu08ce6ab2015-12-02 13:01:29 -05003247 node = ebmb_first(&sni_keytypes_map);
3248 while (node) {
3249 next = ebmb_next(node);
3250 ebmb_delete(node);
William Lallemand8ed5b962019-10-04 17:24:39 +02003251 free(ebmb_entry(node, struct sni_keytype, name));
yanbzhu08ce6ab2015-12-02 13:01:29 -05003252 node = next;
3253 }
3254
William Lallemand02e19a52020-04-08 16:11:26 +02003255 /* we need to free the ctx since we incremented the refcount where it's used */
3256 for (i = 0; i < SSL_SOCK_POSSIBLE_KT_COMBOS; i++) {
3257 if (key_combos[i].ctx)
3258 SSL_CTX_free(key_combos[i].ctx);
3259 }
3260
Emeric Brun054563d2019-10-17 13:16:58 +02003261 if (errcode & ERR_CODE && ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003262 if (ckch_inst->is_default) {
3263 SSL_CTX_free(bind_conf->default_ctx);
3264 bind_conf->default_ctx = NULL;
3265 }
3266
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003267 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003268 ckch_inst = NULL;
William Lallemand0c6d12f2019-10-04 18:38:51 +02003269 }
3270
Emeric Brun054563d2019-10-17 13:16:58 +02003271 *ckchi = ckch_inst;
3272 return errcode;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003273}
3274#else
3275/* This is a dummy, that just logs an error and returns error */
William Lallemandda8584c2020-05-14 10:14:37 +02003276int ckch_inst_new_load_multi_store(const char *path, struct ckch_store *ckchs,
3277 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
3278 char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
yanbzhu08ce6ab2015-12-02 13:01:29 -05003279{
3280 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3281 err && *err ? *err : "", path, strerror(errno));
Emeric Brun054563d2019-10-17 13:16:58 +02003282 return ERR_ALERT | ERR_FATAL;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003283}
3284
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003285#endif /* #if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL: Support for loading multiple certs into a single SSL_CTX */
yanbzhu488a4d22015-12-01 15:16:07 -05003286
William Lallemand614ca0d2019-10-07 13:52:11 +02003287/*
3288 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003289 *
3290 * Returns a bitfield containing the flags:
3291 * ERR_FATAL in any fatal error case
3292 * ERR_ALERT if the reason of the error is available in err
3293 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003294 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003295int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003296 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003297{
William Lallemandc9402072019-05-15 15:33:54 +02003298 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003299 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003300 int order = 0;
3301 X509_NAME *xname;
3302 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003303 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003304 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003305#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3306 STACK_OF(GENERAL_NAME) *names;
3307#endif
William Lallemand36b84632019-07-18 19:28:17 +02003308 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003309 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003310 int errcode = 0;
3311
3312 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003313
William Lallemande3af8fb2019-10-08 11:36:53 +02003314 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003315 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003316
William Lallemande3af8fb2019-10-08 11:36:53 +02003317 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003318
William Lallemandc9402072019-05-15 15:33:54 +02003319 ctx = SSL_CTX_new(SSLv23_server_method());
3320 if (!ctx) {
3321 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3322 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003323 errcode |= ERR_ALERT | ERR_FATAL;
3324 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003325 }
3326
Emeric Bruna96b5822019-10-17 13:25:14 +02003327 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3328 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003329 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003330
3331 ckch_inst = ckch_inst_new();
3332 if (!ckch_inst) {
3333 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3334 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003335 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003336 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003337 }
3338
William Lallemand36b84632019-07-18 19:28:17 +02003339 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003340 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003341 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003342 switch(EVP_PKEY_base_id(pkey)) {
3343 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003344 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003345 break;
3346 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003347 kinfo.sig = TLSEXT_signature_ecdsa;
3348 break;
3349 case EVP_PKEY_DSA:
3350 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003351 break;
3352 }
3353 EVP_PKEY_free(pkey);
3354 }
3355
Emeric Brun50bcecc2013-04-22 13:05:23 +02003356 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003357 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003358 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 +02003359 if (order < 0) {
3360 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003361 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003362 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003363 }
3364 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003365 }
3366 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003367#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003368 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003369 if (names) {
3370 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3371 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3372 if (name->type == GEN_DNS) {
3373 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003374 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003375 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003376 if (order < 0) {
3377 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003378 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003379 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003380 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003381 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003382 }
3383 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003384 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003385 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003386#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003387 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003388 i = -1;
3389 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3390 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003391 ASN1_STRING *value;
3392
3393 value = X509_NAME_ENTRY_get_data(entry);
3394 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003395 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003396 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003397 if (order < 0) {
3398 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003399 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003400 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003401 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003402 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003403 }
3404 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003405 /* we must not free the SSL_CTX anymore below, since it's already in
3406 * the tree, so it will be discovered and cleaned in time.
3407 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003408
Emeric Brunfc0421f2012-09-07 17:30:07 +02003409#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003410 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003411 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3412 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003413 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003414 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003415 }
3416#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003417 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003418 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003419 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003420 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003421 SSL_CTX_up_ref(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003422 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003423
William Lallemand9117de92019-10-04 00:29:42 +02003424 /* everything succeed, the ckch instance can be used */
3425 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003426 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003427 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003428
William Lallemand02e19a52020-04-08 16:11:26 +02003429 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3430
Emeric Brun054563d2019-10-17 13:16:58 +02003431 *ckchi = ckch_inst;
3432 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003433
3434error:
3435 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003436 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003437 if (ckch_inst->is_default)
3438 SSL_CTX_free(ctx);
3439
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003440 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003441 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003442 }
William Lallemandd9199372019-10-04 15:37:05 +02003443 SSL_CTX_free(ctx);
3444
Emeric Brun054563d2019-10-17 13:16:58 +02003445 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003446}
3447
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003448/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003449static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3450 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003451 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003452{
Emeric Brun054563d2019-10-17 13:16:58 +02003453 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003454
3455 /* we found the ckchs in the tree, we can use it directly */
3456 if (ckchs->multi)
William Lallemand24bde432020-03-09 16:48:43 +01003457 errcode |= ckch_inst_new_load_multi_store(path, ckchs, bind_conf, ssl_conf, sni_filter, fcount, ckch_inst, err);
William Lallemand614ca0d2019-10-07 13:52:11 +02003458 else
William Lallemand24bde432020-03-09 16:48:43 +01003459 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 +02003460
Emeric Brun054563d2019-10-17 13:16:58 +02003461 if (errcode & ERR_CODE)
3462 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003463
William Lallemand24bde432020-03-09 16:48:43 +01003464 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003465
3466 /* succeed, add the instance to the ckch_store's list of instance */
William Lallemand24bde432020-03-09 16:48:43 +01003467 LIST_ADDQ(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003468 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003469}
3470
William Lallemand6be66ec2020-03-06 22:26:32 +01003471
William Lallemand4c68bba2020-03-30 18:45:10 +02003472
3473
3474/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3475 * done once. Zero is returned if the operation fails. No error is returned
3476 * if the random is said as not implemented, because we expect that openssl
3477 * will use another method once needed.
3478 */
3479static int ssl_initialize_random()
3480{
3481 unsigned char random;
3482 static int random_initialized = 0;
3483
3484 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3485 random_initialized = 1;
3486
3487 return random_initialized;
3488}
3489
William Lallemand2954c472020-03-06 21:54:13 +01003490/* Load a crt-list file, this is done in 2 parts:
3491 * - store the content of the file in a crtlist structure with crtlist_entry structures
3492 * - generate the instances by iterating on entries in the crtlist struct
3493 *
3494 * Nothing is locked there, this function is used in the configuration parser.
3495 *
3496 * Returns a set of ERR_* flags possibly with an error in <err>.
3497 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003498int 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 +01003499{
3500 struct crtlist *crtlist = NULL;
3501 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003502 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003503 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003504 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003505 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003506
William Lallemand79d31ec2020-03-25 15:10:49 +01003507 bind_conf_node = malloc(sizeof(*bind_conf_node));
3508 if (!bind_conf_node) {
3509 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3510 cfgerr |= ERR_FATAL | ERR_ALERT;
3511 goto error;
3512 }
3513 bind_conf_node->next = NULL;
3514 bind_conf_node->bind_conf = bind_conf;
3515
William Lallemand41ca9302020-04-08 13:15:18 +02003516 /* strip trailing slashes, including first one */
3517 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3518 *end = 0;
3519
William Lallemand2954c472020-03-06 21:54:13 +01003520 /* look for an existing crtlist or create one */
3521 eb = ebst_lookup(&crtlists_tree, file);
3522 if (eb) {
3523 crtlist = ebmb_entry(eb, struct crtlist, node);
3524 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003525 /* load a crt-list OR a directory */
3526 if (dir)
3527 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3528 else
3529 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3530
William Lallemand2954c472020-03-06 21:54:13 +01003531 if (!(cfgerr & ERR_CODE))
3532 ebst_insert(&crtlists_tree, &crtlist->node);
3533 }
3534
3535 if (cfgerr & ERR_CODE) {
3536 cfgerr |= ERR_FATAL | ERR_ALERT;
3537 goto error;
3538 }
3539
3540 /* generates ckch instance from the crtlist_entry */
3541 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3542 struct ckch_store *store;
3543 struct ckch_inst *ckch_inst = NULL;
3544
3545 store = entry->node.key;
3546 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3547 if (cfgerr & ERR_CODE) {
3548 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3549 goto error;
3550 }
William Lallemand49398312020-03-30 17:01:33 +02003551 LIST_ADDQ(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003552 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003553 }
William Lallemand2954c472020-03-06 21:54:13 +01003554
William Lallemand79d31ec2020-03-25 15:10:49 +01003555 /* add the bind_conf to the list */
3556 bind_conf_node->next = crtlist->bind_conf;
3557 crtlist->bind_conf = bind_conf_node;
3558
William Lallemand2954c472020-03-06 21:54:13 +01003559 return cfgerr;
3560error:
3561 {
William Lallemand49398312020-03-30 17:01:33 +02003562 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003563 struct ckch_inst *inst, *s_inst;
3564
William Lallemand49398312020-03-30 17:01:33 +02003565 lastentry = entry; /* which entry we tried to generate last */
3566 if (lastentry) {
3567 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3568 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3569 break;
3570
3571 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003572
William Lallemand49398312020-03-30 17:01:33 +02003573 /* this was not generated for this bind_conf, skip */
3574 if (inst->bind_conf != bind_conf)
3575 continue;
3576
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003577 /* free the sni_ctx and instance */
3578 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003579 }
William Lallemand2954c472020-03-06 21:54:13 +01003580 }
William Lallemand2954c472020-03-06 21:54:13 +01003581 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003582 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003583 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003584 return cfgerr;
3585}
3586
William Lallemand06b22a82020-03-16 14:45:55 +01003587/* Returns a set of ERR_* flags possibly with an error in <err>. */
3588int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3589{
3590 struct stat buf;
3591 char fp[MAXPATHLEN+1];
3592 int cfgerr = 0;
3593 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003594 struct ckch_inst *ckch_inst = NULL;
William Lallemand06b22a82020-03-16 14:45:55 +01003595
3596 if ((ckchs = ckchs_lookup(path))) {
3597 /* we found the ckchs in the tree, we can use it directly */
William Lallemand24bde432020-03-09 16:48:43 +01003598 return ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003599 }
3600 if (stat(path, &buf) == 0) {
3601 if (S_ISDIR(buf.st_mode) == 0) {
3602 ckchs = ckchs_load_cert_file(path, 0, err);
3603 if (!ckchs)
3604 return ERR_ALERT | ERR_FATAL;
3605
William Lallemand24bde432020-03-09 16:48:43 +01003606 return ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003607 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003608 return ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003609 }
3610 } else {
3611 /* stat failed, could be a bundle */
3612 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
3613 /* try to load a bundle if it is permitted */
3614 ckchs = ckchs_load_cert_file(path, 1, err);
3615 if (!ckchs)
3616 return ERR_ALERT | ERR_FATAL;
William Lallemand24bde432020-03-09 16:48:43 +01003617 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003618 } else {
3619 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3620 err && *err ? *err : "", fp, strerror(errno));
3621 cfgerr |= ERR_ALERT | ERR_FATAL;
3622 }
3623 }
3624
3625 return cfgerr;
3626}
3627
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003628/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003629static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003630ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003631{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003632 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003633 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003634 SSL_OP_ALL | /* all known workarounds for bugs */
3635 SSL_OP_NO_SSLv2 |
3636 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003637 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003638 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003639 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003640 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003641 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003642 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003643 SSL_MODE_ENABLE_PARTIAL_WRITE |
3644 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003645 SSL_MODE_RELEASE_BUFFERS |
3646 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003647 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003648 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003649 int flags = MC_SSL_O_ALL;
3650 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003651 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003652
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003653 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003654 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003655
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003656 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003657 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3658 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3659 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003660 else
3661 flags = conf_ssl_methods->flags;
3662
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003663 min = conf_ssl_methods->min;
3664 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003665
3666 /* default minimum is TLSV12, */
3667 if (!min) {
3668 if (!max || (max >= default_min_ver)) {
3669 min = default_min_ver;
3670 } else {
3671 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). "
3672 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3673 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3674 min = max;
3675 }
3676 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003677 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003678 if (min)
3679 flags |= (methodVersions[min].flag - 1);
3680 if (max)
3681 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003682 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003683 min = max = CONF_TLSV_NONE;
3684 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003685 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003686 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003687 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003688 if (min) {
3689 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003690 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3691 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3692 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3693 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003694 hole = 0;
3695 }
3696 max = i;
3697 }
3698 else {
3699 min = max = i;
3700 }
3701 }
3702 else {
3703 if (min)
3704 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003705 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003706 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003707 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3708 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003709 cfgerr += 1;
3710 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003711 /* save real min/max in bind_conf */
3712 conf_ssl_methods->min = min;
3713 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003714
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003715#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003716 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003717 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003718 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003719 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003720 else
3721 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
3722 if (flags & methodVersions[i].flag)
3723 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003724#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003725 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003726 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3727 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003728#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003729
3730 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3731 options |= SSL_OP_NO_TICKET;
3732 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3733 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003734
3735#ifdef SSL_OP_NO_RENEGOTIATION
3736 options |= SSL_OP_NO_RENEGOTIATION;
3737#endif
3738
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003739 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003740
Willy Tarreau5db847a2019-05-09 14:13:35 +02003741#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003742 if (global_ssl.async)
3743 mode |= SSL_MODE_ASYNC;
3744#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003745 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003746 if (global_ssl.life_time)
3747 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003748
3749#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3750#ifdef OPENSSL_IS_BORINGSSL
3751 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3752 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003753#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003754 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003755 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003756 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3757 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003758#else
3759 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003760#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003761 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003762#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003763 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003764}
3765
William Lallemand4f45bb92017-10-30 20:08:51 +01003766
3767static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3768{
3769 if (first == block) {
3770 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3771 if (first->len > 0)
3772 sh_ssl_sess_tree_delete(sh_ssl_sess);
3773 }
3774}
3775
3776/* return first block from sh_ssl_sess */
3777static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3778{
3779 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3780
3781}
3782
3783/* store a session into the cache
3784 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3785 * data: asn1 encoded session
3786 * data_len: asn1 encoded session length
3787 * Returns 1 id session was stored (else 0)
3788 */
3789static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3790{
3791 struct shared_block *first;
3792 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3793
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003794 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003795 if (!first) {
3796 /* Could not retrieve enough free blocks to store that session */
3797 return 0;
3798 }
3799
3800 /* STORE the key in the first elem */
3801 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3802 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3803 first->len = sizeof(struct sh_ssl_sess_hdr);
3804
3805 /* it returns the already existing node
3806 or current node if none, never returns null */
3807 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3808 if (oldsh_ssl_sess != sh_ssl_sess) {
3809 /* NOTE: Row couldn't be in use because we lock read & write function */
3810 /* release the reserved row */
3811 shctx_row_dec_hot(ssl_shctx, first);
3812 /* replace the previous session already in the tree */
3813 sh_ssl_sess = oldsh_ssl_sess;
3814 /* ignore the previous session data, only use the header */
3815 first = sh_ssl_sess_first_block(sh_ssl_sess);
3816 shctx_row_inc_hot(ssl_shctx, first);
3817 first->len = sizeof(struct sh_ssl_sess_hdr);
3818 }
3819
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003820 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01003821 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003822 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01003823 }
3824
3825 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003826
3827 return 1;
3828}
William Lallemanded0b5ad2017-10-30 19:36:36 +01003829
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003830/* SSL callback used when a new session is created while connecting to a server */
3831static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
3832{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02003833 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003834 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003835
Willy Tarreau07d94e42018-09-20 10:57:52 +02003836 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003837
Olivier Houcharde6060c52017-11-16 17:42:52 +01003838 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
3839 int len;
3840 unsigned char *ptr;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003841
Olivier Houcharde6060c52017-11-16 17:42:52 +01003842 len = i2d_SSL_SESSION(sess, NULL);
3843 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
3844 ptr = s->ssl_ctx.reused_sess[tid].ptr;
3845 } else {
3846 free(s->ssl_ctx.reused_sess[tid].ptr);
3847 ptr = s->ssl_ctx.reused_sess[tid].ptr = malloc(len);
3848 s->ssl_ctx.reused_sess[tid].allocated_size = len;
3849 }
3850 if (s->ssl_ctx.reused_sess[tid].ptr) {
3851 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
3852 &ptr);
3853 }
3854 } else {
3855 free(s->ssl_ctx.reused_sess[tid].ptr);
3856 s->ssl_ctx.reused_sess[tid].ptr = NULL;
3857 }
3858
3859 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003860}
3861
Olivier Houcharde6060c52017-11-16 17:42:52 +01003862
William Lallemanded0b5ad2017-10-30 19:36:36 +01003863/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01003864int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003865{
3866 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
3867 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
3868 unsigned char *p;
3869 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02003870 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003871 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003872
3873 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003874 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02003875 * note: SSL_SESSION_set1_id is using
3876 * a memcpy so we need to use a different pointer
3877 * than sid_data or sid_ctx_data to avoid valgrind
3878 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01003879 */
3880
3881 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02003882
3883 /* copy value in an other buffer */
3884 memcpy(encid, sid_data, sid_length);
3885
3886 /* pad with 0 */
3887 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
3888 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
3889
3890 /* force length to zero to avoid ASN1 encoding */
3891 SSL_SESSION_set1_id(sess, encid, 0);
3892
3893 /* force length to zero to avoid ASN1 encoding */
3894 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003895
3896 /* check if buffer is large enough for the ASN1 encoded session */
3897 data_len = i2d_SSL_SESSION(sess, NULL);
3898 if (data_len > SHSESS_MAX_DATA_LEN)
3899 goto err;
3900
3901 p = encsess;
3902
3903 /* process ASN1 session encoding before the lock */
3904 i2d_SSL_SESSION(sess, &p);
3905
William Lallemanded0b5ad2017-10-30 19:36:36 +01003906
William Lallemanda3c77cf2017-10-30 23:44:40 +01003907 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003908 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003909 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01003910 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003911err:
3912 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02003913 SSL_SESSION_set1_id(sess, encid, sid_length);
3914 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003915
3916 return 0; /* do not increment session reference count */
3917}
3918
3919/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003920SSL_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 +01003921{
William Lallemand4f45bb92017-10-30 20:08:51 +01003922 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003923 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
3924 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01003925 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01003926 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003927
3928 global.shctx_lookups++;
3929
3930 /* allow the session to be freed automatically by openssl */
3931 *do_copy = 0;
3932
3933 /* tree key is zeros padded sessionid */
3934 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3935 memcpy(tmpkey, key, key_len);
3936 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
3937 key = tmpkey;
3938 }
3939
3940 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003941 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003942
3943 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003944 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
3945 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003946 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003947 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003948 global.shctx_misses++;
3949 return NULL;
3950 }
3951
William Lallemand4f45bb92017-10-30 20:08:51 +01003952 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
3953 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003954
William Lallemand4f45bb92017-10-30 20:08:51 +01003955 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 +01003956
William Lallemanda3c77cf2017-10-30 23:44:40 +01003957 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003958
3959 /* decode ASN1 session */
3960 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01003961 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003962 /* Reset session id and session id contenxt */
3963 if (sess) {
3964 SSL_SESSION_set1_id(sess, key, key_len);
3965 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
3966 }
3967
3968 return sess;
3969}
3970
William Lallemand4f45bb92017-10-30 20:08:51 +01003971
William Lallemanded0b5ad2017-10-30 19:36:36 +01003972/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003973void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003974{
William Lallemand4f45bb92017-10-30 20:08:51 +01003975 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003976 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
3977 unsigned int sid_length;
3978 const unsigned char *sid_data;
3979 (void)ctx;
3980
3981 sid_data = SSL_SESSION_get_id(sess, &sid_length);
3982 /* tree key is zeros padded sessionid */
3983 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3984 memcpy(tmpkey, sid_data, sid_length);
3985 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
3986 sid_data = tmpkey;
3987 }
3988
William Lallemanda3c77cf2017-10-30 23:44:40 +01003989 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003990
3991 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003992 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
3993 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003994 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003995 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003996 }
3997
3998 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003999 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004000}
4001
4002/* Set session cache mode to server and disable openssl internal cache.
4003 * Set shared cache callbacks on an ssl context.
4004 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004005void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004006{
4007 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4008
4009 if (!ssl_shctx) {
4010 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4011 return;
4012 }
4013
4014 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4015 SSL_SESS_CACHE_NO_INTERNAL |
4016 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4017
4018 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004019 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4020 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4021 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004022}
4023
William Lallemand8b453912019-11-21 15:48:10 +01004024/*
4025 * This function applies the SSL configuration on a SSL_CTX
4026 * It returns an error code and fills the <err> buffer
4027 */
4028int 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 +01004029{
4030 struct proxy *curproxy = bind_conf->frontend;
4031 int cfgerr = 0;
4032 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004033 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004034 const char *conf_ciphers;
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004035#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004036 const char *conf_ciphersuites;
4037#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004038 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004039
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004040 if (ssl_conf) {
4041 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4042 int i, min, max;
4043 int flags = MC_SSL_O_ALL;
4044
4045 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004046 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4047 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004048 if (min)
4049 flags |= (methodVersions[min].flag - 1);
4050 if (max)
4051 flags |= ~((methodVersions[max].flag << 1) - 1);
4052 min = max = CONF_TLSV_NONE;
4053 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4054 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4055 if (min)
4056 max = i;
4057 else
4058 min = max = i;
4059 }
4060 /* save real min/max */
4061 conf_ssl_methods->min = min;
4062 conf_ssl_methods->max = max;
4063 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004064 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4065 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004066 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004067 }
4068 }
4069
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004070 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004071 case SSL_SOCK_VERIFY_NONE:
4072 verify = SSL_VERIFY_NONE;
4073 break;
4074 case SSL_SOCK_VERIFY_OPTIONAL:
4075 verify = SSL_VERIFY_PEER;
4076 break;
4077 case SSL_SOCK_VERIFY_REQUIRED:
4078 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4079 break;
4080 }
4081 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4082 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004083 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 +01004084 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 +01004085 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 +01004086 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004087 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004088 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004089 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004090 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004091 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004092 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004093 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4094 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4095 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4096 cfgerr |= ERR_ALERT | ERR_FATAL;
4097 }
4098 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004099 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004100 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 +02004101 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004102 }
Emeric Brun850efd52014-01-29 12:24:34 +01004103 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004104 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4105 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004106 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004107 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004108#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004109 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004110 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4111
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004112 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004113 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4114 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004115 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004116 }
Emeric Brun561e5742012-10-02 15:20:55 +02004117 else {
4118 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4119 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004120 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004121#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004122 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004123 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004124#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004125 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004126 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004127 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4128 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004129 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004130 }
4131 }
4132#endif
4133
William Lallemand4f45bb92017-10-30 20:08:51 +01004134 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004135 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4136 if (conf_ciphers &&
4137 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004138 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4139 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004140 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004141 }
4142
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004143#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004144 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4145 if (conf_ciphersuites &&
4146 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004147 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4148 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004149 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004150 }
4151#endif
4152
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004153#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004154 /* If tune.ssl.default-dh-param has not been set,
4155 neither has ssl-default-dh-file and no static DH
4156 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004157 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004158 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004159 (ssl_dh_ptr_index == -1 ||
4160 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004161 /* default to dh-param 2048 */
4162 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004163 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004164
Willy Tarreauef934602016-12-22 23:12:01 +01004165 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004166 if (local_dh_1024 == NULL) {
4167 local_dh_1024 = ssl_get_dh_1024();
4168 }
Willy Tarreauef934602016-12-22 23:12:01 +01004169 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004170 if (local_dh_2048 == NULL) {
4171 local_dh_2048 = ssl_get_dh_2048();
4172 }
Willy Tarreauef934602016-12-22 23:12:01 +01004173 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004174 if (local_dh_4096 == NULL) {
4175 local_dh_4096 = ssl_get_dh_4096();
4176 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004177 }
4178 }
4179 }
4180#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004181
Emeric Brunfc0421f2012-09-07 17:30:07 +02004182 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004183#if HA_OPENSSL_VERSION_NUMBER >= 0x00907000L
Emeric Brun29f037d2014-04-25 19:05:36 +02004184 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004185#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004186
Bernard Spil13c53f82018-02-15 13:34:58 +01004187#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004188 ssl_conf_cur = NULL;
4189 if (ssl_conf && ssl_conf->npn_str)
4190 ssl_conf_cur = ssl_conf;
4191 else if (bind_conf->ssl_conf.npn_str)
4192 ssl_conf_cur = &bind_conf->ssl_conf;
4193 if (ssl_conf_cur)
4194 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004195#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004196#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004197 ssl_conf_cur = NULL;
4198 if (ssl_conf && ssl_conf->alpn_str)
4199 ssl_conf_cur = ssl_conf;
4200 else if (bind_conf->ssl_conf.alpn_str)
4201 ssl_conf_cur = &bind_conf->ssl_conf;
4202 if (ssl_conf_cur)
4203 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004204#endif
Lukas Tribusd14b49c2019-11-24 18:20:40 +01004205#if ((HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL) || defined(LIBRESSL_VERSION_NUMBER))
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004206 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4207 if (conf_curves) {
4208 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004209 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4210 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004211 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004212 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004213 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004214 }
4215#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004216#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004217 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004218 int i;
4219 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004220#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004221 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004222 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4223 NULL);
4224
4225 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004226 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004227 return cfgerr;
4228 }
4229#else
4230 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4231 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4232 ECDHE_DEFAULT_CURVE);
4233#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004234
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004235 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004236 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004237 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4238 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004239 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004240 }
4241 else {
4242 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4243 EC_KEY_free(ecdh);
4244 }
4245 }
4246#endif
4247
Emeric Brunfc0421f2012-09-07 17:30:07 +02004248 return cfgerr;
4249}
4250
Evan Broderbe554312013-06-27 00:05:25 -07004251static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4252{
4253 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4254 size_t prefixlen, suffixlen;
4255
4256 /* Trivial case */
4257 if (strcmp(pattern, hostname) == 0)
4258 return 1;
4259
Evan Broderbe554312013-06-27 00:05:25 -07004260 /* The rest of this logic is based on RFC 6125, section 6.4.3
4261 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4262
Emeric Bruna848dae2013-10-08 11:27:28 +02004263 pattern_wildcard = NULL;
4264 pattern_left_label_end = pattern;
4265 while (*pattern_left_label_end != '.') {
4266 switch (*pattern_left_label_end) {
4267 case 0:
4268 /* End of label not found */
4269 return 0;
4270 case '*':
4271 /* If there is more than one wildcards */
4272 if (pattern_wildcard)
4273 return 0;
4274 pattern_wildcard = pattern_left_label_end;
4275 break;
4276 }
4277 pattern_left_label_end++;
4278 }
4279
4280 /* If it's not trivial and there is no wildcard, it can't
4281 * match */
4282 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004283 return 0;
4284
4285 /* Make sure all labels match except the leftmost */
4286 hostname_left_label_end = strchr(hostname, '.');
4287 if (!hostname_left_label_end
4288 || strcmp(pattern_left_label_end, hostname_left_label_end) != 0)
4289 return 0;
4290
4291 /* Make sure the leftmost label of the hostname is long enough
4292 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004293 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004294 return 0;
4295
4296 /* Finally compare the string on either side of the
4297 * wildcard */
4298 prefixlen = pattern_wildcard - pattern;
4299 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
Emeric Bruna848dae2013-10-08 11:27:28 +02004300 if ((prefixlen && (memcmp(pattern, hostname, prefixlen) != 0))
4301 || (suffixlen && (memcmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004302 return 0;
4303
4304 return 1;
4305}
4306
4307static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4308{
4309 SSL *ssl;
4310 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004311 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004312 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004313 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004314
4315 int depth;
4316 X509 *cert;
4317 STACK_OF(GENERAL_NAME) *alt_names;
4318 int i;
4319 X509_NAME *cert_subject;
4320 char *str;
4321
4322 if (ok == 0)
4323 return ok;
4324
4325 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004326 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004327 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004328
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004329 /* We're checking if the provided hostnames match the desired one. The
4330 * desired hostname comes from the SNI we presented if any, or if not
4331 * provided then it may have been explicitly stated using a "verifyhost"
4332 * directive. If neither is set, we don't care about the name so the
4333 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004334 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004335 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004336 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004337 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004338 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004339 if (!servername)
4340 return ok;
4341 }
Evan Broderbe554312013-06-27 00:05:25 -07004342
4343 /* We only need to verify the CN on the actual server cert,
4344 * not the indirect CAs */
4345 depth = X509_STORE_CTX_get_error_depth(ctx);
4346 if (depth != 0)
4347 return ok;
4348
4349 /* At this point, the cert is *not* OK unless we can find a
4350 * hostname match */
4351 ok = 0;
4352
4353 cert = X509_STORE_CTX_get_current_cert(ctx);
4354 /* It seems like this might happen if verify peer isn't set */
4355 if (!cert)
4356 return ok;
4357
4358 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4359 if (alt_names) {
4360 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4361 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4362 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004363#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004364 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4365#else
Evan Broderbe554312013-06-27 00:05:25 -07004366 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004367#endif
Evan Broderbe554312013-06-27 00:05:25 -07004368 ok = ssl_sock_srv_hostcheck(str, servername);
4369 OPENSSL_free(str);
4370 }
4371 }
4372 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004373 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004374 }
4375
4376 cert_subject = X509_get_subject_name(cert);
4377 i = -1;
4378 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4379 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004380 ASN1_STRING *value;
4381 value = X509_NAME_ENTRY_get_data(entry);
4382 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004383 ok = ssl_sock_srv_hostcheck(str, servername);
4384 OPENSSL_free(str);
4385 }
4386 }
4387
Willy Tarreau71d058c2017-07-26 20:09:56 +02004388 /* report the mismatch and indicate if SNI was used or not */
4389 if (!ok && !conn->err_code)
4390 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004391 return ok;
4392}
4393
Emeric Brun94324a42012-10-11 14:00:19 +02004394/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004395int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004396{
Willy Tarreau03209342016-12-22 17:08:28 +01004397 struct proxy *curproxy = srv->proxy;
Emeric Brun94324a42012-10-11 14:00:19 +02004398 int cfgerr = 0;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004399 long options =
Emeric Brun94324a42012-10-11 14:00:19 +02004400 SSL_OP_ALL | /* all known workarounds for bugs */
4401 SSL_OP_NO_SSLv2 |
4402 SSL_OP_NO_COMPRESSION;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004403 long mode =
Emeric Brun94324a42012-10-11 14:00:19 +02004404 SSL_MODE_ENABLE_PARTIAL_WRITE |
4405 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004406 SSL_MODE_RELEASE_BUFFERS |
4407 SSL_MODE_SMALL_BUFFERS;
Emeric Brun850efd52014-01-29 12:24:34 +01004408 int verify = SSL_VERIFY_NONE;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004409 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004410 struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004411 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004412 int flags = MC_SSL_O_ALL;
Emeric Brun94324a42012-10-11 14:00:19 +02004413
Thierry Fournier383085f2013-01-24 14:15:43 +01004414 /* Make sure openssl opens /dev/urandom before the chroot */
4415 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004416 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004417 cfgerr++;
4418 }
4419
Willy Tarreaufce03112015-01-15 21:32:40 +01004420 /* Automatic memory computations need to know we use SSL there */
4421 global.ssl_used_backend = 1;
4422
4423 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004424 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004425 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004426 ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4427 curproxy->id, srv->id,
4428 srv->conf.file, srv->conf.line);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004429 cfgerr++;
4430 return cfgerr;
4431 }
4432 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004433 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004434 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004435
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004436 ctx = SSL_CTX_new(SSLv23_client_method());
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004437 if (!ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004438 ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4439 proxy_type_str(curproxy), curproxy->id,
4440 srv->id);
Emeric Brun94324a42012-10-11 14:00:19 +02004441 cfgerr++;
4442 return cfgerr;
4443 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004444
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004445 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004446 ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4447 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4448 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004449 else
4450 flags = conf_ssl_methods->flags;
4451
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004452 /* Real min and max should be determinate with configuration and openssl's capabilities */
4453 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004454 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004455 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004456 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004457
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004458 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004459 min = max = CONF_TLSV_NONE;
4460 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004461 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004462 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004463 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004464 if (min) {
4465 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004466 ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4467 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4468 proxy_type_str(curproxy), curproxy->id, srv->id,
4469 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004470 hole = 0;
4471 }
4472 max = i;
4473 }
4474 else {
4475 min = max = i;
4476 }
4477 }
4478 else {
4479 if (min)
4480 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004481 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004482 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004483 ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4484 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004485 cfgerr += 1;
4486 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004487
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004488#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004489 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004490 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004491 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004492 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004493 else
4494 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4495 if (flags & methodVersions[i].flag)
4496 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004497#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004498 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004499 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4500 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004501#endif
4502
4503 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4504 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004505 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004506
Willy Tarreau5db847a2019-05-09 14:13:35 +02004507#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004508 if (global_ssl.async)
4509 mode |= SSL_MODE_ASYNC;
4510#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004511 SSL_CTX_set_mode(ctx, mode);
4512 srv->ssl_ctx.ctx = ctx;
4513
Emeric Bruna7aa3092012-10-26 12:58:00 +02004514 if (srv->ssl_ctx.client_crt) {
4515 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 +01004516 ha_alert("config : %s '%s', server '%s': unable to load SSL private key from PEM file '%s'.\n",
4517 proxy_type_str(curproxy), curproxy->id,
4518 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004519 cfgerr++;
4520 }
4521 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 +01004522 ha_alert("config : %s '%s', server '%s': unable to load ssl certificate from PEM file '%s'.\n",
4523 proxy_type_str(curproxy), curproxy->id,
4524 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004525 cfgerr++;
4526 }
4527 else if (SSL_CTX_check_private_key(srv->ssl_ctx.ctx) <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004528 ha_alert("config : %s '%s', server '%s': inconsistencies between private key and certificate loaded from PEM file '%s'.\n",
4529 proxy_type_str(curproxy), curproxy->id,
4530 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004531 cfgerr++;
4532 }
4533 }
Emeric Brun94324a42012-10-11 14:00:19 +02004534
Emeric Brun850efd52014-01-29 12:24:34 +01004535 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4536 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004537 switch (srv->ssl_ctx.verify) {
4538 case SSL_SOCK_VERIFY_NONE:
4539 verify = SSL_VERIFY_NONE;
4540 break;
4541 case SSL_SOCK_VERIFY_REQUIRED:
4542 verify = SSL_VERIFY_PEER;
4543 break;
4544 }
Evan Broderbe554312013-06-27 00:05:25 -07004545 SSL_CTX_set_verify(srv->ssl_ctx.ctx,
Emeric Brun850efd52014-01-29 12:24:34 +01004546 verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004547 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004548 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004549 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004550 /* set CAfile to verify */
4551 if (!ssl_set_verify_locations_file(srv->ssl_ctx.ctx, srv->ssl_ctx.ca_file)) {
4552 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to set CA file '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004553 curproxy->id, srv->id,
4554 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004555 cfgerr++;
4556 }
4557 }
Emeric Brun850efd52014-01-29 12:24:34 +01004558 else {
4559 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Christopher Faulet767a84b2017-11-24 16:50:31 +01004560 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",
4561 curproxy->id, srv->id,
4562 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004563 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01004564 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4565 curproxy->id, srv->id,
4566 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004567 cfgerr++;
4568 }
Emeric Brunef42d922012-10-11 16:11:36 +02004569#ifdef X509_V_FLAG_CRL_CHECK
4570 if (srv->ssl_ctx.crl_file) {
4571 X509_STORE *store = SSL_CTX_get_cert_store(srv->ssl_ctx.ctx);
4572
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004573 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004574 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4575 curproxy->id, srv->id,
4576 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004577 cfgerr++;
4578 }
4579 else {
4580 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4581 }
4582 }
4583#endif
4584 }
4585
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004586 SSL_CTX_set_session_cache_mode(srv->ssl_ctx.ctx, SSL_SESS_CACHE_CLIENT |
4587 SSL_SESS_CACHE_NO_INTERNAL_STORE);
4588 SSL_CTX_sess_set_new_cb(srv->ssl_ctx.ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004589 if (srv->ssl_ctx.ciphers &&
4590 !SSL_CTX_set_cipher_list(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphers)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004591 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4592 curproxy->id, srv->id,
4593 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004594 cfgerr++;
4595 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004596
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004597#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004598 if (srv->ssl_ctx.ciphersuites &&
Pierre Cheynierbc34cd12019-03-21 16:15:47 +00004599 !SSL_CTX_set_ciphersuites(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphersuites)) {
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004600 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4601 curproxy->id, srv->id,
4602 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4603 cfgerr++;
4604 }
4605#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004606#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4607 if (srv->ssl_ctx.npn_str)
4608 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, srv);
4609#endif
4610#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4611 if (srv->ssl_ctx.alpn_str)
4612 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4613#endif
4614
Emeric Brun94324a42012-10-11 14:00:19 +02004615
4616 return cfgerr;
4617}
4618
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004619/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004620 * be NULL, in which case nothing is done. Returns the number of errors
4621 * encountered.
4622 */
Willy Tarreau03209342016-12-22 17:08:28 +01004623int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004624{
4625 struct ebmb_node *node;
4626 struct sni_ctx *sni;
4627 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004628 int errcode = 0;
4629 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004630
Willy Tarreaufce03112015-01-15 21:32:40 +01004631 /* Automatic memory computations need to know we use SSL there */
4632 global.ssl_used_frontend = 1;
4633
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004634 /* Make sure openssl opens /dev/urandom before the chroot */
4635 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004636 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004637 err++;
4638 }
4639 /* Create initial_ctx used to start the ssl connection before do switchctx */
4640 if (!bind_conf->initial_ctx) {
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004641 err += ssl_sock_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004642 /* It should not be necessary to call this function, but it's
4643 necessary first to check and move all initialisation related
4644 to initial_ctx in ssl_sock_initial_ctx. */
William Lallemand8b453912019-11-21 15:48:10 +01004645 errcode |= ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004646 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004647 if (bind_conf->default_ctx)
William Lallemand8b453912019-11-21 15:48:10 +01004648 errcode |= ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, &errmsg);
Emeric Brun0bed9942014-10-30 19:25:24 +01004649
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004650 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004651 while (node) {
4652 sni = ebmb_entry(node, struct sni_ctx, name);
Emeric Brun0bed9942014-10-30 19:25:24 +01004653 if (!sni->order && sni->ctx != bind_conf->default_ctx)
4654 /* only initialize the CTX on its first occurrence and
4655 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004656 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004657 node = ebmb_next(node);
4658 }
4659
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004660 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004661 while (node) {
4662 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004663 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004664 /* only initialize the CTX on its first occurrence and
4665 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004666 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
4667 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004668 node = ebmb_next(node);
4669 }
William Lallemand8b453912019-11-21 15:48:10 +01004670
4671 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004672 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004673 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004674 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004675 err++;
4676 }
4677
4678 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004679 return err;
4680}
4681
Willy Tarreau55d37912016-12-21 23:38:39 +01004682/* Prepares all the contexts for a bind_conf and allocates the shared SSL
4683 * context if needed. Returns < 0 on error, 0 on success. The warnings and
4684 * alerts are directly emitted since the rest of the stack does it below.
4685 */
4686int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
4687{
4688 struct proxy *px = bind_conf->frontend;
4689 int alloc_ctx;
4690 int err;
4691
4692 if (!bind_conf->is_ssl) {
4693 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004694 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
4695 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01004696 }
4697 return 0;
4698 }
4699 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004700 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004701 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
4702 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004703 }
4704 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004705 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
4706 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004707 return -1;
4708 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004709 }
William Lallemandc61c0b32017-12-04 18:46:39 +01004710 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004711 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02004712 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01004713 sizeof(*sh_ssl_sess_tree),
4714 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02004715 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004716 if (alloc_ctx == SHCTX_E_INIT_LOCK)
4717 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");
4718 else
4719 ha_alert("Unable to allocate SSL session cache.\n");
4720 return -1;
4721 }
4722 /* free block callback */
4723 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
4724 /* init the root tree within the extra space */
4725 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
4726 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01004727 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004728 err = 0;
4729 /* initialize all certificate contexts */
4730 err += ssl_sock_prepare_all_ctx(bind_conf);
4731
4732 /* initialize CA variables if the certificates generation is enabled */
4733 err += ssl_sock_load_ca(bind_conf);
4734
4735 return -err;
4736}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004737
4738/* release ssl context allocated for servers. */
4739void ssl_sock_free_srv_ctx(struct server *srv)
4740{
Olivier Houchardc7566002018-11-20 23:33:50 +01004741#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4742 if (srv->ssl_ctx.alpn_str)
4743 free(srv->ssl_ctx.alpn_str);
4744#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01004745#ifdef OPENSSL_NPN_NEGOTIATED
Olivier Houchardc7566002018-11-20 23:33:50 +01004746 if (srv->ssl_ctx.npn_str)
4747 free(srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01004748#endif
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004749 if (srv->ssl_ctx.ctx)
4750 SSL_CTX_free(srv->ssl_ctx.ctx);
4751}
4752
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004753/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004754 * be NULL, in which case nothing is done. The default_ctx is nullified too.
4755 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004756void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004757{
4758 struct ebmb_node *node, *back;
4759 struct sni_ctx *sni;
4760
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004761 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004762 while (node) {
4763 sni = ebmb_entry(node, struct sni_ctx, name);
4764 back = ebmb_next(node);
4765 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004766 SSL_CTX_free(sni->ctx);
4767 if (!sni->order) { /* only free the CTX conf on its first occurrence */
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004768 ssl_sock_free_ssl_conf(sni->conf);
4769 free(sni->conf);
4770 sni->conf = NULL;
4771 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004772 free(sni);
4773 node = back;
4774 }
4775
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004776 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004777 while (node) {
4778 sni = ebmb_entry(node, struct sni_ctx, name);
4779 back = ebmb_next(node);
4780 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004781 SSL_CTX_free(sni->ctx);
4782 if (!sni->order) { /* only free the SSL conf its first occurrence */
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004783 ssl_sock_free_ssl_conf(sni->conf);
4784 free(sni->conf);
4785 sni->conf = NULL;
4786 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004787 free(sni);
4788 node = back;
4789 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004790 SSL_CTX_free(bind_conf->initial_ctx);
4791 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02004792 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004793 bind_conf->default_ctx = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004794 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02004795}
4796
Willy Tarreau795cdab2016-12-22 17:30:54 +01004797/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
4798void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
4799{
4800 ssl_sock_free_ca(bind_conf);
4801 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004802 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01004803 free(bind_conf->ca_sign_file);
4804 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02004805 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01004806 free(bind_conf->keys_ref->filename);
4807 free(bind_conf->keys_ref->tlskeys);
4808 LIST_DEL(&bind_conf->keys_ref->list);
4809 free(bind_conf->keys_ref);
4810 }
4811 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004812 bind_conf->ca_sign_pass = NULL;
4813 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004814}
4815
Christopher Faulet31af49d2015-06-09 17:29:50 +02004816/* Load CA cert file and private key used to generate certificates */
4817int
Willy Tarreau03209342016-12-22 17:08:28 +01004818ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02004819{
Willy Tarreau03209342016-12-22 17:08:28 +01004820 struct proxy *px = bind_conf->frontend;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004821 FILE *fp;
4822 X509 *cacert = NULL;
4823 EVP_PKEY *capkey = NULL;
4824 int err = 0;
4825
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02004826 if (!bind_conf->generate_certs)
Christopher Faulet31af49d2015-06-09 17:29:50 +02004827 return err;
4828
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01004829#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02004830 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01004831 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004832 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02004833 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004834 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02004835#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02004836
Christopher Faulet31af49d2015-06-09 17:29:50 +02004837 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004838 ha_alert("Proxy '%s': cannot enable certificate generation, "
4839 "no CA certificate File configured at [%s:%d].\n",
4840 px->id, bind_conf->file, bind_conf->line);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004841 goto load_error;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004842 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004843
4844 /* read in the CA certificate */
4845 if (!(fp = fopen(bind_conf->ca_sign_file, "r"))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004846 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
4847 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004848 goto load_error;
4849 }
4850 if (!(cacert = PEM_read_X509(fp, NULL, NULL, NULL))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004851 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
4852 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004853 goto read_error;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004854 }
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004855 rewind(fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004856 if (!(capkey = PEM_read_PrivateKey(fp, NULL, NULL, bind_conf->ca_sign_pass))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004857 ha_alert("Proxy '%s': Failed to read CA private key file '%s' at [%s:%d].\n",
4858 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004859 goto read_error;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004860 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004861
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004862 fclose (fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004863 bind_conf->ca_sign_cert = cacert;
4864 bind_conf->ca_sign_pkey = capkey;
4865 return err;
4866
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004867 read_error:
4868 fclose (fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004869 if (capkey) EVP_PKEY_free(capkey);
4870 if (cacert) X509_free(cacert);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004871 load_error:
4872 bind_conf->generate_certs = 0;
4873 err++;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004874 return err;
4875}
4876
4877/* Release CA cert and private key used to generate certificated */
4878void
4879ssl_sock_free_ca(struct bind_conf *bind_conf)
4880{
Christopher Faulet31af49d2015-06-09 17:29:50 +02004881 if (bind_conf->ca_sign_pkey)
4882 EVP_PKEY_free(bind_conf->ca_sign_pkey);
4883 if (bind_conf->ca_sign_cert)
4884 X509_free(bind_conf->ca_sign_cert);
Willy Tarreau94ff03a2016-12-22 17:57:46 +01004885 bind_conf->ca_sign_pkey = NULL;
4886 bind_conf->ca_sign_cert = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004887}
4888
Emeric Brun46591952012-05-18 15:47:34 +02004889/*
4890 * This function is called if SSL * context is not yet allocated. The function
4891 * is designed to be called before any other data-layer operation and sets the
4892 * handshake flag on the connection. It is safe to call it multiple times.
4893 * It returns 0 on success and -1 in error case.
4894 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004895static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004896{
Olivier Houchard66ab4982019-02-26 18:37:15 +01004897 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02004898 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004899 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004900 return 0;
4901
Willy Tarreau3c728722014-01-23 13:50:42 +01004902 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02004903 return 0;
4904
Olivier Houchard66ab4982019-02-26 18:37:15 +01004905 ctx = pool_alloc(ssl_sock_ctx_pool);
4906 if (!ctx) {
4907 conn->err_code = CO_ER_SSL_NO_MEM;
4908 return -1;
4909 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004910 ctx->wait_event.tasklet = tasklet_new();
4911 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004912 conn->err_code = CO_ER_SSL_NO_MEM;
4913 pool_free(ssl_sock_ctx_pool, ctx);
4914 return -1;
4915 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004916 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
4917 ctx->wait_event.tasklet->context = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004918 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01004919 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01004920 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004921 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01004922 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02004923 ctx->xprt_st = 0;
4924 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004925
4926 /* Only work with sockets for now, this should be adapted when we'll
4927 * add QUIC support.
4928 */
4929 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02004930 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004931 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
4932 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02004933 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01004934
Willy Tarreau20879a02012-12-03 16:32:10 +01004935 if (global.maxsslconn && sslconns >= global.maxsslconn) {
4936 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004937 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004938 }
Willy Tarreau403edff2012-09-06 11:58:37 +02004939
Emeric Brun46591952012-05-18 15:47:34 +02004940 /* If it is in client mode initiate SSL session
4941 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01004942 if (objt_server(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004943 int may_retry = 1;
4944
4945 retry_connect:
Emeric Brun46591952012-05-18 15:47:34 +02004946 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004947 ctx->ssl = SSL_new(__objt_server(conn->target)->ssl_ctx.ctx);
4948 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004949 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004950 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004951 goto retry_connect;
4952 }
Willy Tarreau20879a02012-12-03 16:32:10 +01004953 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004954 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004955 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004956 ctx->bio = BIO_new(ha_meth);
4957 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01004958 SSL_free(ctx->ssl);
4959 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004960 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004961 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004962 goto retry_connect;
4963 }
Emeric Brun55476152014-11-12 17:35:37 +01004964 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004965 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004966 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004967 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02004968 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02004969
Evan Broderbe554312013-06-27 00:05:25 -07004970 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004971 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
4972 SSL_free(ctx->ssl);
4973 ctx->ssl = NULL;
Emeric Brun55476152014-11-12 17:35:37 +01004974 conn->xprt_ctx = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004975 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004976 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004977 goto retry_connect;
4978 }
Emeric Brun55476152014-11-12 17:35:37 +01004979 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004980 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004981 }
4982
Olivier Houchard66ab4982019-02-26 18:37:15 +01004983 SSL_set_connect_state(ctx->ssl);
Willy Tarreau07d94e42018-09-20 10:57:52 +02004984 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
4985 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
4986 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 +01004987 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004988 SSL_SESSION_free(sess);
Willy Tarreau07d94e42018-09-20 10:57:52 +02004989 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
4990 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004991 } else if (sess) {
4992 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01004993 }
4994 }
Evan Broderbe554312013-06-27 00:05:25 -07004995
Emeric Brun46591952012-05-18 15:47:34 +02004996 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02004997 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02004998
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01004999 _HA_ATOMIC_ADD(&sslconns, 1);
5000 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005001 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005002 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005003 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005004 return 0;
5005 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005006 else if (objt_listener(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005007 int may_retry = 1;
5008
5009 retry_accept:
Emeric Brun46591952012-05-18 15:47:34 +02005010 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005011 ctx->ssl = SSL_new(__objt_listener(conn->target)->bind_conf->initial_ctx);
5012 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005013 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005014 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005015 goto retry_accept;
5016 }
Willy Tarreau20879a02012-12-03 16:32:10 +01005017 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005018 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005019 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005020 ctx->bio = BIO_new(ha_meth);
5021 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01005022 SSL_free(ctx->ssl);
5023 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005024 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005025 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005026 goto retry_accept;
5027 }
Emeric Brun55476152014-11-12 17:35:37 +01005028 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005029 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005030 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005031 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02005032 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02005033
Emeric Brune1f38db2012-09-03 20:36:47 +02005034 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005035 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
5036 SSL_free(ctx->ssl);
5037 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005038 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005039 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005040 goto retry_accept;
5041 }
Emeric Brun55476152014-11-12 17:35:37 +01005042 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005043 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005044 }
5045
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005046#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5047 if (__objt_listener(conn->target)->bind_conf->ssl_conf.early_data) {
5048 b_alloc(&ctx->early_buf);
5049 SSL_set_max_early_data(ctx->ssl,
5050 /* Only allow early data if we managed to allocate
5051 * a buffer.
5052 */
5053 (!b_is_null(&ctx->early_buf)) ?
5054 global.tune.bufsize - global.tune.maxrewrite : 0);
5055 }
5056#endif
5057
Olivier Houchard66ab4982019-02-26 18:37:15 +01005058 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005059
Emeric Brun46591952012-05-18 15:47:34 +02005060 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005061 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005062#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchardc2aae742017-09-22 18:26:28 +02005063 conn->flags |= CO_FL_EARLY_SSL_HS;
5064#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005065
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005066 _HA_ATOMIC_ADD(&sslconns, 1);
5067 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005068 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005069 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005070 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005071 return 0;
5072 }
5073 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005074 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005075err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005076 if (ctx && ctx->wait_event.tasklet)
5077 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005078 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005079 return -1;
5080}
5081
5082
5083/* This is the callback which is used when an SSL handshake is pending. It
5084 * updates the FD status if it wants some polling before being called again.
5085 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5086 * otherwise it returns non-zero and removes itself from the connection's
5087 * flags (the bit is provided in <flag> by the caller).
5088 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005089static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005090{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005091 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005092 int ret;
5093
Willy Tarreau3c728722014-01-23 13:50:42 +01005094 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005095 return 0;
5096
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005097 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005098 goto out_error;
5099
Willy Tarreau5db847a2019-05-09 14:13:35 +02005100#if HA_OPENSSL_VERSION_NUMBER >= 0x10101000L
Olivier Houchardc2aae742017-09-22 18:26:28 +02005101 /*
5102 * Check if we have early data. If we do, we have to read them
5103 * before SSL_do_handshake() is called, And there's no way to
5104 * detect early data, except to try to read them
5105 */
5106 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005107 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005108
Olivier Houchard54907bb2019-12-19 15:02:39 +01005109 while (1) {
5110 ret = SSL_read_early_data(ctx->ssl,
5111 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5112 &read_data);
5113 if (ret == SSL_READ_EARLY_DATA_ERROR)
5114 goto check_error;
5115 if (read_data > 0) {
5116 conn->flags |= CO_FL_EARLY_DATA;
5117 b_add(&ctx->early_buf, read_data);
5118 }
5119 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5120 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5121 if (!b_data(&ctx->early_buf))
5122 b_free(&ctx->early_buf);
5123 break;
5124 }
5125 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005126 }
5127#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005128 /* If we use SSL_do_handshake to process a reneg initiated by
5129 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5130 * Usually SSL_write and SSL_read are used and process implicitly
5131 * the reneg handshake.
5132 * Here we use SSL_peek as a workaround for reneg.
5133 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005134 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005135 char c;
5136
Olivier Houchard66ab4982019-02-26 18:37:15 +01005137 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005138 if (ret <= 0) {
5139 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005140 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005141
Emeric Brun674b7432012-11-08 19:21:55 +01005142 if (ret == SSL_ERROR_WANT_WRITE) {
5143 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005144 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005145 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005146 return 0;
5147 }
5148 else if (ret == SSL_ERROR_WANT_READ) {
5149 /* handshake may have been completed but we have
5150 * no more data to read.
5151 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005152 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005153 ret = 1;
5154 goto reneg_ok;
5155 }
5156 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005157 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005158 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005159 return 0;
5160 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005161#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005162 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005163 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005164 return 0;
5165 }
5166#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005167 else if (ret == SSL_ERROR_SYSCALL) {
5168 /* if errno is null, then connection was successfully established */
5169 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5170 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005171 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005172#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5173 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005174 conn->err_code = CO_ER_SSL_HANDSHAKE;
5175#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005176 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005177#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005178 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005179 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005180 empty_handshake = state == TLS_ST_BEFORE;
5181#else
Lukas Tribus49799162019-07-08 14:29:15 +02005182 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5183 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005184#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005185 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005186 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005187 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005188 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5189 else
5190 conn->err_code = CO_ER_SSL_EMPTY;
5191 }
5192 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005193 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005194 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5195 else
5196 conn->err_code = CO_ER_SSL_ABORT;
5197 }
5198 }
5199 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005200 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005201 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005202 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005203 conn->err_code = CO_ER_SSL_HANDSHAKE;
5204 }
Lukas Tribus49799162019-07-08 14:29:15 +02005205#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005206 }
Emeric Brun674b7432012-11-08 19:21:55 +01005207 goto out_error;
5208 }
5209 else {
5210 /* Fail on all other handshake errors */
5211 /* Note: OpenSSL may leave unread bytes in the socket's
5212 * buffer, causing an RST to be emitted upon close() on
5213 * TCP sockets. We first try to drain possibly pending
5214 * data to avoid this as much as possible.
5215 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005216 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005217 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005218 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005219 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005220 goto out_error;
5221 }
5222 }
5223 /* read some data: consider handshake completed */
5224 goto reneg_ok;
5225 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005226 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005227check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005228 if (ret != 1) {
5229 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005230 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005231
5232 if (ret == SSL_ERROR_WANT_WRITE) {
5233 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005234 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005235 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005236 return 0;
5237 }
5238 else if (ret == SSL_ERROR_WANT_READ) {
5239 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005240 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005241 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5242 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005243 return 0;
5244 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005245#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005246 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005247 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005248 return 0;
5249 }
5250#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005251 else if (ret == SSL_ERROR_SYSCALL) {
5252 /* if errno is null, then connection was successfully established */
5253 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5254 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005255 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005256#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5257 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005258 conn->err_code = CO_ER_SSL_HANDSHAKE;
5259#else
5260 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005261#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005262 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005263 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005264 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005265#else
Lukas Tribus49799162019-07-08 14:29:15 +02005266 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5267 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005268#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005269 if (empty_handshake) {
5270 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005271 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005272 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5273 else
5274 conn->err_code = CO_ER_SSL_EMPTY;
5275 }
5276 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005277 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005278 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5279 else
5280 conn->err_code = CO_ER_SSL_ABORT;
5281 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005282 }
5283 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005284 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005285 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5286 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005287 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005288 }
Lukas Tribus49799162019-07-08 14:29:15 +02005289#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005290 }
Willy Tarreau89230192012-09-28 20:22:13 +02005291 goto out_error;
5292 }
Emeric Brun46591952012-05-18 15:47:34 +02005293 else {
5294 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005295 /* Note: OpenSSL may leave unread bytes in the socket's
5296 * buffer, causing an RST to be emitted upon close() on
5297 * TCP sockets. We first try to drain possibly pending
5298 * data to avoid this as much as possible.
5299 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005300 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005301 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005302 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005303 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005304 goto out_error;
5305 }
5306 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005307#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchard522eea72017-11-03 16:27:47 +01005308 else {
5309 /*
5310 * If the server refused the early data, we have to send a
5311 * 425 to the client, as we no longer have the data to sent
5312 * them again.
5313 */
5314 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005315 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005316 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5317 goto out_error;
5318 }
5319 }
5320 }
5321#endif
5322
Emeric Brun46591952012-05-18 15:47:34 +02005323
Emeric Brun674b7432012-11-08 19:21:55 +01005324reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005325
Willy Tarreau5db847a2019-05-09 14:13:35 +02005326#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005327 /* ASYNC engine API doesn't support moving read/write
5328 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005329 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005330 */
5331 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005332 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005333#endif
Emeric Brun46591952012-05-18 15:47:34 +02005334 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005335 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005336 if (objt_server(conn->target)) {
5337 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5338 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5339 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005340 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005341 else {
5342 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5343 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5344 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5345 }
Emeric Brun46591952012-05-18 15:47:34 +02005346 }
5347
5348 /* The connection is now established at both layers, it's time to leave */
5349 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5350 return 1;
5351
5352 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005353 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005354 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005355 ERR_clear_error();
5356
Emeric Brun9fa89732012-10-04 17:09:56 +02005357 /* free resumed session if exists */
Willy Tarreau07d94e42018-09-20 10:57:52 +02005358 if (objt_server(conn->target) && __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5359 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
5360 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Emeric Brun9fa89732012-10-04 17:09:56 +02005361 }
5362
Emeric Brun46591952012-05-18 15:47:34 +02005363 /* Fail on all other handshake errors */
5364 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005365 if (!conn->err_code)
5366 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005367 return 0;
5368}
5369
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005370/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5371 * event subscriber <es> is not allowed to change from a previous call as long
5372 * as at least one event is still subscribed. The <event_type> must only be a
5373 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5374 * unless the transport layer was already released.
5375 */
5376static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005377{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005378 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005379
Olivier Houchard0ff28652019-06-24 18:57:39 +02005380 if (!ctx)
5381 return -1;
5382
Willy Tarreau113d52b2020-01-10 09:20:26 +01005383 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005384 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005385
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005386 ctx->subs = es;
5387 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005388
5389 /* we may have to subscribe to lower layers for new events */
5390 event_type &= ~ctx->wait_event.events;
5391 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5392 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005393 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005394}
5395
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005396/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5397 * The <es> pointer is not allowed to differ from the one passed to the
5398 * subscribe() call. It always returns zero.
5399 */
5400static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005401{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005402 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005403
Willy Tarreau113d52b2020-01-10 09:20:26 +01005404 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005405 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005406
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005407 es->events &= ~event_type;
5408 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005409 ctx->subs = NULL;
5410
5411 /* If we subscribed, and we're not doing the handshake,
5412 * then we subscribed because the upper layer asked for it,
5413 * as the upper layer is no longer interested, we can
5414 * unsubscribe too.
5415 */
5416 event_type &= ctx->wait_event.events;
5417 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5418 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005419
5420 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005421}
5422
Olivier Houchard2e055482019-05-27 19:50:12 +02005423/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5424 * Returns 0 on success, and non-zero on failure.
5425 */
5426static 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)
5427{
5428 struct ssl_sock_ctx *ctx = xprt_ctx;
5429
5430 if (oldxprt_ops != NULL)
5431 *oldxprt_ops = ctx->xprt;
5432 if (oldxprt_ctx != NULL)
5433 *oldxprt_ctx = ctx->xprt_ctx;
5434 ctx->xprt = toadd_ops;
5435 ctx->xprt_ctx = toadd_ctx;
5436 return 0;
5437}
5438
Olivier Houchard5149b592019-05-23 17:47:36 +02005439/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5440 * return 0, otherwise just call the remove_xprt method from the underlying
5441 * XPRT.
5442 */
5443static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5444{
5445 struct ssl_sock_ctx *ctx = xprt_ctx;
5446
5447 if (ctx->xprt_ctx == toremove_ctx) {
5448 ctx->xprt_ctx = newctx;
5449 ctx->xprt = newops;
5450 return 0;
5451 }
5452 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5453}
5454
Olivier Houchardea8dd942019-05-20 14:02:16 +02005455static struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned short state)
5456{
5457 struct ssl_sock_ctx *ctx = context;
5458
5459 /* First if we're doing an handshake, try that */
5460 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS)
5461 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
5462 /* If we had an error, or the handshake is done and I/O is available,
5463 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005464 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005465 * we can't be sure conn_fd_handler() will be called again.
5466 */
5467 if ((ctx->conn->flags & CO_FL_ERROR) ||
5468 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5469 int ret = 0;
5470 int woke = 0;
5471
5472 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005473 if (ctx->subs) {
5474 tasklet_wakeup(ctx->subs->tasklet);
5475 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005476 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005477 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005478 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005479
Olivier Houchardea8dd942019-05-20 14:02:16 +02005480 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005481 * upper layers know. If we have no mux, create it,
5482 * and once we have a mux, call its wake method if we didn't
5483 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005484 */
5485 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005486 if (!ctx->conn->mux)
5487 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005488 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
5489 ctx->conn->mux->wake(ctx->conn);
5490 return NULL;
5491 }
5492 }
Olivier Houchard54907bb2019-12-19 15:02:39 +01005493#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5494 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005495 else if (b_data(&ctx->early_buf) && ctx->subs &&
5496 ctx->subs->events & SUB_RETRY_RECV) {
5497 tasklet_wakeup(ctx->subs->tasklet);
5498 ctx->subs->events &= ~SUB_RETRY_RECV;
5499 if (!ctx->subs->events)
5500 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005501 }
5502#endif
Olivier Houchardea8dd942019-05-20 14:02:16 +02005503 return NULL;
5504}
5505
Emeric Brun46591952012-05-18 15:47:34 +02005506/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01005507 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02005508 * buffer wraps, in which case a second call may be performed. The connection's
5509 * flags are updated with whatever special event is detected (error, read0,
5510 * empty). The caller is responsible for taking care of those events and
5511 * avoiding the call if inappropriate. The function does not call the
5512 * connection's polling update function, so the caller is responsible for this.
5513 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005514static 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 +02005515{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005516 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02005517 ssize_t ret;
5518 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02005519
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005520 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005521 goto out_error;
5522
Olivier Houchard54907bb2019-12-19 15:02:39 +01005523#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5524 if (b_data(&ctx->early_buf)) {
5525 try = b_contig_space(buf);
5526 if (try > b_data(&ctx->early_buf))
5527 try = b_data(&ctx->early_buf);
5528 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
5529 b_add(buf, try);
5530 b_del(&ctx->early_buf, try);
5531 if (b_data(&ctx->early_buf) == 0)
5532 b_free(&ctx->early_buf);
5533 return try;
5534 }
5535#endif
5536
Willy Tarreau911db9b2020-01-23 16:27:54 +01005537 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005538 /* a handshake was requested */
5539 return 0;
5540
Emeric Brun46591952012-05-18 15:47:34 +02005541 /* read the largest possible block. For this, we perform only one call
5542 * to recv() unless the buffer wraps and we exactly fill the first hunk,
5543 * in which case we accept to do it once again. A new attempt is made on
5544 * EINTR too.
5545 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01005546 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005547
Willy Tarreau591d4452018-06-15 17:21:00 +02005548 try = b_contig_space(buf);
5549 if (!try)
5550 break;
5551
Willy Tarreauabf08d92014-01-14 11:31:27 +01005552 if (try > count)
5553 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02005554
Olivier Houchard66ab4982019-02-26 18:37:15 +01005555 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005556
Emeric Brune1f38db2012-09-03 20:36:47 +02005557 if (conn->flags & CO_FL_ERROR) {
5558 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005559 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005560 }
Emeric Brun46591952012-05-18 15:47:34 +02005561 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02005562 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005563 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005564 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005565 }
Emeric Brun46591952012-05-18 15:47:34 +02005566 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005567 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005568 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005569 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02005570 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005571 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005572#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005573 /* Async mode can be re-enabled, because we're leaving data state.*/
5574 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005575 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005576#endif
Emeric Brun46591952012-05-18 15:47:34 +02005577 break;
5578 }
5579 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005580 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005581 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5582 SUB_RETRY_RECV,
5583 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01005584 /* handshake is running, and it may need to re-enable read */
5585 conn->flags |= CO_FL_SSL_WAIT_HS;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005586#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005587 /* Async mode can be re-enabled, because we're leaving data state.*/
5588 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005589 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005590#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005591 break;
5592 }
Emeric Brun46591952012-05-18 15:47:34 +02005593 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005594 } else if (ret == SSL_ERROR_ZERO_RETURN)
5595 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005596 /* For SSL_ERROR_SYSCALL, make sure to clear the error
5597 * stack before shutting down the connection for
5598 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005599 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
5600 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02005601 /* otherwise it's a real error */
5602 goto out_error;
5603 }
5604 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005605 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005606 return done;
5607
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005608 clear_ssl_error:
5609 /* Clear openssl global errors stack */
5610 ssl_sock_dump_errors(conn);
5611 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02005612 read0:
5613 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005614 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005615
Emeric Brun46591952012-05-18 15:47:34 +02005616 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005617 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01005618 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005619 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005620 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005621 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005622}
5623
5624
Willy Tarreau787db9a2018-06-14 18:31:46 +02005625/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
5626 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
5627 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02005628 * Only one call to send() is performed, unless the buffer wraps, in which case
5629 * a second call may be performed. The connection's flags are updated with
5630 * whatever special event is detected (error, empty). The caller is responsible
5631 * for taking care of those events and avoiding the call if inappropriate. The
5632 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02005633 * is responsible for this. The buffer's output is not adjusted, it's up to the
5634 * caller to take care of this. It's up to the caller to update the buffer's
5635 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02005636 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005637static 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 +02005638{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005639 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005640 ssize_t ret;
5641 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02005642
5643 done = 0;
5644
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005645 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005646 goto out_error;
5647
Willy Tarreau911db9b2020-01-23 16:27:54 +01005648 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005649 /* a handshake was requested */
5650 return 0;
5651
5652 /* send the largest possible block. For this we perform only one call
5653 * to send() unless the buffer wraps and we exactly fill the first hunk,
5654 * in which case we accept to do it once again.
5655 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02005656 while (count) {
Willy Tarreau5db847a2019-05-09 14:13:35 +02005657#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchardc2aae742017-09-22 18:26:28 +02005658 size_t written_data;
5659#endif
5660
Willy Tarreau787db9a2018-06-14 18:31:46 +02005661 try = b_contig_data(buf, done);
5662 if (try > count)
5663 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01005664
Willy Tarreau7bed9452014-02-02 02:00:24 +01005665 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005666 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01005667 global_ssl.max_record && try > global_ssl.max_record) {
5668 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005669 }
5670 else {
5671 /* we need to keep the information about the fact that
5672 * we're not limiting the upcoming send(), because if it
5673 * fails, we'll have to retry with at least as many data.
5674 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005675 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005676 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01005677
Willy Tarreau5db847a2019-05-09 14:13:35 +02005678#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchard010941f2019-05-03 20:56:19 +02005679 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005680 unsigned int max_early;
5681
Olivier Houchard522eea72017-11-03 16:27:47 +01005682 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01005683 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01005684 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005685 if (SSL_get0_session(ctx->ssl))
5686 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01005687 else
5688 max_early = 0;
5689 }
5690
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005691 if (try + ctx->sent_early_data > max_early) {
5692 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01005693 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02005694 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005695 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005696 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01005697 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005698 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005699 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005700 if (ret == 1) {
5701 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005702 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005703 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005704 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005705 /* Initiate the handshake, now */
5706 tasklet_wakeup(ctx->wait_event.tasklet);
5707 }
Olivier Houchard522eea72017-11-03 16:27:47 +01005708
Olivier Houchardc2aae742017-09-22 18:26:28 +02005709 }
5710
5711 } else
5712#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005713 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01005714
Emeric Brune1f38db2012-09-03 20:36:47 +02005715 if (conn->flags & CO_FL_ERROR) {
5716 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005717 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005718 }
Emeric Brun46591952012-05-18 15:47:34 +02005719 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005720 /* A send succeeded, so we can consider ourself connected */
5721 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005722 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005723 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005724 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005725 }
5726 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005727 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005728
Emeric Brun46591952012-05-18 15:47:34 +02005729 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005730 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01005731 /* handshake is running, and it may need to re-enable write */
5732 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005733 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005734#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005735 /* Async mode can be re-enabled, because we're leaving data state.*/
5736 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005737 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005738#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005739 break;
5740 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005741
Emeric Brun46591952012-05-18 15:47:34 +02005742 break;
5743 }
5744 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005745 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02005746 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005747 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5748 SUB_RETRY_RECV,
5749 &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005750#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005751 /* Async mode can be re-enabled, because we're leaving data state.*/
5752 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005753 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005754#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005755 break;
5756 }
Emeric Brun46591952012-05-18 15:47:34 +02005757 goto out_error;
5758 }
5759 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005760 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005761 return done;
5762
5763 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005764 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005765 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005766 ERR_clear_error();
5767
Emeric Brun46591952012-05-18 15:47:34 +02005768 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005769 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005770}
5771
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005772static void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02005773
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005774 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005775
Olivier Houchardea8dd942019-05-20 14:02:16 +02005776
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005777 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005778 if (ctx->wait_event.events != 0)
5779 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
5780 ctx->wait_event.events,
5781 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01005782 if (ctx->subs) {
5783 ctx->subs->events = 0;
5784 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005785 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005786
Olivier Houchard692c1d02019-05-23 18:41:47 +02005787 if (ctx->xprt->close)
5788 ctx->xprt->close(conn, ctx->xprt_ctx);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005789#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +02005790 if (global_ssl.async) {
5791 OSSL_ASYNC_FD all_fd[32], afd;
5792 size_t num_all_fds = 0;
5793 int i;
5794
Olivier Houchard66ab4982019-02-26 18:37:15 +01005795 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005796 if (num_all_fds > 32) {
5797 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
5798 return;
5799 }
5800
Olivier Houchard66ab4982019-02-26 18:37:15 +01005801 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005802
5803 /* If an async job is pending, we must try to
5804 to catch the end using polling before calling
5805 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005806 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02005807 for (i=0 ; i < num_all_fds ; i++) {
5808 /* switch on an handler designed to
5809 * handle the SSL_free
5810 */
5811 afd = all_fd[i];
5812 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005813 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02005814 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00005815 /* To ensure that the fd cache won't be used
5816 * and we'll catch a real RD event.
5817 */
5818 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02005819 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005820 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005821 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005822 _HA_ATOMIC_ADD(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005823 return;
5824 }
Emeric Brun3854e012017-05-17 20:42:48 +02005825 /* Else we can remove the fds from the fdtab
5826 * and call SSL_free.
5827 * note: we do a fd_remove and not a delete
5828 * because the fd is owned by the engine.
5829 * the engine is responsible to close
5830 */
5831 for (i=0 ; i < num_all_fds ; i++)
5832 fd_remove(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005833 }
5834#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005835 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01005836 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005837 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005838 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005839 _HA_ATOMIC_SUB(&sslconns, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005840 }
Emeric Brun46591952012-05-18 15:47:34 +02005841}
5842
5843/* This function tries to perform a clean shutdown on an SSL connection, and in
5844 * any case, flags the connection as reusable if no handshake was in progress.
5845 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005846static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02005847{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005848 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005849
Willy Tarreau911db9b2020-01-23 16:27:54 +01005850 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005851 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01005852 if (!clean)
5853 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005854 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005855 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005856 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01005857 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005858 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005859 ERR_clear_error();
5860 }
Emeric Brun46591952012-05-18 15:47:34 +02005861}
5862
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01005863
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005864/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01005865int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
5866{
5867 struct ssl_sock_ctx *ctx;
5868 X509 *crt;
5869
5870 if (!ssl_sock_is_ssl(conn))
5871 return 0;
5872
5873 ctx = conn->xprt_ctx;
5874
5875 crt = SSL_get_certificate(ctx->ssl);
5876 if (!crt)
5877 return 0;
5878
5879 return cert_get_pkey_algo(crt, out);
5880}
5881
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005882/* used for ppv2 cert signature (can be used for logging) */
5883const char *ssl_sock_get_cert_sig(struct connection *conn)
5884{
Christopher Faulet82004142019-09-10 10:12:03 +02005885 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005886
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005887 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
5888 X509 *crt;
5889
5890 if (!ssl_sock_is_ssl(conn))
5891 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005892 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005893 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005894 if (!crt)
5895 return NULL;
5896 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
5897 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
5898}
5899
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005900/* used for ppv2 authority */
5901const char *ssl_sock_get_sni(struct connection *conn)
5902{
5903#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02005904 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005905
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005906 if (!ssl_sock_is_ssl(conn))
5907 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005908 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005909 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005910#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01005911 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005912#endif
5913}
5914
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005915/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005916const char *ssl_sock_get_cipher_name(struct connection *conn)
5917{
Christopher Faulet82004142019-09-10 10:12:03 +02005918 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005919
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005920 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005921 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005922 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005923 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005924}
5925
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005926/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005927const char *ssl_sock_get_proto_version(struct connection *conn)
5928{
Christopher Faulet82004142019-09-10 10:12:03 +02005929 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005930
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005931 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005932 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005933 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005934 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005935}
5936
Olivier Houchardab28a322018-12-21 19:45:40 +01005937void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
5938{
5939#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02005940 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005941
Olivier Houcharde488ea82019-06-28 14:10:33 +02005942 if (!ssl_sock_is_ssl(conn))
5943 return;
Christopher Faulet82004142019-09-10 10:12:03 +02005944 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005945 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01005946#endif
5947}
5948
Willy Tarreau119a4082016-12-22 21:58:38 +01005949/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
5950 * to disable SNI.
5951 */
Willy Tarreau63076412015-07-10 11:33:32 +02005952void ssl_sock_set_servername(struct connection *conn, const char *hostname)
5953{
5954#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02005955 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005956
Willy Tarreau119a4082016-12-22 21:58:38 +01005957 char *prev_name;
5958
Willy Tarreau63076412015-07-10 11:33:32 +02005959 if (!ssl_sock_is_ssl(conn))
5960 return;
Christopher Faulet82004142019-09-10 10:12:03 +02005961 ctx = conn->xprt_ctx;
Willy Tarreau63076412015-07-10 11:33:32 +02005962
Willy Tarreau119a4082016-12-22 21:58:38 +01005963 /* if the SNI changes, we must destroy the reusable context so that a
5964 * new connection will present a new SNI. As an optimization we could
5965 * later imagine having a small cache of ssl_ctx to hold a few SNI per
5966 * server.
5967 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005968 prev_name = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau119a4082016-12-22 21:58:38 +01005969 if ((!prev_name && hostname) ||
5970 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01005971 SSL_set_session(ctx->ssl, NULL);
Willy Tarreau119a4082016-12-22 21:58:38 +01005972
Olivier Houchard66ab4982019-02-26 18:37:15 +01005973 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02005974#endif
5975}
5976
Emeric Brun0abf8362014-06-24 18:26:41 +02005977/* Extract peer certificate's common name into the chunk dest
5978 * Returns
5979 * the len of the extracted common name
5980 * or 0 if no CN found in DN
5981 * or -1 on error case (i.e. no peer certificate)
5982 */
Willy Tarreau83061a82018-07-13 11:56:34 +02005983int ssl_sock_get_remote_common_name(struct connection *conn,
5984 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04005985{
Christopher Faulet82004142019-09-10 10:12:03 +02005986 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04005987 X509 *crt = NULL;
5988 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04005989 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02005990 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005991 .area = (char *)&find_cn,
5992 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04005993 };
Emeric Brun0abf8362014-06-24 18:26:41 +02005994 int result = -1;
David Safb76832014-05-08 23:42:08 -04005995
5996 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02005997 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02005998 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04005999
6000 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006001 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006002 if (!crt)
6003 goto out;
6004
6005 name = X509_get_subject_name(crt);
6006 if (!name)
6007 goto out;
David Safb76832014-05-08 23:42:08 -04006008
Emeric Brun0abf8362014-06-24 18:26:41 +02006009 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6010out:
David Safb76832014-05-08 23:42:08 -04006011 if (crt)
6012 X509_free(crt);
6013
6014 return result;
6015}
6016
Dave McCowan328fb582014-07-30 10:39:13 -04006017/* returns 1 if client passed a certificate for this session, 0 if not */
6018int ssl_sock_get_cert_used_sess(struct connection *conn)
6019{
Christopher Faulet82004142019-09-10 10:12:03 +02006020 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006021 X509 *crt = NULL;
6022
6023 if (!ssl_sock_is_ssl(conn))
6024 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006025 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006026
6027 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006028 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006029 if (!crt)
6030 return 0;
6031
6032 X509_free(crt);
6033 return 1;
6034}
6035
6036/* returns 1 if client passed a certificate for this connection, 0 if not */
6037int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006038{
Christopher Faulet82004142019-09-10 10:12:03 +02006039 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006040
David Safb76832014-05-08 23:42:08 -04006041 if (!ssl_sock_is_ssl(conn))
6042 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006043 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006044 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006045}
6046
6047/* returns result from SSL verify */
6048unsigned int ssl_sock_get_verify_result(struct connection *conn)
6049{
Christopher Faulet82004142019-09-10 10:12:03 +02006050 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006051
David Safb76832014-05-08 23:42:08 -04006052 if (!ssl_sock_is_ssl(conn))
6053 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006054 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006055 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006056}
6057
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006058/* Returns the application layer protocol name in <str> and <len> when known.
6059 * Zero is returned if the protocol name was not found, otherwise non-zero is
6060 * returned. The string is allocated in the SSL context and doesn't have to be
6061 * freed by the caller. NPN is also checked if available since older versions
6062 * of openssl (1.0.1) which are more common in field only support this one.
6063 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006064static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006065{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006066#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6067 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006068 struct ssl_sock_ctx *ctx = xprt_ctx;
6069 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006070 return 0;
6071
6072 *str = NULL;
6073
6074#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006075 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006076 if (*str)
6077 return 1;
6078#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006079#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006080 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006081 if (*str)
6082 return 1;
6083#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006084#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006085 return 0;
6086}
6087
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006088/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006089int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006090{
6091 X509 *ca;
6092 X509_NAME *name = NULL;
6093 ASN1_OCTET_STRING *skid = NULL;
6094 STACK_OF(X509) *chain = NULL;
6095 struct issuer_chain *issuer;
6096 struct eb64_node *node;
6097 char *path;
6098 u64 key;
6099 int ret = 0;
6100
6101 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6102 if (chain == NULL) {
6103 chain = sk_X509_new_null();
6104 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6105 name = X509_get_subject_name(ca);
6106 }
6107 if (!sk_X509_push(chain, ca)) {
6108 X509_free(ca);
6109 goto end;
6110 }
6111 }
6112 if (!chain) {
6113 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6114 goto end;
6115 }
6116 if (!skid) {
6117 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6118 goto end;
6119 }
6120 if (!name) {
6121 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6122 goto end;
6123 }
6124 key = XXH64(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006125 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006126 issuer = container_of(node, typeof(*issuer), node);
6127 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6128 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6129 goto end;
6130 }
6131 }
6132 issuer = calloc(1, sizeof *issuer);
6133 path = strdup(fp);
6134 if (!issuer || !path) {
6135 free(issuer);
6136 free(path);
6137 goto end;
6138 }
6139 issuer->node.key = key;
6140 issuer->path = path;
6141 issuer->chain = chain;
6142 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006143 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006144 ret = 1;
6145 end:
6146 if (skid)
6147 ASN1_OCTET_STRING_free(skid);
6148 if (chain)
6149 sk_X509_pop_free(chain, X509_free);
6150 return ret;
6151}
6152
William Lallemandda8584c2020-05-14 10:14:37 +02006153 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006154{
6155 AUTHORITY_KEYID *akid;
6156 struct issuer_chain *issuer = NULL;
6157
6158 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
6159 if (akid) {
6160 struct eb64_node *node;
6161 u64 hk;
6162 hk = XXH64(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
6163 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6164 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6165 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6166 issuer = ti;
6167 break;
6168 }
6169 }
6170 AUTHORITY_KEYID_free(akid);
6171 }
6172 return issuer;
6173}
6174
William Lallemanddad31052020-05-14 17:47:32 +02006175void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006176{
6177 struct eb64_node *node, *back;
6178 struct issuer_chain *issuer;
6179
William Lallemande0f3fd52020-02-25 14:53:06 +01006180 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006181 while (node) {
6182 issuer = container_of(node, typeof(*issuer), node);
6183 back = eb64_next(node);
6184 eb64_delete(node);
6185 free(issuer->path);
6186 sk_X509_pop_free(issuer->chain, X509_free);
6187 free(issuer);
6188 node = back;
6189 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006190}
6191
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006192#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006193static int ssl_check_async_engine_count(void) {
6194 int err_code = 0;
6195
Emeric Brun3854e012017-05-17 20:42:48 +02006196 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006197 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006198 err_code = ERR_ABORT;
6199 }
6200 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006201}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006202#endif
6203
William Lallemand32af2032016-10-29 18:09:35 +02006204/* This function is used with TLS ticket keys management. It permits to browse
6205 * each reference. The variable <getnext> must contain the current node,
6206 * <end> point to the root node.
6207 */
6208#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6209static inline
6210struct tls_keys_ref *tlskeys_list_get_next(struct tls_keys_ref *getnext, struct list *end)
6211{
6212 struct tls_keys_ref *ref = getnext;
6213
6214 while (1) {
6215
6216 /* Get next list entry. */
6217 ref = LIST_NEXT(&ref->list, struct tls_keys_ref *, list);
6218
6219 /* If the entry is the last of the list, return NULL. */
6220 if (&ref->list == end)
6221 return NULL;
6222
6223 return ref;
6224 }
6225}
6226
6227static inline
6228struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6229{
6230 int id;
6231 char *error;
6232
6233 /* If the reference starts by a '#', this is numeric id. */
6234 if (reference[0] == '#') {
6235 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6236 id = strtol(reference + 1, &error, 10);
6237 if (*error != '\0')
6238 return NULL;
6239
6240 /* Perform the unique id lookup. */
6241 return tlskeys_ref_lookupid(id);
6242 }
6243
6244 /* Perform the string lookup. */
6245 return tlskeys_ref_lookup(reference);
6246}
6247#endif
6248
6249
6250#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6251
6252static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6253
6254static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6255 return cli_io_handler_tlskeys_files(appctx);
6256}
6257
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006258/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6259 * (next index to be dumped), and cli.p0 (next key reference).
6260 */
William Lallemand32af2032016-10-29 18:09:35 +02006261static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6262
6263 struct stream_interface *si = appctx->owner;
6264
6265 switch (appctx->st2) {
6266 case STAT_ST_INIT:
6267 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006268 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006269 * later and restart at the state "STAT_ST_INIT".
6270 */
6271 chunk_reset(&trash);
6272
6273 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6274 chunk_appendf(&trash, "# id secret\n");
6275 else
6276 chunk_appendf(&trash, "# id (file)\n");
6277
Willy Tarreau06d80a92017-10-19 14:32:15 +02006278 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006279 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006280 return 0;
6281 }
6282
William Lallemand32af2032016-10-29 18:09:35 +02006283 /* Now, we start the browsing of the references lists.
6284 * Note that the following call to LIST_ELEM return bad pointer. The only
6285 * available field of this pointer is <list>. It is used with the function
6286 * tlskeys_list_get_next() for retruning the first available entry
6287 */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006288 if (appctx->ctx.cli.p0 == NULL) {
6289 appctx->ctx.cli.p0 = LIST_ELEM(&tlskeys_reference, struct tls_keys_ref *, list);
6290 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006291 }
6292
6293 appctx->st2 = STAT_ST_LIST;
6294 /* fall through */
6295
6296 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006297 while (appctx->ctx.cli.p0) {
6298 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006299
6300 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006301 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006302 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006303
6304 if (appctx->ctx.cli.i1 == 0)
6305 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6306
William Lallemand32af2032016-10-29 18:09:35 +02006307 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006308 int head;
6309
6310 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6311 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006312 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006313 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006314
6315 chunk_reset(t2);
6316 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006317 if (ref->key_size_bits == 128) {
6318 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6319 sizeof(struct tls_sess_key_128),
6320 t2->area, t2->size);
6321 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6322 t2->area);
6323 }
6324 else if (ref->key_size_bits == 256) {
6325 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6326 sizeof(struct tls_sess_key_256),
6327 t2->area, t2->size);
6328 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6329 t2->area);
6330 }
6331 else {
6332 /* This case should never happen */
6333 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6334 }
William Lallemand32af2032016-10-29 18:09:35 +02006335
Willy Tarreau06d80a92017-10-19 14:32:15 +02006336 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006337 /* let's try again later from this stream. We add ourselves into
6338 * this stream's users so that it can remove us upon termination.
6339 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006340 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006341 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006342 return 0;
6343 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006344 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006345 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006346 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006347 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006348 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006349 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006350 /* let's try again later from this stream. We add ourselves into
6351 * this stream's users so that it can remove us upon termination.
6352 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006353 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006354 return 0;
6355 }
6356
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006357 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006358 break;
6359
6360 /* get next list entry and check the end of the list */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006361 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006362 }
6363
6364 appctx->st2 = STAT_ST_FIN;
6365 /* fall through */
6366
6367 default:
6368 appctx->st2 = STAT_ST_FIN;
6369 return 1;
6370 }
6371 return 0;
6372}
6373
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006374/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006375static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006376{
William Lallemand32af2032016-10-29 18:09:35 +02006377 /* no parameter, shows only file list */
6378 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006379 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006380 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006381 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006382 }
6383
6384 if (args[2][0] == '*') {
6385 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006386 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006387 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006388 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006389 if (!appctx->ctx.cli.p0)
6390 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006391 }
William Lallemand32af2032016-10-29 18:09:35 +02006392 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006393 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006394}
6395
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006396static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006397{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006398 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006399 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006400
William Lallemand32af2032016-10-29 18:09:35 +02006401 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006402 if (!*args[3] || !*args[4])
6403 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 +02006404
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006405 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006406 if (!ref)
6407 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006408
Willy Tarreau1c913e42018-08-22 05:26:57 +02006409 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006410 if (ret < 0)
6411 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006412
Willy Tarreau1c913e42018-08-22 05:26:57 +02006413 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006414 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6415 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006416
Willy Tarreau9d008692019-08-09 11:21:01 +02006417 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006418}
William Lallemandd4f946c2019-12-05 10:26:40 +01006419#endif
William Lallemand419e6342020-04-08 12:05:39 +02006420
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006421static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006422{
6423#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6424 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006425 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006426
6427 if (!payload)
6428 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006429
6430 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006431 if (!*payload)
6432 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006433
6434 /* remove \r and \n from the payload */
6435 for (i = 0, j = 0; payload[i]; i++) {
6436 if (payload[i] == '\r' || payload[i] == '\n')
6437 continue;
6438 payload[j++] = payload[i];
6439 }
6440 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006441
Willy Tarreau1c913e42018-08-22 05:26:57 +02006442 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006443 if (ret < 0)
6444 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006445
Willy Tarreau1c913e42018-08-22 05:26:57 +02006446 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02006447 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02006448 if (err)
6449 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
6450 else
6451 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006452 }
Willy Tarreau9d008692019-08-09 11:21:01 +02006453
6454 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006455#else
Willy Tarreau9d008692019-08-09 11:21:01 +02006456 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 +02006457#endif
6458
Elliot Otchet71f82972020-01-15 08:12:14 -05006459}
6460
William Lallemand32af2032016-10-29 18:09:35 +02006461/* register cli keywords */
6462static struct cli_kw_list cli_kws = {{ },{
6463#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6464 { { "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 +02006465 { { "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 +02006466#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006467 { { "set", "ssl", "ocsp-response", NULL }, NULL, cli_parse_set_ocspresponse, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02006468 { { NULL }, NULL, NULL, NULL }
6469}};
6470
Willy Tarreau0108d902018-11-25 19:14:37 +01006471INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02006472
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02006473/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02006474struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02006475 .snd_buf = ssl_sock_from_buf,
6476 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01006477 .subscribe = ssl_subscribe,
6478 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02006479 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02006480 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02006481 .rcv_pipe = NULL,
6482 .snd_pipe = NULL,
6483 .shutr = NULL,
6484 .shutw = ssl_sock_shutw,
6485 .close = ssl_sock_close,
6486 .init = ssl_sock_init,
Willy Tarreau55d37912016-12-21 23:38:39 +01006487 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01006488 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01006489 .prepare_srv = ssl_sock_prepare_srv_ctx,
6490 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006491 .get_alpn = ssl_sock_get_alpn,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01006492 .name = "SSL",
Emeric Brun46591952012-05-18 15:47:34 +02006493};
6494
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006495enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
6496 struct session *sess, struct stream *s, int flags)
6497{
6498 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006499 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006500
6501 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006502 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006503
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006504 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006505 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006506 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006507 s->req.flags |= CF_READ_NULL;
6508 return ACT_RET_YIELD;
6509 }
6510 }
6511 return (ACT_RET_CONT);
6512}
6513
6514static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
6515{
6516 rule->action_ptr = ssl_action_wait_for_hs;
6517
6518 return ACT_RET_PRS_OK;
6519}
6520
6521static struct action_kw_list http_req_actions = {ILH, {
6522 { "wait-for-handshake", ssl_parse_wait_for_hs },
6523 { /* END */ }
6524}};
6525
Willy Tarreau0108d902018-11-25 19:14:37 +01006526INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
6527
Willy Tarreau5db847a2019-05-09 14:13:35 +02006528#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006529
6530static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6531{
6532 if (ptr) {
6533 chunk_destroy(ptr);
6534 free(ptr);
6535 }
6536}
6537
6538#endif
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006539static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6540{
Willy Tarreaubafbe012017-11-24 17:34:44 +01006541 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006542}
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006543
Emeric Brun46591952012-05-18 15:47:34 +02006544__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02006545static void __ssl_sock_init(void)
6546{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006547#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006548 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006549 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006550#endif
Emeric Brun46591952012-05-18 15:47:34 +02006551
Willy Tarreauef934602016-12-22 23:12:01 +01006552 if (global_ssl.listen_default_ciphers)
6553 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
6554 if (global_ssl.connect_default_ciphers)
6555 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Emmanuel Hocdet839af572019-05-14 16:27:35 +02006556#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02006557 if (global_ssl.listen_default_ciphersuites)
6558 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
6559 if (global_ssl.connect_default_ciphersuites)
6560 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
6561#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01006562
Willy Tarreau13e14102016-12-22 20:25:26 +01006563 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006564#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02006565 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08006566#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006567#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006568 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006569 n = sk_SSL_COMP_num(cm);
6570 while (n--) {
6571 (void) sk_SSL_COMP_pop(cm);
6572 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006573#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006574
Willy Tarreau5db847a2019-05-09 14:13:35 +02006575#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006576 ssl_locking_init();
6577#endif
Willy Tarreau5db847a2019-05-09 14:13:35 +02006578#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006579 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
6580#endif
Thierry FOURNIER28962c92018-06-17 21:37:05 +02006581 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02006582 ssl_capture_ptr_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_capture_free_func);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006583#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006584 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006585 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006586#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01006587#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6588 hap_register_post_check(tlskeys_finalize_config);
6589#endif
Willy Tarreau80713382018-11-26 10:19:54 +01006590
6591 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
6592 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
6593
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006594 hap_register_post_deinit(ssl_free_global_issuers);
6595
Willy Tarreau80713382018-11-26 10:19:54 +01006596#ifndef OPENSSL_NO_DH
6597 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
6598 hap_register_post_deinit(ssl_free_dh);
6599#endif
6600#ifndef OPENSSL_NO_ENGINE
6601 hap_register_post_deinit(ssl_free_engines);
6602#endif
6603 /* Load SSL string for the verbose & debug mode. */
6604 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02006605 ha_meth = BIO_meth_new(0x666, "ha methods");
6606 BIO_meth_set_write(ha_meth, ha_ssl_write);
6607 BIO_meth_set_read(ha_meth, ha_ssl_read);
6608 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
6609 BIO_meth_set_create(ha_meth, ha_ssl_new);
6610 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
6611 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
6612 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02006613
6614 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006615
Dragan Dosen9ac98092020-05-11 15:51:45 +02006616 /* Try to register dedicated SSL/TLS protocol message callbacks for
6617 * heartbleed attack (CVE-2014-0160) and clienthello.
6618 */
6619 hap_register_post_check(ssl_sock_register_msg_callbacks);
6620
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006621 /* Try to free all callbacks that were registered by using
6622 * ssl_sock_register_msg_callback().
6623 */
6624 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01006625}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01006626
Willy Tarreau80713382018-11-26 10:19:54 +01006627/* Compute and register the version string */
6628static void ssl_register_build_options()
6629{
6630 char *ptr = NULL;
6631 int i;
6632
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006633 memprintf(&ptr, "Built with OpenSSL version : "
6634#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006635 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006636#else /* OPENSSL_IS_BORINGSSL */
6637 OPENSSL_VERSION_TEXT
6638 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08006639 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02006640 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006641#endif
6642 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006643#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006644 "no (library version too old)"
6645#elif defined(OPENSSL_NO_TLSEXT)
6646 "no (disabled via OPENSSL_NO_TLSEXT)"
6647#else
6648 "yes"
6649#endif
6650 "", ptr);
6651
6652 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
6653#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
6654 "yes"
6655#else
6656#ifdef OPENSSL_NO_TLSEXT
6657 "no (because of OPENSSL_NO_TLSEXT)"
6658#else
6659 "no (version might be too old, 0.9.8f min needed)"
6660#endif
6661#endif
6662 "", ptr);
6663
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02006664 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
6665 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
6666 if (methodVersions[i].option)
6667 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006668
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006669 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01006670}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006671
Willy Tarreau80713382018-11-26 10:19:54 +01006672INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02006673
Emeric Brun46591952012-05-18 15:47:34 +02006674
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006675#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006676void ssl_free_engines(void) {
6677 struct ssl_engine_list *wl, *wlb;
6678 /* free up engine list */
6679 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
6680 ENGINE_finish(wl->e);
6681 ENGINE_free(wl->e);
6682 LIST_DEL(&wl->list);
6683 free(wl);
6684 }
6685}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006686#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02006687
Remi Gacogned3a23c32015-05-28 16:39:47 +02006688#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00006689void ssl_free_dh(void) {
6690 if (local_dh_1024) {
6691 DH_free(local_dh_1024);
6692 local_dh_1024 = NULL;
6693 }
6694 if (local_dh_2048) {
6695 DH_free(local_dh_2048);
6696 local_dh_2048 = NULL;
6697 }
6698 if (local_dh_4096) {
6699 DH_free(local_dh_4096);
6700 local_dh_4096 = NULL;
6701 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02006702 if (global_dh) {
6703 DH_free(global_dh);
6704 global_dh = NULL;
6705 }
Grant Zhang872f9c22017-01-21 01:10:18 +00006706}
6707#endif
6708
6709__attribute__((destructor))
6710static void __ssl_sock_deinit(void)
6711{
6712#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006713 if (ssl_ctx_lru_tree) {
6714 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01006715 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02006716 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02006717#endif
6718
Willy Tarreau5db847a2019-05-09 14:13:35 +02006719#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006720 ERR_remove_state(0);
6721 ERR_free_strings();
6722
6723 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08006724#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02006725
Willy Tarreau5db847a2019-05-09 14:13:35 +02006726#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006727 CRYPTO_cleanup_all_ex_data();
6728#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02006729 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02006730}
6731
Emeric Brun46591952012-05-18 15:47:34 +02006732/*
6733 * Local variables:
6734 * c-indent-level: 8
6735 * c-basic-offset: 8
6736 * End:
6737 */