blob: 357828d29301dbf6d67e0cbfd06f6685382b9e9e [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 Tarreau8d366972020-05-27 16:10:29 +020049#include <haproxy/errors.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020050#include <haproxy/openssl-compat.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020051#include <haproxy/shctx.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020052#include <haproxy/tools.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020053#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020054#include <haproxy/time.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020055#include <haproxy/base64.h>
Emeric Brun46591952012-05-18 15:47:34 +020056
Willy Tarreau8d2b7772020-05-27 10:58:19 +020057#include <import/ebpttree.h>
58#include <import/ebsttree.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020059
William Lallemand32af2032016-10-29 18:09:35 +020060#include <types/applet.h>
61#include <types/cli.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020062#include <types/global.h>
63#include <types/ssl_sock.h>
William Lallemand32af2032016-10-29 18:09:35 +020064#include <types/stats.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020065
Willy Tarreau7875d092012-09-10 08:20:03 +020066#include <proto/acl.h>
67#include <proto/arg.h>
William Lallemand32af2032016-10-29 18:09:35 +020068#include <proto/channel.h>
Emeric Brun46591952012-05-18 15:47:34 +020069#include <proto/connection.h>
William Lallemand32af2032016-10-29 18:09:35 +020070#include <proto/cli.h>
Willy Tarreau0f6ffd62020-06-03 19:33:00 +020071#include <haproxy/fd.h>
Willy Tarreau66347942020-06-01 12:18:08 +020072#include <haproxy/freq_ctr.h>
Emeric Brun46591952012-05-18 15:47:34 +020073#include <proto/frontend.h>
Willy Tarreau61c112a2018-10-02 16:43:32 +020074#include <proto/http_rules.h>
Willy Tarreau79eeafa2012-09-14 07:53:05 +020075#include <proto/listener.h>
Thierry FOURNIERed66c292013-11-28 11:05:19 +010076#include <proto/pattern.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020077#include <proto/proto_tcp.h>
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020078#include <proto/http_ana.h>
Willy Tarreau92faadf2012-10-10 23:04:25 +020079#include <proto/server.h>
William Lallemand32af2032016-10-29 18:09:35 +020080#include <proto/stream_interface.h>
Emeric Brun46591952012-05-18 15:47:34 +020081#include <proto/log.h>
Emeric Brun94324a42012-10-11 14:00:19 +020082#include <proto/proxy.h>
William Lallemandc69973f2020-05-12 17:42:42 +020083#include <proto/ssl_ckch.h>
William Lallemand6e9556b2020-05-12 17:52:44 +020084#include <proto/ssl_crtlist.h>
Emeric Brun46591952012-05-18 15:47:34 +020085#include <proto/ssl_sock.h>
William Lallemand6a66a5e2020-05-15 12:01:17 +020086#include <proto/ssl_utils.h>
Willy Tarreau9ad7bd42015-04-03 19:19:59 +020087#include <proto/stream.h>
Emeric Brun46591952012-05-18 15:47:34 +020088#include <proto/task.h>
Nenad Merdanovicc31499d2019-03-23 11:00:32 +010089#include <proto/vars.h>
Emeric Brun46591952012-05-18 15:47:34 +020090
Willy Tarreau9356dac2019-05-10 09:22:53 +020091/* ***** READ THIS before adding code here! *****
92 *
93 * Due to API incompatibilities between multiple OpenSSL versions and their
94 * derivatives, it's often tempting to add macros to (re-)define certain
95 * symbols. Please do not do this here, and do it in common/openssl-compat.h
96 * exclusively so that the whole code consistently uses the same macros.
97 *
98 * Whenever possible if a macro is missing in certain versions, it's better
99 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
100 */
101
Willy Tarreau71b734c2014-01-28 15:19:44 +0100102int sslconns = 0;
103int totalsslconns = 0;
Emeric Brunece0c332017-12-06 13:51:49 +0100104int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +0200105
William Lallemande0f3fd52020-02-25 14:53:06 +0100106static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
107
William Lallemand7fd8b452020-05-07 15:20:43 +0200108struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100109#ifdef LISTEN_DEFAULT_CIPHERS
110 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
111#endif
112#ifdef CONNECT_DEFAULT_CIPHERS
113 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
114#endif
Emmanuel Hocdet839af572019-05-14 16:27:35 +0200115#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200116#ifdef LISTEN_DEFAULT_CIPHERSUITES
117 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
118#endif
119#ifdef CONNECT_DEFAULT_CIPHERSUITES
120 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
121#endif
122#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100123 .listen_default_ssloptions = BC_SSL_O_NONE,
124 .connect_default_ssloptions = SRV_SSL_O_NONE,
125
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200126 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
127 .listen_default_sslmethods.min = CONF_TLSV_NONE,
128 .listen_default_sslmethods.max = CONF_TLSV_NONE,
129 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
130 .connect_default_sslmethods.min = CONF_TLSV_NONE,
131 .connect_default_sslmethods.max = CONF_TLSV_NONE,
132
Willy Tarreauef934602016-12-22 23:12:01 +0100133#ifdef DEFAULT_SSL_MAX_RECORD
134 .max_record = DEFAULT_SSL_MAX_RECORD,
135#endif
136 .default_dh_param = SSL_DEFAULT_DH_PARAM,
137 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Thierry FOURNIER5bf77322017-02-25 12:45:22 +0100138 .capture_cipherlist = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100139 .extra_files = SSL_GF_ALL,
Willy Tarreauef934602016-12-22 23:12:01 +0100140};
141
Olivier Houcharda8955d52019-04-07 22:00:38 +0200142static BIO_METHOD *ha_meth;
143
Olivier Houchard66ab4982019-02-26 18:37:15 +0100144DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
145
Olivier Houchardea8dd942019-05-20 14:02:16 +0200146static struct task *ssl_sock_io_cb(struct task *, void *, unsigned short);
Olivier Houchard000694c2019-05-23 14:45:12 +0200147static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200148
Olivier Houcharda8955d52019-04-07 22:00:38 +0200149/* Methods to implement OpenSSL BIO */
150static int ha_ssl_write(BIO *h, const char *buf, int num)
151{
152 struct buffer tmpbuf;
153 struct ssl_sock_ctx *ctx;
154 int ret;
155
156 ctx = BIO_get_data(h);
157 tmpbuf.size = num;
158 tmpbuf.area = (void *)(uintptr_t)buf;
159 tmpbuf.data = num;
160 tmpbuf.head = 0;
161 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200162 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200163 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200164 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200165 } else if (ret == 0)
166 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200167 return ret;
168}
169
170static int ha_ssl_gets(BIO *h, char *buf, int size)
171{
172
173 return 0;
174}
175
176static int ha_ssl_puts(BIO *h, const char *str)
177{
178
179 return ha_ssl_write(h, str, strlen(str));
180}
181
182static int ha_ssl_read(BIO *h, char *buf, int size)
183{
184 struct buffer tmpbuf;
185 struct ssl_sock_ctx *ctx;
186 int ret;
187
188 ctx = BIO_get_data(h);
189 tmpbuf.size = size;
190 tmpbuf.area = buf;
191 tmpbuf.data = 0;
192 tmpbuf.head = 0;
193 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200194 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200195 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200196 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200197 } else if (ret == 0)
198 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200199
200 return ret;
201}
202
203static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
204{
205 int ret = 0;
206 switch (cmd) {
207 case BIO_CTRL_DUP:
208 case BIO_CTRL_FLUSH:
209 ret = 1;
210 break;
211 }
212 return ret;
213}
214
215static int ha_ssl_new(BIO *h)
216{
217 BIO_set_init(h, 1);
218 BIO_set_data(h, NULL);
219 BIO_clear_flags(h, ~0);
220 return 1;
221}
222
223static int ha_ssl_free(BIO *data)
224{
225
226 return 1;
227}
228
229
Willy Tarreau5db847a2019-05-09 14:13:35 +0200230#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100231
Emeric Brun821bb9b2017-06-15 16:37:39 +0200232static HA_RWLOCK_T *ssl_rwlocks;
233
234
235unsigned long ssl_id_function(void)
236{
237 return (unsigned long)tid;
238}
239
240void ssl_locking_function(int mode, int n, const char * file, int line)
241{
242 if (mode & CRYPTO_LOCK) {
243 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100244 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200245 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100246 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200247 }
248 else {
249 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100250 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200251 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100252 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200253 }
254}
255
256static int ssl_locking_init(void)
257{
258 int i;
259
260 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
261 if (!ssl_rwlocks)
262 return -1;
263
264 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100265 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200266
267 CRYPTO_set_id_callback(ssl_id_function);
268 CRYPTO_set_locking_callback(ssl_locking_function);
269
270 return 0;
271}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100272
Emeric Brun821bb9b2017-06-15 16:37:39 +0200273#endif
274
Willy Tarreauaf613e82020-06-05 08:40:51 +0200275__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200276
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100277
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200278/*
Emmanuel Hocdetb270e812019-11-21 19:09:31 +0100279 * deduplicate cafile (and crlfile)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200280 */
281struct cafile_entry {
282 X509_STORE *ca_store;
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200283 STACK_OF(X509_NAME) *ca_list;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200284 struct ebmb_node node;
285 char path[0];
286};
287
288static struct eb_root cafile_tree = EB_ROOT_UNIQUE;
289
290static X509_STORE* ssl_store_get0_locations_file(char *path)
291{
292 struct ebmb_node *eb;
293
294 eb = ebst_lookup(&cafile_tree, path);
295 if (eb) {
296 struct cafile_entry *ca_e;
297 ca_e = ebmb_entry(eb, struct cafile_entry, node);
298 return ca_e->ca_store;
299 }
300 return NULL;
301}
302
William Lallemanddad31052020-05-14 17:47:32 +0200303int ssl_store_load_locations_file(char *path)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200304{
305 if (ssl_store_get0_locations_file(path) == NULL) {
306 struct cafile_entry *ca_e;
307 X509_STORE *store = X509_STORE_new();
308 if (X509_STORE_load_locations(store, path, NULL)) {
309 int pathlen;
310 pathlen = strlen(path);
311 ca_e = calloc(1, sizeof(*ca_e) + pathlen + 1);
312 if (ca_e) {
313 memcpy(ca_e->path, path, pathlen + 1);
314 ca_e->ca_store = store;
315 ebst_insert(&cafile_tree, &ca_e->node);
316 return 1;
317 }
318 }
319 X509_STORE_free(store);
320 return 0;
321 }
322 return 1;
323}
324
325/* mimic what X509_STORE_load_locations do with store_ctx */
326static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
327{
328 X509_STORE *store;
329 store = ssl_store_get0_locations_file(path);
330 if (store_ctx && store) {
331 int i;
332 X509_OBJECT *obj;
333 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
334 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
335 obj = sk_X509_OBJECT_value(objs, i);
336 switch (X509_OBJECT_get_type(obj)) {
337 case X509_LU_X509:
338 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
339 break;
340 case X509_LU_CRL:
341 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
342 break;
343 default:
344 break;
345 }
346 }
347 return 1;
348 }
349 return 0;
350}
351
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500352/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200353static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
354{
355 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
356 return ssl_set_cert_crl_file(store_ctx, path);
357}
358
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200359/*
360 Extract CA_list from CA_file already in tree.
361 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
362 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
363*/
364static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
365{
366 struct ebmb_node *eb;
367 struct cafile_entry *ca_e;
368
369 eb = ebst_lookup(&cafile_tree, path);
370 if (!eb)
371 return NULL;
372 ca_e = ebmb_entry(eb, struct cafile_entry, node);
373
374 if (ca_e->ca_list == NULL) {
375 int i;
376 unsigned long key;
377 struct eb_root ca_name_tree = EB_ROOT;
378 struct eb64_node *node, *back;
379 struct {
380 struct eb64_node node;
381 X509_NAME *xname;
382 } *ca_name;
383 STACK_OF(X509_OBJECT) *objs;
384 STACK_OF(X509_NAME) *skn;
385 X509 *x;
386 X509_NAME *xn;
387
388 skn = sk_X509_NAME_new_null();
389 /* take x509 from cafile_tree */
390 objs = X509_STORE_get0_objects(ca_e->ca_store);
391 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
392 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
393 if (!x)
394 continue;
395 xn = X509_get_subject_name(x);
396 if (!xn)
397 continue;
398 /* Check for duplicates. */
399 key = X509_NAME_hash(xn);
400 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
401 node && ca_name == NULL;
402 node = eb64_next(node)) {
403 ca_name = container_of(node, typeof(*ca_name), node);
404 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
405 ca_name = NULL;
406 }
407 /* find a duplicate */
408 if (ca_name)
409 continue;
410 ca_name = calloc(1, sizeof *ca_name);
411 xn = X509_NAME_dup(xn);
412 if (!ca_name ||
413 !xn ||
414 !sk_X509_NAME_push(skn, xn)) {
415 free(ca_name);
416 X509_NAME_free(xn);
417 sk_X509_NAME_pop_free(skn, X509_NAME_free);
418 sk_X509_NAME_free(skn);
419 skn = NULL;
420 break;
421 }
422 ca_name->node.key = key;
423 ca_name->xname = xn;
424 eb64_insert(&ca_name_tree, &ca_name->node);
425 }
426 ca_e->ca_list = skn;
427 /* remove temporary ca_name tree */
428 node = eb64_first(&ca_name_tree);
429 while (node) {
430 ca_name = container_of(node, typeof(*ca_name), node);
431 back = eb64_next(node);
432 eb64_delete(node);
433 free(ca_name);
434 node = back;
435 }
436 }
437 return ca_e->ca_list;
438}
439
Willy Tarreaubafbe012017-11-24 17:34:44 +0100440struct pool_head *pool_head_ssl_capture = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200441int ssl_capture_ptr_index = -1;
Thierry FOURNIER28962c92018-06-17 21:37:05 +0200442static int ssl_app_data_index = -1;
Willy Tarreauef934602016-12-22 23:12:01 +0100443
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200444#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
445struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
446#endif
447
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200448#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200449unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000450struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
451struct ssl_engine_list {
452 struct list list;
453 ENGINE *e;
454};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200455#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000456
Remi Gacogne8de54152014-07-15 11:36:40 +0200457#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200458static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200459static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200460static DH *local_dh_1024 = NULL;
461static DH *local_dh_2048 = NULL;
462static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100463static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200464#endif /* OPENSSL_NO_DH */
465
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100466#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200467/* X509V3 Extensions that will be added on generated certificates */
468#define X509V3_EXT_SIZE 5
469static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
470 "basicConstraints",
471 "nsComment",
472 "subjectKeyIdentifier",
473 "authorityKeyIdentifier",
474 "keyUsage",
475};
476static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
477 "CA:FALSE",
478 "\"OpenSSL Generated Certificate\"",
479 "hash",
480 "keyid,issuer:always",
481 "nonRepudiation,digitalSignature,keyEncipherment"
482};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200483/* LRU cache to store generated certificate */
484static struct lru64_head *ssl_ctx_lru_tree = NULL;
485static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200486static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100487__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200488
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200489#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
490
Willy Tarreau9a1ab082019-05-09 13:26:41 +0200491#if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
yanbzhube2774d2015-12-10 15:07:30 -0500492/* The order here matters for picking a default context,
493 * keep the most common keytype at the bottom of the list
494 */
495const char *SSL_SOCK_KEYTYPE_NAMES[] = {
496 "dsa",
497 "ecdsa",
498 "rsa"
499};
yanbzhube2774d2015-12-10 15:07:30 -0500500#endif
501
William Lallemandc3cd35f2017-11-28 11:04:43 +0100502static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100503static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
504
Dragan Dosen9ac98092020-05-11 15:51:45 +0200505/* Dedicated callback functions for heartbeat and clienthello.
506 */
507#ifdef TLS1_RT_HEARTBEAT
508static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
509 int content_type, const void *buf, size_t len,
510 SSL *ssl);
511#endif
512static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
513 int content_type, const void *buf, size_t len,
514 SSL *ssl);
515
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200516/* List head of all registered SSL/TLS protocol message callbacks. */
517struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
518
519/* Registers the function <func> in order to be called on SSL/TLS protocol
520 * message processing. It will return 0 if the function <func> is not set
521 * or if it fails to allocate memory.
522 */
523int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
524{
525 struct ssl_sock_msg_callback *cbk;
526
527 if (!func)
528 return 0;
529
530 cbk = calloc(1, sizeof(*cbk));
531 if (!cbk) {
532 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
533 return 0;
534 }
535
536 cbk->func = func;
537
538 LIST_ADDQ(&ssl_sock_msg_callbacks, &cbk->list);
539
540 return 1;
541}
542
Dragan Dosen9ac98092020-05-11 15:51:45 +0200543/* Used to register dedicated SSL/TLS protocol message callbacks.
544 */
545static int ssl_sock_register_msg_callbacks(void)
546{
547#ifdef TLS1_RT_HEARTBEAT
548 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
549 return ERR_ABORT;
550#endif
551 if (global_ssl.capture_cipherlist > 0) {
552 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
553 return ERR_ABORT;
554 }
555 return 0;
556}
557
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200558/* Used to free all SSL/TLS protocol message callbacks that were
559 * registered by using ssl_sock_register_msg_callback().
560 */
561static void ssl_sock_unregister_msg_callbacks(void)
562{
563 struct ssl_sock_msg_callback *cbk, *cbkback;
564
565 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
566 LIST_DEL(&cbk->list);
567 free(cbk);
568 }
569}
570
Dragan Doseneb607fe2020-05-11 17:17:06 +0200571SSL *ssl_sock_get_ssl_object(struct connection *conn)
572{
573 if (!ssl_sock_is_ssl(conn))
574 return NULL;
575
576 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
577}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100578/*
579 * This function gives the detail of the SSL error. It is used only
580 * if the debug mode and the verbose mode are activated. It dump all
581 * the SSL error until the stack was empty.
582 */
583static forceinline void ssl_sock_dump_errors(struct connection *conn)
584{
585 unsigned long ret;
586
587 if (unlikely(global.mode & MODE_DEBUG)) {
588 while(1) {
589 ret = ERR_get_error();
590 if (ret == 0)
591 return;
592 fprintf(stderr, "fd[%04x] OpenSSL error[0x%lx] %s: %s\n",
Willy Tarreau585744b2017-08-24 14:31:19 +0200593 (unsigned short)conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100594 ERR_func_error_string(ret), ERR_reason_error_string(ret));
595 }
596 }
597}
598
yanbzhube2774d2015-12-10 15:07:30 -0500599
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200600#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200601int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000602{
603 int err_code = ERR_ABORT;
604 ENGINE *engine;
605 struct ssl_engine_list *el;
606
607 /* grab the structural reference to the engine */
608 engine = ENGINE_by_id(engine_id);
609 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100610 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000611 goto fail_get;
612 }
613
614 if (!ENGINE_init(engine)) {
615 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100616 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000617 goto fail_init;
618 }
619
620 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100621 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000622 goto fail_set_method;
623 }
624
625 el = calloc(1, sizeof(*el));
626 el->e = engine;
627 LIST_ADD(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100628 nb_engines++;
629 if (global_ssl.async)
630 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000631 return 0;
632
633fail_set_method:
634 /* release the functional reference from ENGINE_init() */
635 ENGINE_finish(engine);
636
637fail_init:
638 /* release the structural reference from ENGINE_by_id() */
639 ENGINE_free(engine);
640
641fail_get:
642 return err_code;
643}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200644#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000645
Willy Tarreau5db847a2019-05-09 14:13:35 +0200646#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +0200647/*
648 * openssl async fd handler
649 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200650void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000651{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200652 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000653
Emeric Brun3854e012017-05-17 20:42:48 +0200654 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000655 * to poll this fd until it is requested
656 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000657 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000658 fd_cant_recv(fd);
659
660 /* crypto engine is available, let's notify the associated
661 * connection that it can pursue its processing.
662 */
Olivier Houchard03abf2d2019-05-28 10:12:02 +0200663 ssl_sock_io_cb(NULL, ctx, 0);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000664}
665
Emeric Brun3854e012017-05-17 20:42:48 +0200666/*
667 * openssl async delayed SSL_free handler
668 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200669void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000670{
671 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200672 OSSL_ASYNC_FD all_fd[32];
673 size_t num_all_fds = 0;
674 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000675
Emeric Brun3854e012017-05-17 20:42:48 +0200676 /* We suppose that the async job for a same SSL *
677 * are serialized. So if we are awake it is
678 * because the running job has just finished
679 * and we can remove all async fds safely
680 */
681 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
682 if (num_all_fds > 32) {
683 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
684 return;
685 }
686
687 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
688 for (i=0 ; i < num_all_fds ; i++)
689 fd_remove(all_fd[i]);
690
691 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000692 SSL_free(ssl);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +0100693 _HA_ATOMIC_SUB(&sslconns, 1);
694 _HA_ATOMIC_SUB(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000695}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000696/*
Emeric Brun3854e012017-05-17 20:42:48 +0200697 * function used to manage a returned SSL_ERROR_WANT_ASYNC
698 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000699 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200700static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000701{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100702 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200703 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200704 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000705 size_t num_add_fds = 0;
706 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200707 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000708
709 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
710 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200711 if (num_add_fds > 32 || num_del_fds > 32) {
712 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 +0000713 return;
714 }
715
Emeric Brun3854e012017-05-17 20:42:48 +0200716 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000717
Emeric Brun3854e012017-05-17 20:42:48 +0200718 /* We remove unused fds from the fdtab */
719 for (i=0 ; i < num_del_fds ; i++)
720 fd_remove(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000721
Emeric Brun3854e012017-05-17 20:42:48 +0200722 /* We add new fds to the fdtab */
723 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200724 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000725 }
726
Emeric Brun3854e012017-05-17 20:42:48 +0200727 num_add_fds = 0;
728 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
729 if (num_add_fds > 32) {
730 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
731 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000732 }
Emeric Brun3854e012017-05-17 20:42:48 +0200733
734 /* We activate the polling for all known async fds */
735 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000736 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200737 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000738 /* To ensure that the fd cache won't be used
739 * We'll prefer to catch a real RD event
740 * because handling an EAGAIN on this fd will
741 * result in a context switch and also
742 * some engines uses a fd in blocking mode.
743 */
744 fd_cant_recv(add_fd[i]);
745 }
Emeric Brun3854e012017-05-17 20:42:48 +0200746
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000747}
748#endif
749
William Lallemand104a7a62019-10-14 14:14:59 +0200750#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200751/*
752 * This function returns the number of seconds elapsed
753 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
754 * date presented un ASN1_GENERALIZEDTIME.
755 *
756 * In parsing error case, it returns -1.
757 */
758static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
759{
760 long epoch;
761 char *p, *end;
762 const unsigned short month_offset[12] = {
763 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
764 };
765 int year, month;
766
767 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
768
769 p = (char *)d->data;
770 end = p + d->length;
771
772 if (end - p < 4) return -1;
773 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
774 p += 4;
775 if (end - p < 2) return -1;
776 month = 10 * (p[0] - '0') + p[1] - '0';
777 if (month < 1 || month > 12) return -1;
778 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
779 We consider leap years and the current month (<marsh or not) */
780 epoch = ( ((year - 1970) * 365)
781 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
782 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
783 + month_offset[month-1]
784 ) * 24 * 60 * 60;
785 p += 2;
786 if (end - p < 2) return -1;
787 /* Add the number of seconds of completed days of current month */
788 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
789 p += 2;
790 if (end - p < 2) return -1;
791 /* Add the completed hours of the current day */
792 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
793 p += 2;
794 if (end - p < 2) return -1;
795 /* Add the completed minutes of the current hour */
796 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
797 p += 2;
798 if (p == end) return -1;
799 /* Test if there is available seconds */
800 if (p[0] < '0' || p[0] > '9')
801 goto nosec;
802 if (end - p < 2) return -1;
803 /* Add the seconds of the current minute */
804 epoch += 10 * (p[0] - '0') + p[1] - '0';
805 p += 2;
806 if (p == end) return -1;
807 /* Ignore seconds float part if present */
808 if (p[0] == '.') {
809 do {
810 if (++p == end) return -1;
811 } while (p[0] >= '0' && p[0] <= '9');
812 }
813
814nosec:
815 if (p[0] == 'Z') {
816 if (end - p != 1) return -1;
817 return epoch;
818 }
819 else if (p[0] == '+') {
820 if (end - p != 5) return -1;
821 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700822 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 +0200823 }
824 else if (p[0] == '-') {
825 if (end - p != 5) return -1;
826 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700827 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 +0200828 }
829
830 return -1;
831}
832
William Lallemand104a7a62019-10-14 14:14:59 +0200833/*
834 * struct alignment works here such that the key.key is the same as key_data
835 * Do not change the placement of key_data
836 */
837struct certificate_ocsp {
838 struct ebmb_node key;
839 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
840 struct buffer response;
841 long expire;
842};
843
844struct ocsp_cbk_arg {
845 int is_single;
846 int single_kt;
847 union {
848 struct certificate_ocsp *s_ocsp;
849 /*
850 * m_ocsp will have multiple entries dependent on key type
851 * Entry 0 - DSA
852 * Entry 1 - ECDSA
853 * Entry 2 - RSA
854 */
855 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
856 };
857};
858
Emeric Brun1d3865b2014-06-20 15:37:32 +0200859static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200860
861/* This function starts to check if the OCSP response (in DER format) contained
862 * in chunk 'ocsp_response' is valid (else exits on error).
863 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
864 * contained in the OCSP Response and exits on error if no match.
865 * If it's a valid OCSP Response:
866 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
867 * pointed by 'ocsp'.
868 * If 'ocsp' is NULL, the function looks up into the OCSP response's
869 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
870 * from the response) and exits on error if not found. Finally, If an OCSP response is
871 * already present in the container, it will be overwritten.
872 *
873 * Note: OCSP response containing more than one OCSP Single response is not
874 * considered valid.
875 *
876 * Returns 0 on success, 1 in error case.
877 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200878static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
879 struct certificate_ocsp *ocsp,
880 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200881{
882 OCSP_RESPONSE *resp;
883 OCSP_BASICRESP *bs = NULL;
884 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200885 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200886 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200887 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200888 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200889 int reason;
890 int ret = 1;
891
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200892 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
893 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200894 if (!resp) {
895 memprintf(err, "Unable to parse OCSP response");
896 goto out;
897 }
898
899 rc = OCSP_response_status(resp);
900 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
901 memprintf(err, "OCSP response status not successful");
902 goto out;
903 }
904
905 bs = OCSP_response_get1_basic(resp);
906 if (!bs) {
907 memprintf(err, "Failed to get basic response from OCSP Response");
908 goto out;
909 }
910
911 count_sr = OCSP_resp_count(bs);
912 if (count_sr > 1) {
913 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
914 goto out;
915 }
916
917 sr = OCSP_resp_get0(bs, 0);
918 if (!sr) {
919 memprintf(err, "Failed to get OCSP single response");
920 goto out;
921 }
922
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200923 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
924
Emeric Brun4147b2e2014-06-16 18:36:30 +0200925 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200926 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200927 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200928 goto out;
929 }
930
Emeric Brun13a6b482014-06-20 15:44:34 +0200931 if (!nextupd) {
932 memprintf(err, "OCSP single response: missing nextupdate");
933 goto out;
934 }
935
Emeric Brunc8b27b62014-06-19 14:16:17 +0200936 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200937 if (!rc) {
938 memprintf(err, "OCSP single response: no longer valid.");
939 goto out;
940 }
941
942 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200943 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +0200944 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
945 goto out;
946 }
947 }
948
949 if (!ocsp) {
950 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
951 unsigned char *p;
952
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200953 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200954 if (!rc) {
955 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
956 goto out;
957 }
958
959 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
960 memprintf(err, "OCSP single response: Certificate ID too long");
961 goto out;
962 }
963
964 p = key;
965 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200966 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200967 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
968 if (!ocsp) {
969 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
970 goto out;
971 }
972 }
973
974 /* According to comments on "chunk_dup", the
975 previous chunk buffer will be freed */
976 if (!chunk_dup(&ocsp->response, ocsp_response)) {
977 memprintf(err, "OCSP response: Memory allocation error");
978 goto out;
979 }
980
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200981 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
982
Emeric Brun4147b2e2014-06-16 18:36:30 +0200983 ret = 0;
984out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +0100985 ERR_clear_error();
986
Emeric Brun4147b2e2014-06-16 18:36:30 +0200987 if (bs)
988 OCSP_BASICRESP_free(bs);
989
990 if (resp)
991 OCSP_RESPONSE_free(resp);
992
993 return ret;
994}
995/*
996 * External function use to update the OCSP response in the OCSP response's
997 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
998 * to update in DER format.
999 *
1000 * Returns 0 on success, 1 in error case.
1001 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001002int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001003{
1004 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1005}
1006
William Lallemand4a660132019-10-14 14:51:41 +02001007#endif
1008
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001009#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1010static 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)
1011{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001012 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001013 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001014 struct connection *conn;
1015 int head;
1016 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001017 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001018
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001019 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001020 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001021 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1022
1023 keys = ref->tlskeys;
1024 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001025
1026 if (enc) {
1027 memcpy(key_name, keys[head].name, 16);
1028
1029 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001030 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001031
Emeric Brun9e754772019-01-10 17:51:55 +01001032 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001033
Emeric Brun9e754772019-01-10 17:51:55 +01001034 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1035 goto end;
1036
Willy Tarreau9356dac2019-05-10 09:22:53 +02001037 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001038 ret = 1;
1039 }
1040 else if (ref->key_size_bits == 256 ) {
1041
1042 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1043 goto end;
1044
Willy Tarreau9356dac2019-05-10 09:22:53 +02001045 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001046 ret = 1;
1047 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001048 } else {
1049 for (i = 0; i < TLS_TICKETS_NO; i++) {
1050 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1051 goto found;
1052 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001053 ret = 0;
1054 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001055
Christopher Faulet16f45c82018-02-16 11:23:49 +01001056 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001057 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001058 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 +01001059 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1060 goto end;
1061 /* 2 for key renewal, 1 if current key is still valid */
1062 ret = i ? 2 : 1;
1063 }
1064 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001065 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 +01001066 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1067 goto end;
1068 /* 2 for key renewal, 1 if current key is still valid */
1069 ret = i ? 2 : 1;
1070 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001071 }
Emeric Brun9e754772019-01-10 17:51:55 +01001072
Christopher Faulet16f45c82018-02-16 11:23:49 +01001073 end:
1074 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1075 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001076}
1077
1078struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1079{
1080 struct tls_keys_ref *ref;
1081
1082 list_for_each_entry(ref, &tlskeys_reference, list)
1083 if (ref->filename && strcmp(filename, ref->filename) == 0)
1084 return ref;
1085 return NULL;
1086}
1087
1088struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1089{
1090 struct tls_keys_ref *ref;
1091
1092 list_for_each_entry(ref, &tlskeys_reference, list)
1093 if (ref->unique_id == unique_id)
1094 return ref;
1095 return NULL;
1096}
1097
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001098/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001099 * match existing ones, this function returns -1
1100 * else it returns 0 on success.
1101 */
1102int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001103 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001104{
Emeric Brun9e754772019-01-10 17:51:55 +01001105 if (ref->key_size_bits == 128) {
1106 if (tlskey->data != sizeof(struct tls_sess_key_128))
1107 return -1;
1108 }
1109 else if (ref->key_size_bits == 256) {
1110 if (tlskey->data != sizeof(struct tls_sess_key_256))
1111 return -1;
1112 }
1113 else
1114 return -1;
1115
Christopher Faulet16f45c82018-02-16 11:23:49 +01001116 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001117 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1118 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001119 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1120 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001121
1122 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001123}
1124
Willy Tarreau83061a82018-07-13 11:56:34 +02001125int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001126{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001127 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1128
1129 if(!ref) {
1130 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1131 return 1;
1132 }
Emeric Brun9e754772019-01-10 17:51:55 +01001133 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1134 memprintf(err, "Invalid key size");
1135 return 1;
1136 }
1137
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001138 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001139}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001140
1141/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001142 * automatic ids. It's called just after the basic checks. It returns
1143 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001144 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001145static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001146{
1147 int i = 0;
1148 struct tls_keys_ref *ref, *ref2, *ref3;
1149 struct list tkr = LIST_HEAD_INIT(tkr);
1150
1151 list_for_each_entry(ref, &tlskeys_reference, list) {
1152 if (ref->unique_id == -1) {
1153 /* Look for the first free id. */
1154 while (1) {
1155 list_for_each_entry(ref2, &tlskeys_reference, list) {
1156 if (ref2->unique_id == i) {
1157 i++;
1158 break;
1159 }
1160 }
1161 if (&ref2->list == &tlskeys_reference)
1162 break;
1163 }
1164
1165 /* Uses the unique id and increment it for the next entry. */
1166 ref->unique_id = i;
1167 i++;
1168 }
1169 }
1170
1171 /* This sort the reference list by id. */
1172 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
1173 LIST_DEL(&ref->list);
1174 list_for_each_entry(ref3, &tkr, list) {
1175 if (ref->unique_id < ref3->unique_id) {
1176 LIST_ADDQ(&ref3->list, &ref->list);
1177 break;
1178 }
1179 }
1180 if (&ref3->list == &tkr)
1181 LIST_ADDQ(&tkr, &ref->list);
1182 }
1183
1184 /* swap root */
1185 LIST_ADD(&tkr, &tlskeys_reference);
1186 LIST_DEL(&tkr);
Willy Tarreaud1c57502016-12-22 22:46:15 +01001187 return 0;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001188}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001189#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1190
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001191#ifndef OPENSSL_NO_OCSP
yanbzhube2774d2015-12-10 15:07:30 -05001192int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1193{
1194 switch (evp_keytype) {
1195 case EVP_PKEY_RSA:
1196 return 2;
1197 case EVP_PKEY_DSA:
1198 return 0;
1199 case EVP_PKEY_EC:
1200 return 1;
1201 }
1202
1203 return -1;
1204}
1205
Emeric Brun4147b2e2014-06-16 18:36:30 +02001206/*
1207 * Callback used to set OCSP status extension content in server hello.
1208 */
1209int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1210{
yanbzhube2774d2015-12-10 15:07:30 -05001211 struct certificate_ocsp *ocsp;
1212 struct ocsp_cbk_arg *ocsp_arg;
1213 char *ssl_buf;
1214 EVP_PKEY *ssl_pkey;
1215 int key_type;
1216 int index;
1217
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001218 ocsp_arg = arg;
yanbzhube2774d2015-12-10 15:07:30 -05001219
1220 ssl_pkey = SSL_get_privatekey(ssl);
1221 if (!ssl_pkey)
1222 return SSL_TLSEXT_ERR_NOACK;
1223
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001224 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001225
1226 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1227 ocsp = ocsp_arg->s_ocsp;
1228 else {
1229 /* For multiple certs per context, we have to find the correct OCSP response based on
1230 * the certificate type
1231 */
1232 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1233
1234 if (index < 0)
1235 return SSL_TLSEXT_ERR_NOACK;
1236
1237 ocsp = ocsp_arg->m_ocsp[index];
1238
1239 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001240
1241 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001242 !ocsp->response.area ||
1243 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001244 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001245 return SSL_TLSEXT_ERR_NOACK;
1246
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001247 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001248 if (!ssl_buf)
1249 return SSL_TLSEXT_ERR_NOACK;
1250
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001251 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1252 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001253
1254 return SSL_TLSEXT_ERR_OK;
1255}
1256
William Lallemand4a660132019-10-14 14:51:41 +02001257#endif
1258
1259#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001260/*
1261 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001262 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1263 * status extension, the issuer's certificate is mandatory. It should be
1264 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001265 *
William Lallemand246c0242019-10-11 08:59:13 +02001266 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1267 * OCSP response. If file is empty or content is not a valid OCSP response,
1268 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1269 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001270 *
1271 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001272 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001273 */
William Lallemand4a660132019-10-14 14:51:41 +02001274#ifndef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001275static 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 +02001276{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001277 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001278 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001279 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001280 struct certificate_ocsp *ocsp = NULL, *iocsp;
1281 char *warn = NULL;
1282 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001283 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001284
Emeric Brun4147b2e2014-06-16 18:36:30 +02001285
William Lallemand246c0242019-10-11 08:59:13 +02001286 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001287 if (!x)
1288 goto out;
1289
William Lallemand246c0242019-10-11 08:59:13 +02001290 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001291 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1292 if (chain) {
1293 /* check if one of the certificate of the chain is the issuer */
1294 for (i = 0; i < sk_X509_num(chain); i++) {
1295 X509 *ti = sk_X509_value(chain, i);
1296 if (X509_check_issued(ti, x) == X509_V_OK) {
1297 issuer = ti;
1298 break;
1299 }
1300 }
1301 }
William Lallemand246c0242019-10-11 08:59:13 +02001302 if (!issuer)
1303 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001304
1305 cid = OCSP_cert_to_id(0, x, issuer);
1306 if (!cid)
1307 goto out;
1308
1309 i = i2d_OCSP_CERTID(cid, NULL);
1310 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1311 goto out;
1312
Vincent Bernat02779b62016-04-03 13:48:43 +02001313 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001314 if (!ocsp)
1315 goto out;
1316
1317 p = ocsp->key_data;
1318 i2d_OCSP_CERTID(cid, &p);
1319
1320 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1321 if (iocsp == ocsp)
1322 ocsp = NULL;
1323
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001324#ifndef SSL_CTX_get_tlsext_status_cb
1325# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1326 *cb = (void (*) (void))ctx->tlsext_status_cb;
1327#endif
1328 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1329
1330 if (!callback) {
Vincent Bernat02779b62016-04-03 13:48:43 +02001331 struct ocsp_cbk_arg *cb_arg = calloc(1, sizeof(*cb_arg));
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001332 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001333
1334 cb_arg->is_single = 1;
1335 cb_arg->s_ocsp = iocsp;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001336
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001337 pkey = X509_get_pubkey(x);
1338 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1339 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001340
1341 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
1342 SSL_CTX_set_tlsext_status_arg(ctx, cb_arg);
1343 } else {
1344 /*
1345 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1346 * Update that cb_arg with the new cert's staple
1347 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001348 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001349 struct certificate_ocsp *tmp_ocsp;
1350 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001351 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001352 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001353
1354#ifdef SSL_CTX_get_tlsext_status_arg
1355 SSL_CTX_ctrl(ctx, SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG, 0, &cb_arg);
1356#else
1357 cb_arg = ctx->tlsext_status_arg;
1358#endif
yanbzhube2774d2015-12-10 15:07:30 -05001359
1360 /*
1361 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1362 * the order of operations below matter, take care when changing it
1363 */
1364 tmp_ocsp = cb_arg->s_ocsp;
1365 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1366 cb_arg->s_ocsp = NULL;
1367 cb_arg->m_ocsp[index] = tmp_ocsp;
1368 cb_arg->is_single = 0;
1369 cb_arg->single_kt = 0;
1370
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001371 pkey = X509_get_pubkey(x);
1372 key_type = EVP_PKEY_base_id(pkey);
1373 EVP_PKEY_free(pkey);
1374
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001375 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
yanbzhube2774d2015-12-10 15:07:30 -05001376 if (index >= 0 && !cb_arg->m_ocsp[index])
1377 cb_arg->m_ocsp[index] = iocsp;
1378
1379 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001380
1381 ret = 0;
1382
1383 warn = NULL;
William Lallemand246c0242019-10-11 08:59:13 +02001384 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, ocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001385 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001386 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001387 }
1388
1389out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001390 if (cid)
1391 OCSP_CERTID_free(cid);
1392
1393 if (ocsp)
1394 free(ocsp);
1395
1396 if (warn)
1397 free(warn);
1398
Emeric Brun4147b2e2014-06-16 18:36:30 +02001399 return ret;
1400}
William Lallemand4a660132019-10-14 14:51:41 +02001401#else /* OPENSSL_IS_BORINGSSL */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001402static 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 +02001403{
William Lallemand4a660132019-10-14 14:51:41 +02001404 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 +02001405}
1406#endif
1407
William Lallemand4a660132019-10-14 14:51:41 +02001408#endif
1409
1410
Willy Tarreau5db847a2019-05-09 14:13:35 +02001411#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001412
1413#define CT_EXTENSION_TYPE 18
1414
William Lallemand03c331c2020-05-13 10:10:01 +02001415int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001416
1417int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1418{
Willy Tarreau83061a82018-07-13 11:56:34 +02001419 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001420
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001421 *out = (unsigned char *) sctl->area;
1422 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001423
1424 return 1;
1425}
1426
1427int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1428{
1429 return 1;
1430}
1431
William Lallemanda17f4112019-10-10 15:16:44 +02001432static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001433{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001434 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001435
William Lallemanda17f4112019-10-10 15:16:44 +02001436 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 +01001437 goto out;
1438
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001439 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1440
1441 ret = 0;
1442
1443out:
1444 return ret;
1445}
1446
1447#endif
1448
Emeric Brune1f38db2012-09-03 20:36:47 +02001449void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1450{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001451 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001452 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001453 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001454 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001455
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001456#ifndef SSL_OP_NO_RENEGOTIATION
1457 /* Please note that BoringSSL defines this macro to zero so don't
1458 * change this to #if and do not assign a default value to this macro!
1459 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001460 if (where & SSL_CB_HANDSHAKE_START) {
1461 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001462 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 +02001463 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001464 conn->err_code = CO_ER_SSL_RENEG;
1465 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001466 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001467#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001468
1469 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001470 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001471 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001472 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001473 consider that the buffering was activated,
1474 so we rise the output buffer size from 4k
1475 to 16k */
1476 write_bio = SSL_get_wbio(ssl);
1477 if (write_bio != SSL_get_rbio(ssl)) {
1478 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001479 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001480 }
1481 }
1482 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001483}
1484
Emeric Brune64aef12012-09-21 13:15:06 +02001485/* Callback is called for each certificate of the chain during a verify
1486 ok is set to 1 if preverify detect no error on current certificate.
1487 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001488int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001489{
1490 SSL *ssl;
1491 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001492 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001493 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001494
1495 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001496 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001497
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001498 ctx = conn->xprt_ctx;
1499
1500 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001501
Emeric Brun81c00f02012-09-21 14:31:21 +02001502 if (ok) /* no errors */
1503 return ok;
1504
1505 depth = X509_STORE_CTX_get_error_depth(x_store);
1506 err = X509_STORE_CTX_get_error(x_store);
1507
1508 /* check if CA error needs to be ignored */
1509 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001510 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1511 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1512 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001513 }
1514
Willy Tarreau731248f2020-02-04 14:02:02 +01001515 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001516 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001517 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001518 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001519 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001520
Willy Tarreau20879a02012-12-03 16:32:10 +01001521 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001522 return 0;
1523 }
1524
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001525 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1526 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001527
Emeric Brun81c00f02012-09-21 14:31:21 +02001528 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001529 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001530 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001531 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001532 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001533 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001534
Willy Tarreau20879a02012-12-03 16:32:10 +01001535 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001536 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001537}
1538
Dragan Dosen9ac98092020-05-11 15:51:45 +02001539#ifdef TLS1_RT_HEARTBEAT
1540static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1541 int content_type, const void *buf, size_t len,
1542 SSL *ssl)
1543{
1544 /* test heartbeat received (write_p is set to 0
1545 for a received record) */
1546 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1547 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1548 const unsigned char *p = buf;
1549 unsigned int payload;
1550
1551 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1552
1553 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1554 if (*p != TLS1_HB_REQUEST)
1555 return;
1556
1557 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1558 goto kill_it;
1559
1560 payload = (p[1] * 256) + p[2];
1561 if (3 + payload + 16 <= len)
1562 return; /* OK no problem */
1563 kill_it:
1564 /* We have a clear heartbleed attack (CVE-2014-0160), the
1565 * advertised payload is larger than the advertised packet
1566 * length, so we have garbage in the buffer between the
1567 * payload and the end of the buffer (p+len). We can't know
1568 * if the SSL stack is patched, and we don't know if we can
1569 * safely wipe out the area between p+3+len and payload.
1570 * So instead, we prevent the response from being sent by
1571 * setting the max_send_fragment to 0 and we report an SSL
1572 * error, which will kill this connection. It will be reported
1573 * above as SSL_ERROR_SSL while an other handshake failure with
1574 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1575 */
1576 ssl->max_send_fragment = 0;
1577 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1578 }
1579}
1580#endif
1581
1582static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1583 int content_type, const void *buf, size_t len,
1584 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001585{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001586 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001587 unsigned char *msg;
1588 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001589 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001590
1591 /* This function is called for "from client" and "to server"
1592 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001593 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001594 */
1595
1596 /* "write_p" is set to 0 is the bytes are received messages,
1597 * otherwise it is set to 1.
1598 */
1599 if (write_p != 0)
1600 return;
1601
1602 /* content_type contains the type of message received or sent
1603 * according with the SSL/TLS protocol spec. This message is
1604 * encoded with one byte. The value 256 (two bytes) is used
1605 * for designing the SSL/TLS record layer. According with the
1606 * rfc6101, the expected message (other than 256) are:
1607 * - change_cipher_spec(20)
1608 * - alert(21)
1609 * - handshake(22)
1610 * - application_data(23)
1611 * - (255)
1612 * We are interessed by the handshake and specially the client
1613 * hello.
1614 */
1615 if (content_type != 22)
1616 return;
1617
1618 /* The message length is at least 4 bytes, containing the
1619 * message type and the message length.
1620 */
1621 if (len < 4)
1622 return;
1623
1624 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001625 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001626 * - hello_request(0)
1627 * - client_hello(1)
1628 * - server_hello(2)
1629 * - certificate(11)
1630 * - server_key_exchange (12)
1631 * - certificate_request(13)
1632 * - server_hello_done(14)
1633 * We are interested by the client hello.
1634 */
1635 msg = (unsigned char *)buf;
1636 if (msg[0] != 1)
1637 return;
1638
1639 /* Next three bytes are the length of the message. The total length
1640 * must be this decoded length + 4. If the length given as argument
1641 * is not the same, we abort the protocol dissector.
1642 */
1643 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1644 if (len < rec_len + 4)
1645 return;
1646 msg += 4;
1647 end = msg + rec_len;
1648 if (end < msg)
1649 return;
1650
1651 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1652 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001653 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1654 */
1655 msg += 1 + 1 + 4 + 28;
1656 if (msg > end)
1657 return;
1658
1659 /* Next, is session id:
1660 * if present, we have to jump by length + 1 for the size information
1661 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001662 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001663 if (msg[0] > 0)
1664 msg += msg[0];
1665 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001666 if (msg > end)
1667 return;
1668
1669 /* Next two bytes are the ciphersuite length. */
1670 if (msg + 2 > end)
1671 return;
1672 rec_len = (msg[0] << 8) + msg[1];
1673 msg += 2;
1674 if (msg + rec_len > end || msg + rec_len < msg)
1675 return;
1676
Willy Tarreaubafbe012017-11-24 17:34:44 +01001677 capture = pool_alloc_dirty(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001678 if (!capture)
1679 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001680 /* Compute the xxh64 of the ciphersuite. */
1681 capture->xxh64 = XXH64(msg, rec_len, 0);
1682
1683 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001684 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1685 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001686 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001687
1688 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001689}
1690
Emeric Brun29f037d2014-04-25 19:05:36 +02001691/* Callback is called for ssl protocol analyse */
1692void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1693{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001694 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1695 struct ssl_sock_msg_callback *cbk;
1696
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001697 /* Try to call all callback functions that were registered by using
1698 * ssl_sock_register_msg_callback().
1699 */
1700 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1701 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1702 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001703}
1704
Bernard Spil13c53f82018-02-15 13:34:58 +01001705#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001706static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1707 const unsigned char *in, unsigned int inlen,
1708 void *arg)
1709{
1710 struct server *srv = arg;
1711
1712 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1713 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1714 return SSL_TLSEXT_ERR_OK;
1715 return SSL_TLSEXT_ERR_NOACK;
1716}
1717#endif
1718
1719#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001720/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001721 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001722 */
1723static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1724 unsigned int *len, void *arg)
1725{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001726 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001727
1728 *data = (const unsigned char *)conf->npn_str;
1729 *len = conf->npn_len;
1730 return SSL_TLSEXT_ERR_OK;
1731}
1732#endif
1733
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001734#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001735/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001736 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001737 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001738static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1739 unsigned char *outlen,
1740 const unsigned char *server,
1741 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001742{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001743 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001744
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001745 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1746 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1747 return SSL_TLSEXT_ERR_NOACK;
1748 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001749 return SSL_TLSEXT_ERR_OK;
1750}
1751#endif
1752
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001753#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001754#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001755
Christopher Faulet30548802015-06-11 13:39:32 +02001756/* Create a X509 certificate with the specified servername and serial. This
1757 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001758static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001759ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001760{
Christopher Faulet7969a332015-10-09 11:15:03 +02001761 X509 *cacert = bind_conf->ca_sign_cert;
1762 EVP_PKEY *capkey = bind_conf->ca_sign_pkey;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001763 SSL_CTX *ssl_ctx = NULL;
1764 X509 *newcrt = NULL;
1765 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001766 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001767 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001768 X509_NAME *name;
1769 const EVP_MD *digest;
1770 X509V3_CTX ctx;
1771 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001772 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001773
Christopher Faulet48a83322017-07-28 16:56:09 +02001774 /* Get the private key of the default certificate and use it */
Willy Tarreau5db847a2019-05-09 14:13:35 +02001775#if (HA_OPENSSL_VERSION_NUMBER >= 0x10002000L)
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001776 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1777#else
1778 tmp_ssl = SSL_new(bind_conf->default_ctx);
1779 if (tmp_ssl)
1780 pkey = SSL_get_privatekey(tmp_ssl);
1781#endif
1782 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001783 goto mkcert_error;
1784
1785 /* Create the certificate */
1786 if (!(newcrt = X509_new()))
1787 goto mkcert_error;
1788
1789 /* Set version number for the certificate (X509v3) and the serial
1790 * number */
1791 if (X509_set_version(newcrt, 2L) != 1)
1792 goto mkcert_error;
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01001793 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001794
1795 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001796 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1797 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001798 goto mkcert_error;
1799
1800 /* set public key in the certificate */
1801 if (X509_set_pubkey(newcrt, pkey) != 1)
1802 goto mkcert_error;
1803
1804 /* Set issuer name from the CA */
1805 if (!(name = X509_get_subject_name(cacert)))
1806 goto mkcert_error;
1807 if (X509_set_issuer_name(newcrt, name) != 1)
1808 goto mkcert_error;
1809
1810 /* Set the subject name using the same, but the CN */
1811 name = X509_NAME_dup(name);
1812 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1813 (const unsigned char *)servername,
1814 -1, -1, 0) != 1) {
1815 X509_NAME_free(name);
1816 goto mkcert_error;
1817 }
1818 if (X509_set_subject_name(newcrt, name) != 1) {
1819 X509_NAME_free(name);
1820 goto mkcert_error;
1821 }
1822 X509_NAME_free(name);
1823
1824 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001825 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001826 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1827 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1828 X509_EXTENSION *ext;
1829
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001830 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001831 goto mkcert_error;
1832 if (!X509_add_ext(newcrt, ext, -1)) {
1833 X509_EXTENSION_free(ext);
1834 goto mkcert_error;
1835 }
1836 X509_EXTENSION_free(ext);
1837 }
1838
1839 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001840
1841 key_type = EVP_PKEY_base_id(capkey);
1842
1843 if (key_type == EVP_PKEY_DSA)
1844 digest = EVP_sha1();
1845 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001846 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001847 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001848 digest = EVP_sha256();
1849 else {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02001850#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000000fL) && !defined(OPENSSL_IS_BORINGSSL)
Christopher Faulet7969a332015-10-09 11:15:03 +02001851 int nid;
1852
1853 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1854 goto mkcert_error;
1855 if (!(digest = EVP_get_digestbynid(nid)))
1856 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02001857#else
1858 goto mkcert_error;
1859#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02001860 }
1861
Christopher Faulet31af49d2015-06-09 17:29:50 +02001862 if (!(X509_sign(newcrt, capkey, digest)))
1863 goto mkcert_error;
1864
1865 /* Create and set the new SSL_CTX */
1866 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
1867 goto mkcert_error;
1868 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1869 goto mkcert_error;
1870 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
1871 goto mkcert_error;
1872 if (!SSL_CTX_check_private_key(ssl_ctx))
1873 goto mkcert_error;
1874
1875 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02001876
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01001877#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001878 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01001879#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001880#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
1881 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001882 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001883 EC_KEY *ecc;
1884 int nid;
1885
1886 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
1887 goto end;
1888 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
1889 goto end;
1890 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
1891 EC_KEY_free(ecc);
1892 }
1893#endif
1894 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02001895 return ssl_ctx;
1896
1897 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001898 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001899 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001900 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
1901 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001902 return NULL;
1903}
1904
Christopher Faulet7969a332015-10-09 11:15:03 +02001905SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001906ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02001907{
Willy Tarreau07d94e42018-09-20 10:57:52 +02001908 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01001909 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001910
Olivier Houchard66ab4982019-02-26 18:37:15 +01001911 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02001912}
1913
Christopher Faulet30548802015-06-11 13:39:32 +02001914/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02001915 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02001916SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02001917ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02001918{
1919 struct lru64 *lru = NULL;
1920
1921 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001922 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001923 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02001924 if (lru && lru->domain) {
1925 if (ssl)
1926 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001927 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02001928 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02001929 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001930 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02001931 }
1932 return NULL;
1933}
1934
Emeric Brun821bb9b2017-06-15 16:37:39 +02001935/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
1936 * function is not thread-safe, it should only be used to check if a certificate
1937 * exists in the lru cache (with no warranty it will not be removed by another
1938 * thread). It is kept for backward compatibility. */
1939SSL_CTX *
1940ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
1941{
1942 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
1943}
1944
Christopher Fauletd2cab922015-07-28 16:03:47 +02001945/* Set a certificate int the LRU cache used to store generated
1946 * certificate. Return 0 on success, otherwise -1 */
1947int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001948ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02001949{
1950 struct lru64 *lru = NULL;
1951
1952 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001953 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001954 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02001955 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001956 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001957 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02001958 }
Christopher Faulet30548802015-06-11 13:39:32 +02001959 if (lru->domain && lru->data)
1960 lru->free((SSL_CTX *)lru->data);
Christopher Faulet7969a332015-10-09 11:15:03 +02001961 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001962 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001963 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02001964 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02001965 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02001966}
1967
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001968/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02001969unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001970ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02001971{
1972 return XXH32(data, len, ssl_ctx_lru_seed);
1973}
1974
Willy Tarreau2f63ef42015-10-20 15:16:01 +02001975/* Generate a cert and immediately assign it to the SSL session so that the cert's
1976 * refcount is maintained regardless of the cert's presence in the LRU cache.
1977 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02001978static int
Christopher Faulet7969a332015-10-09 11:15:03 +02001979ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001980{
1981 X509 *cacert = bind_conf->ca_sign_cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001982 SSL_CTX *ssl_ctx = NULL;
1983 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001984 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001985
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001986 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001987 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001988 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001989 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001990 if (lru && lru->domain)
1991 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02001992 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001993 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001994 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001995 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02001996 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001997 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02001998 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001999 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002000 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002001 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002002 SSL_set_SSL_CTX(ssl, ssl_ctx);
2003 /* No LRU cache, this CTX will be released as soon as the session dies */
2004 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002005 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002006 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002007 return 0;
2008}
2009static int
2010ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2011{
2012 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002013 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002014
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002015 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002016 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002017 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002018 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002019 }
2020 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002021}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002022#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002023
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002024#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002025
2026static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002027{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002028#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002029 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002030 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2031#endif
2032}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002033static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2034 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002035 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2036}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002037static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002038#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002039 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002040 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2041#endif
2042}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002043static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002044#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002045 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002046 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2047#endif
2048}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002049/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002050static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2051/* Unusable in this context. */
2052static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2053static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2054static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2055static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2056static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002057#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002058
2059static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2060 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002061 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2062}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002063static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2064 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2065 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2066}
2067static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2068 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002069 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2070}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002071static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2072 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2073 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2074}
2075static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2076 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002077 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2078}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002079static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2080 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2081 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2082}
2083static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2084 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002085 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2086}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002087static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2088 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2089 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2090}
2091static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002092#if SSL_OP_NO_TLSv1_3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002093 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002094 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2095#endif
2096}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002097static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
2098#if SSL_OP_NO_TLSv1_3
2099 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2100 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002101#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002102}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002103#endif
2104static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2105static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002106
William Lallemand7fd8b452020-05-07 15:20:43 +02002107struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002108 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2109 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2110 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2111 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2112 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2113 {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 +02002114};
2115
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002116static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2117{
2118 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2119 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2120 SSL_set_SSL_CTX(ssl, ctx);
2121}
2122
Willy Tarreau5db847a2019-05-09 14:13:35 +02002123#if ((HA_OPENSSL_VERSION_NUMBER >= 0x10101000L) || defined(OPENSSL_IS_BORINGSSL))
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002124
2125static int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
2126{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002127 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002128 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002129
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002130 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2131 return SSL_TLSEXT_ERR_OK;
2132 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002133}
2134
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002135#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002136static int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
2137{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002138 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002139#else
2140static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
2141{
2142#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002143 struct connection *conn;
2144 struct bind_conf *s;
2145 const uint8_t *extension_data;
2146 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002147 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002148
2149 char *wildp = NULL;
2150 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002151 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002152 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002153 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002154 int i;
2155
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002156 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002157 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002158
Olivier Houchard9679ac92017-10-27 14:58:08 +02002159 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002160 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002161#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002162 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2163 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002164#else
2165 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2166#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002167 /*
2168 * The server_name extension was given too much extensibility when it
2169 * was written, so parsing the normal case is a bit complex.
2170 */
2171 size_t len;
2172 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002173 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002174 /* Extract the length of the supplied list of names. */
2175 len = (*extension_data++) << 8;
2176 len |= *extension_data++;
2177 if (len + 2 != extension_len)
2178 goto abort;
2179 /*
2180 * The list in practice only has a single element, so we only consider
2181 * the first one.
2182 */
2183 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2184 goto abort;
2185 extension_len = len - 1;
2186 /* Now we can finally pull out the byte array with the actual hostname. */
2187 if (extension_len <= 2)
2188 goto abort;
2189 len = (*extension_data++) << 8;
2190 len |= *extension_data++;
2191 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2192 || memchr(extension_data, 0, len) != NULL)
2193 goto abort;
2194 servername = extension_data;
2195 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002196 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002197#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2198 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002199 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002200 }
2201#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002202 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002203 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002204 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002205 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002206 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002207 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002208 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002209 goto abort;
2210 }
2211
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002212 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002213#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002214 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002215#else
2216 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2217#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002218 uint8_t sign;
2219 size_t len;
2220 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002221 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002222 len = (*extension_data++) << 8;
2223 len |= *extension_data++;
2224 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002225 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002226 if (len % 2 != 0)
2227 goto abort;
2228 for (; len > 0; len -= 2) {
2229 extension_data++; /* hash */
2230 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002231 switch (sign) {
2232 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002233 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002234 break;
2235 case TLSEXT_signature_ecdsa:
2236 has_ecdsa_sig = 1;
2237 break;
2238 default:
2239 continue;
2240 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002241 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002242 break;
2243 }
2244 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002245 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002246 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002247 }
2248 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002249 const SSL_CIPHER *cipher;
2250 size_t len;
2251 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002252 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002253#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002254 len = ctx->cipher_suites_len;
2255 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002256#else
2257 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2258#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002259 if (len % 2 != 0)
2260 goto abort;
2261 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002262#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002263 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002264 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002265#else
2266 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2267#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002268 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002269 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002270 break;
2271 }
2272 }
2273 }
2274
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002275 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002276 trash.area[i] = tolower(servername[i]);
2277 if (!wildp && (trash.area[i] == '.'))
2278 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002279 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002280 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002281
William Lallemand150bfa82019-09-19 17:12:49 +02002282 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002283
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002284 for (i = 0; i < 2; i++) {
2285 if (i == 0) /* lookup in full qualified names */
2286 node = ebst_lookup(&s->sni_ctx, trash.area);
2287 else if (i == 1 && wildp) /* lookup in wildcards names */
2288 node = ebst_lookup(&s->sni_w_ctx, wildp);
2289 else
2290 break;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002291 for (n = node; n; n = ebmb_next_dup(n)) {
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002292 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002293 if (!container_of(n, struct sni_ctx, name)->neg) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002294 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002295 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002296 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002297 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002298 break;
2299 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002300 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002301 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002302 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002303 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002304 if (!node_anonymous)
2305 node_anonymous = n;
2306 break;
2307 }
2308 }
2309 }
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002310 /* select by key_signature priority order */
2311 node = (has_ecdsa_sig && node_ecdsa) ? node_ecdsa
2312 : ((has_rsa_sig && node_rsa) ? node_rsa
2313 : (node_anonymous ? node_anonymous
2314 : (node_ecdsa ? node_ecdsa /* no ecdsa signature case (< TLSv1.2) */
2315 : node_rsa /* no rsa signature case (far far away) */
2316 )));
2317 if (node) {
2318 /* switch ctx */
2319 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2320 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
Olivier Houchard35a63cc2017-11-02 19:04:38 +01002321 if (conf) {
2322 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2323 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2324 if (conf->early_data)
2325 allow_early = 1;
2326 }
William Lallemand02010472019-10-18 11:02:19 +02002327 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchard35a63cc2017-11-02 19:04:38 +01002328 goto allow_early;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002329 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002330 }
William Lallemand150bfa82019-09-19 17:12:49 +02002331
William Lallemand02010472019-10-18 11:02:19 +02002332 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002333#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002334 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002335 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002336 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002337 }
2338#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002339 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002340 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002341 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002342 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002343 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002344 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02002345allow_early:
2346#ifdef OPENSSL_IS_BORINGSSL
2347 if (allow_early)
2348 SSL_set_early_data_enabled(ssl, 1);
2349#else
2350 if (!allow_early)
2351 SSL_set_max_early_data(ssl, 0);
2352#endif
2353 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002354 abort:
2355 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2356 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002357#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002358 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002359#else
2360 *al = SSL_AD_UNRECOGNIZED_NAME;
2361 return 0;
2362#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002363}
2364
2365#else /* OPENSSL_IS_BORINGSSL */
2366
Emeric Brunfc0421f2012-09-07 17:30:07 +02002367/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2368 * warning when no match is found, which implies the default (first) cert
2369 * will keep being used.
2370 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002371static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002372{
2373 const char *servername;
2374 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002375 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002376 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002377 int i;
2378 (void)al; /* shut gcc stupid warning */
2379
2380 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002381 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002382#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002383 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2384 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002385#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002386 if (s->strict_sni)
2387 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002388 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002389 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002390 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002391 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002392 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002393
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002394 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002395 if (!servername[i])
2396 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002397 trash.area[i] = tolower(servername[i]);
2398 if (!wildp && (trash.area[i] == '.'))
2399 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002400 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002401 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002402
William Lallemand150bfa82019-09-19 17:12:49 +02002403 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002404 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002405 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002406 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2407 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002408 if (!container_of(n, struct sni_ctx, name)->neg) {
2409 node = n;
2410 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002411 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002412 }
2413 if (!node && wildp) {
2414 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002415 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2416 /* lookup a not neg filter */
2417 if (!container_of(n, struct sni_ctx, name)->neg) {
2418 node = n;
2419 break;
2420 }
2421 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002422 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002423 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002424#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002425 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2426 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002427 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002428 return SSL_TLSEXT_ERR_OK;
2429 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002430#endif
William Lallemand21724f02019-11-04 17:56:13 +01002431 if (s->strict_sni) {
2432 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002433 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002434 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002435 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002436 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002437 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002438 }
2439
2440 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002441 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002442 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002443 return SSL_TLSEXT_ERR_OK;
2444}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002445#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002446#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2447
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002448#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002449
2450static DH * ssl_get_dh_1024(void)
2451{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002452 static unsigned char dh1024_p[]={
2453 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2454 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2455 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2456 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2457 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2458 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2459 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2460 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2461 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2462 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2463 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2464 };
2465 static unsigned char dh1024_g[]={
2466 0x02,
2467 };
2468
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002469 BIGNUM *p;
2470 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002471 DH *dh = DH_new();
2472 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002473 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2474 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002475
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002476 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002477 DH_free(dh);
2478 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002479 } else {
2480 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002481 }
2482 }
2483 return dh;
2484}
2485
2486static DH *ssl_get_dh_2048(void)
2487{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002488 static unsigned char dh2048_p[]={
2489 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2490 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2491 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2492 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2493 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2494 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2495 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2496 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2497 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2498 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2499 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2500 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2501 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2502 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2503 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2504 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2505 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2506 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2507 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2508 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2509 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2510 0xB7,0x1F,0x77,0xF3,
2511 };
2512 static unsigned char dh2048_g[]={
2513 0x02,
2514 };
2515
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002516 BIGNUM *p;
2517 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002518 DH *dh = DH_new();
2519 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002520 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2521 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002522
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002523 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002524 DH_free(dh);
2525 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002526 } else {
2527 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002528 }
2529 }
2530 return dh;
2531}
2532
2533static DH *ssl_get_dh_4096(void)
2534{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002535 static unsigned char dh4096_p[]={
2536 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2537 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2538 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2539 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2540 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2541 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2542 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2543 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2544 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2545 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2546 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2547 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2548 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2549 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2550 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2551 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2552 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2553 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2554 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2555 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2556 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2557 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2558 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2559 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2560 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2561 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2562 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2563 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2564 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2565 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2566 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2567 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2568 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2569 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2570 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2571 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2572 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2573 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2574 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2575 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2576 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2577 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2578 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002579 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002580 static unsigned char dh4096_g[]={
2581 0x02,
2582 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002583
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002584 BIGNUM *p;
2585 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002586 DH *dh = DH_new();
2587 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002588 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2589 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002590
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002591 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002592 DH_free(dh);
2593 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002594 } else {
2595 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002596 }
2597 }
2598 return dh;
2599}
2600
2601/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002602 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002603static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2604{
2605 DH *dh = NULL;
2606 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002607 int type;
2608
2609 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002610
2611 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2612 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2613 */
2614 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2615 keylen = EVP_PKEY_bits(pkey);
2616 }
2617
Willy Tarreauef934602016-12-22 23:12:01 +01002618 if (keylen > global_ssl.default_dh_param) {
2619 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002620 }
2621
Remi Gacogned3a341a2015-05-29 16:26:17 +02002622 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002623 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002624 }
2625 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002626 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002627 }
2628 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002629 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002630 }
2631
2632 return dh;
2633}
2634
Remi Gacogne47783ef2015-05-29 15:53:22 +02002635static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002636{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002637 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002638 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002639
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002640 if (in == NULL)
2641 goto end;
2642
Remi Gacogne47783ef2015-05-29 15:53:22 +02002643 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002644 goto end;
2645
Remi Gacogne47783ef2015-05-29 15:53:22 +02002646 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2647
2648end:
2649 if (in)
2650 BIO_free(in);
2651
Emeric Brune1b4ed42018-08-16 15:14:12 +02002652 ERR_clear_error();
2653
Remi Gacogne47783ef2015-05-29 15:53:22 +02002654 return dh;
2655}
2656
2657int ssl_sock_load_global_dh_param_from_file(const char *filename)
2658{
2659 global_dh = ssl_sock_get_dh_from_file(filename);
2660
2661 if (global_dh) {
2662 return 0;
2663 }
2664
2665 return -1;
2666}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002667#endif
2668
William Lallemand9117de92019-10-04 00:29:42 +02002669/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002670static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002671 struct bind_conf *s, struct ssl_bind_conf *conf,
2672 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002673{
2674 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002675 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002676
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002677 if (*name == '!') {
2678 neg = 1;
2679 name++;
2680 }
2681 if (*name == '*') {
2682 wild = 1;
2683 name++;
2684 }
2685 /* !* filter is a nop */
2686 if (neg && wild)
2687 return order;
2688 if (*name) {
2689 int j, len;
2690 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002691 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002692 trash.area[j] = tolower(name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002693 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002694 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002695 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002696
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002697 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002698 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002699 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002700 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002701 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002702 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002703 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002704 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002705 sc->order = order++;
2706 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002707 sc->wild = wild;
2708 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002709 sc->ckch_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02002710 LIST_ADDQ(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002711 }
2712 return order;
2713}
2714
William Lallemand6af03992019-07-23 15:00:54 +02002715/*
William Lallemand1d29c742019-10-04 00:53:29 +02002716 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2717 * This function can't return an error.
2718 *
2719 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2720 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002721void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002722{
2723
2724 struct sni_ctx *sc0, *sc0b, *sc1;
2725 struct ebmb_node *node;
William Lallemand21724f02019-11-04 17:56:13 +01002726 int def = 0;
William Lallemand1d29c742019-10-04 00:53:29 +02002727
2728 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2729
2730 /* ignore if sc0 was already inserted in a tree */
2731 if (sc0->name.node.leaf_p)
2732 continue;
2733
2734 /* Check for duplicates. */
2735 if (sc0->wild)
2736 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2737 else
2738 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2739
2740 for (; node; node = ebmb_next_dup(node)) {
2741 sc1 = ebmb_entry(node, struct sni_ctx, name);
2742 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2743 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2744 /* it's a duplicate, we should remove and free it */
2745 LIST_DEL(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002746 SSL_CTX_free(sc0->ctx);
William Lallemand1d29c742019-10-04 00:53:29 +02002747 free(sc0);
2748 sc0 = NULL;
William Lallemande15029b2019-10-14 10:46:58 +02002749 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002750 }
2751 }
2752
2753 /* if duplicate, ignore the insertion */
2754 if (!sc0)
2755 continue;
2756
2757 if (sc0->wild)
2758 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
2759 else
2760 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
William Lallemand21724f02019-11-04 17:56:13 +01002761
2762 /* replace the default_ctx if required with the first ctx */
2763 if (ckch_inst->is_default && !def) {
William Lallemand02e19a52020-04-08 16:11:26 +02002764 SSL_CTX_free(bind_conf->default_ctx);
2765 SSL_CTX_up_ref(sc0->ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002766 bind_conf->default_ctx = sc0->ctx;
2767 def = 1;
2768 }
William Lallemand1d29c742019-10-04 00:53:29 +02002769 }
2770}
2771
2772/*
William Lallemande3af8fb2019-10-08 11:36:53 +02002773 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02002774 */
William Lallemande3af8fb2019-10-08 11:36:53 +02002775struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02002776
William Lallemand2954c472020-03-06 21:54:13 +01002777/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02002778struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02002779
Emeric Brun7a883362019-10-17 13:27:40 +02002780/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002781 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02002782 * DH parameter is loaded into the SSL_CTX and if there is no
2783 * DH parameter available in ckchs nor in global, the default
2784 * DH parameters are applied on the SSL_CTX.
2785 * Returns a bitfield containing the flags:
2786 * ERR_FATAL in any fatal error case
2787 * ERR_ALERT if a reason of the error is availabine in err
2788 * ERR_WARN if a warning is available into err
2789 * The value 0 means there is no error nor warning and
2790 * the operation succeed.
2791 */
William Lallemandfa892222019-07-23 16:06:08 +02002792#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02002793static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
2794 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02002795{
Emeric Brun7a883362019-10-17 13:27:40 +02002796 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02002797 DH *dh = NULL;
2798
William Lallemanda8c73742019-07-31 18:31:34 +02002799 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02002800 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02002801 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
2802 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
2803 err && *err ? *err : "", path);
2804#if defined(SSL_CTX_set_dh_auto)
2805 SSL_CTX_set_dh_auto(ctx, 1);
2806 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2807 err && *err ? *err : "");
2808#else
2809 memprintf(err, "%s, DH ciphers won't be available.\n",
2810 err && *err ? *err : "");
2811#endif
2812 ret |= ERR_WARN;
2813 goto end;
2814 }
William Lallemandfa892222019-07-23 16:06:08 +02002815
2816 if (ssl_dh_ptr_index >= 0) {
2817 /* store a pointer to the DH params to avoid complaining about
2818 ssl-default-dh-param not being set for this SSL_CTX */
2819 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
2820 }
2821 }
2822 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02002823 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
2824 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
2825 err && *err ? *err : "", path);
2826#if defined(SSL_CTX_set_dh_auto)
2827 SSL_CTX_set_dh_auto(ctx, 1);
2828 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2829 err && *err ? *err : "");
2830#else
2831 memprintf(err, "%s, DH ciphers won't be available.\n",
2832 err && *err ? *err : "");
2833#endif
2834 ret |= ERR_WARN;
2835 goto end;
2836 }
William Lallemandfa892222019-07-23 16:06:08 +02002837 }
2838 else {
2839 /* Clear openssl global errors stack */
2840 ERR_clear_error();
2841
2842 if (global_ssl.default_dh_param <= 1024) {
2843 /* we are limited to DH parameter of 1024 bits anyway */
2844 if (local_dh_1024 == NULL)
2845 local_dh_1024 = ssl_get_dh_1024();
2846
Emeric Brun7a883362019-10-17 13:27:40 +02002847 if (local_dh_1024 == NULL) {
2848 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
2849 err && *err ? *err : "", path);
2850 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02002851 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02002852 }
William Lallemandfa892222019-07-23 16:06:08 +02002853
Emeric Bruna9363eb2019-10-17 14:53:03 +02002854 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
2855 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
2856 err && *err ? *err : "", path);
2857#if defined(SSL_CTX_set_dh_auto)
2858 SSL_CTX_set_dh_auto(ctx, 1);
2859 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2860 err && *err ? *err : "");
2861#else
2862 memprintf(err, "%s, DH ciphers won't be available.\n",
2863 err && *err ? *err : "");
2864#endif
2865 ret |= ERR_WARN;
2866 goto end;
2867 }
William Lallemandfa892222019-07-23 16:06:08 +02002868 }
2869 else {
2870 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
2871 }
William Lallemand8d0f8932019-10-17 18:03:58 +02002872 }
2873
William Lallemandf9568fc2019-10-16 18:27:58 +02002874end:
William Lallemandf9568fc2019-10-16 18:27:58 +02002875 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02002876 return ret;
2877}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02002878#endif
William Lallemandfa892222019-07-23 16:06:08 +02002879
yanbzhu488a4d22015-12-01 15:16:07 -05002880/* Loads the info in ckch into ctx
Emeric Bruna96b5822019-10-17 13:25:14 +02002881 * Returns a bitfield containing the flags:
2882 * ERR_FATAL in any fatal error case
2883 * ERR_ALERT if the reason of the error is available in err
2884 * ERR_WARN if a warning is available into err
2885 * The value 0 means there is no error nor warning and
2886 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05002887 */
2888static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
2889{
Emeric Bruna96b5822019-10-17 13:25:14 +02002890 int errcode = 0;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002891 STACK_OF(X509) *find_chain = NULL;
Emeric Bruna96b5822019-10-17 13:25:14 +02002892
yanbzhu488a4d22015-12-01 15:16:07 -05002893 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
2894 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
2895 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002896 errcode |= ERR_ALERT | ERR_FATAL;
2897 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05002898 }
2899
2900 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
2901 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
2902 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002903 errcode |= ERR_ALERT | ERR_FATAL;
2904 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05002905 }
2906
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002907 if (ckch->chain) {
2908 find_chain = ckch->chain;
2909 } else {
2910 /* Find Certificate Chain in global */
2911 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01002912 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002913 if (issuer)
2914 find_chain = issuer->chain;
2915 }
William Lallemand85888572020-02-27 14:48:35 +01002916
William Lallemandf187ce62020-06-02 18:27:20 +02002917 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
2918 if (find_chain)
2919#ifdef SSL_CTX_set1_chain
2920 if (!SSL_CTX_set1_chain(ctx, find_chain)) {
2921 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
2922 err && *err ? *err : "", path);
2923 errcode |= ERR_ALERT | ERR_FATAL;
2924 goto end;
2925 }
2926#else
2927 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002928 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02002929 STACK_OF(X509) *chain;
2930 chain = X509_chain_up_ref(find_chain);
2931 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002932 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002933 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
2934 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02002935 X509_free(ca);
2936 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002937 errcode |= ERR_ALERT | ERR_FATAL;
2938 goto end;
2939 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002940 }
William Lallemandf187ce62020-06-02 18:27:20 +02002941#endif
yanbzhu488a4d22015-12-01 15:16:07 -05002942
William Lallemandfa892222019-07-23 16:06:08 +02002943#ifndef OPENSSL_NO_DH
2944 /* store a NULL pointer to indicate we have not yet loaded
2945 a custom DH param file */
2946 if (ssl_dh_ptr_index >= 0) {
2947 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
2948 }
2949
Emeric Brun7a883362019-10-17 13:27:40 +02002950 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
2951 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02002952 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
2953 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002954 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02002955 }
2956#endif
2957
William Lallemanda17f4112019-10-10 15:16:44 +02002958#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
2959 if (sctl_ex_index >= 0 && ckch->sctl) {
2960 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
2961 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01002962 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002963 errcode |= ERR_ALERT | ERR_FATAL;
2964 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02002965 }
2966 }
2967#endif
2968
William Lallemand4a660132019-10-14 14:51:41 +02002969#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02002970 /* Load OCSP Info into context */
2971 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01002972 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01002973 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",
2974 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002975 errcode |= ERR_ALERT | ERR_FATAL;
2976 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02002977 }
2978 }
William Lallemand246c0242019-10-11 08:59:13 +02002979#endif
2980
Emeric Bruna96b5822019-10-17 13:25:14 +02002981 end:
2982 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05002983}
2984
William Lallemandc4ecddf2019-07-31 16:50:08 +02002985#if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
yanbzhu08ce6ab2015-12-02 13:01:29 -05002986
William Lallemand28a8fce2019-10-04 17:36:55 +02002987static int ssl_sock_populate_sni_keytypes_hplr(const char *str, struct eb_root *sni_keytypes, int key_index)
yanbzhu08ce6ab2015-12-02 13:01:29 -05002988{
2989 struct sni_keytype *s_kt = NULL;
2990 struct ebmb_node *node;
2991 int i;
2992
2993 for (i = 0; i < trash.size; i++) {
2994 if (!str[i])
2995 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002996 trash.area[i] = tolower(str[i]);
yanbzhu08ce6ab2015-12-02 13:01:29 -05002997 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002998 trash.area[i] = 0;
2999 node = ebst_lookup(sni_keytypes, trash.area);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003000 if (!node) {
3001 /* CN not found in tree */
3002 s_kt = malloc(sizeof(struct sni_keytype) + i + 1);
3003 /* Using memcpy here instead of strncpy.
3004 * strncpy will cause sig_abrt errors under certain versions of gcc with -O2
3005 * See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60792
3006 */
William Lallemand28a8fce2019-10-04 17:36:55 +02003007 if (!s_kt)
3008 return -1;
3009
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003010 memcpy(s_kt->name.key, trash.area, i+1);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003011 s_kt->keytypes = 0;
3012 ebst_insert(sni_keytypes, &s_kt->name);
3013 } else {
3014 /* CN found in tree */
3015 s_kt = container_of(node, struct sni_keytype, name);
3016 }
3017
3018 /* Mark that this CN has the keytype of key_index via keytypes mask */
3019 s_kt->keytypes |= 1<<key_index;
3020
William Lallemand28a8fce2019-10-04 17:36:55 +02003021 return 0;
3022
William Lallemand6af03992019-07-23 15:00:54 +02003023}
3024
William Lallemandc4ecddf2019-07-31 16:50:08 +02003025#endif
William Lallemand36b84632019-07-18 19:28:17 +02003026
William Lallemandc4ecddf2019-07-31 16:50:08 +02003027#if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
3028
William Lallemand36b84632019-07-18 19:28:17 +02003029/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003030 * Take a ckch_store which contains a multi-certificate bundle.
William Lallemand36b84632019-07-18 19:28:17 +02003031 * Group these certificates into a set of SSL_CTX*
yanbzhu08ce6ab2015-12-02 13:01:29 -05003032 * based on shared and unique CN and SAN entries. Add these SSL_CTX* to the SNI tree.
3033 *
Joseph Herlant017b3da2018-11-15 09:07:59 -08003034 * This will allow the user to explicitly group multiple cert/keys for a single purpose
yanbzhu08ce6ab2015-12-02 13:01:29 -05003035 *
Emeric Brun054563d2019-10-17 13:16:58 +02003036 * Returns a bitfield containing the flags:
3037 * ERR_FATAL in any fatal error case
3038 * ERR_ALERT if the reason of the error is available in err
3039 * ERR_WARN if a warning is available into err
William Lallemand36b84632019-07-18 19:28:17 +02003040 *
yanbzhu08ce6ab2015-12-02 13:01:29 -05003041 */
William Lallemandda8584c2020-05-14 10:14:37 +02003042int ckch_inst_new_load_multi_store(const char *path, struct ckch_store *ckchs,
3043 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
3044 char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
yanbzhu08ce6ab2015-12-02 13:01:29 -05003045{
William Lallemand36b84632019-07-18 19:28:17 +02003046 int i = 0, n = 0;
3047 struct cert_key_and_chain *certs_and_keys;
William Lallemand4b989f22019-10-04 18:36:55 +02003048 struct eb_root sni_keytypes_map = EB_ROOT;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003049 struct ebmb_node *node;
3050 struct ebmb_node *next;
3051 /* Array of SSL_CTX pointers corresponding to each possible combo
3052 * of keytypes
3053 */
3054 struct key_combo_ctx key_combos[SSL_SOCK_POSSIBLE_KT_COMBOS] = { {0} };
Emeric Brun054563d2019-10-17 13:16:58 +02003055 int errcode = 0;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003056 X509_NAME *xname = NULL;
3057 char *str = NULL;
3058#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3059 STACK_OF(GENERAL_NAME) *names = NULL;
3060#endif
William Lallemand614ca0d2019-10-07 13:52:11 +02003061 struct ckch_inst *ckch_inst;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003062
Emeric Brun054563d2019-10-17 13:16:58 +02003063 *ckchi = NULL;
3064
William Lallemande3af8fb2019-10-08 11:36:53 +02003065 if (!ckchs || !ckchs->ckch || !ckchs->multi) {
William Lallemand36b84632019-07-18 19:28:17 +02003066 memprintf(err, "%sunable to load SSL certificate file '%s' file does not exist.\n",
3067 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003068 return ERR_ALERT | ERR_FATAL;
William Lallemand614ca0d2019-10-07 13:52:11 +02003069 }
3070
3071 ckch_inst = ckch_inst_new();
3072 if (!ckch_inst) {
3073 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3074 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003075 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand614ca0d2019-10-07 13:52:11 +02003076 goto end;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003077 }
3078
William Lallemande3af8fb2019-10-08 11:36:53 +02003079 certs_and_keys = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003080
yanbzhu08ce6ab2015-12-02 13:01:29 -05003081 /* Process each ckch and update keytypes for each CN/SAN
3082 * for example, if CN/SAN www.a.com is associated with
3083 * certs with keytype 0 and 2, then at the end of the loop,
3084 * www.a.com will have:
3085 * keyindex = 0 | 1 | 4 = 5
3086 */
3087 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
William Lallemand28a8fce2019-10-04 17:36:55 +02003088 int ret;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003089
3090 if (!ssl_sock_is_ckch_valid(&certs_and_keys[n]))
3091 continue;
3092
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003093 if (fcount) {
William Lallemand28a8fce2019-10-04 17:36:55 +02003094 for (i = 0; i < fcount; i++) {
3095 ret = ssl_sock_populate_sni_keytypes_hplr(sni_filter[i], &sni_keytypes_map, n);
3096 if (ret < 0) {
3097 memprintf(err, "%sunable to allocate SSL context.\n",
3098 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003099 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003100 goto end;
3101 }
3102 }
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003103 } else {
3104 /* A lot of the following code is OpenSSL boilerplate for processing CN's and SAN's,
3105 * so the line that contains logic is marked via comments
3106 */
3107 xname = X509_get_subject_name(certs_and_keys[n].cert);
3108 i = -1;
3109 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3110 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003111 ASN1_STRING *value;
3112 value = X509_NAME_ENTRY_get_data(entry);
3113 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003114 /* Important line is here */
William Lallemand28a8fce2019-10-04 17:36:55 +02003115 ret = ssl_sock_populate_sni_keytypes_hplr(str, &sni_keytypes_map, n);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003116
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003117 OPENSSL_free(str);
3118 str = NULL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003119 if (ret < 0) {
3120 memprintf(err, "%sunable to allocate SSL context.\n",
3121 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003122 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003123 goto end;
3124 }
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003125 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003126 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003127
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003128 /* Do the above logic for each SAN */
yanbzhu08ce6ab2015-12-02 13:01:29 -05003129#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003130 names = X509_get_ext_d2i(certs_and_keys[n].cert, NID_subject_alt_name, NULL, NULL);
3131 if (names) {
3132 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3133 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003134
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003135 if (name->type == GEN_DNS) {
3136 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
3137 /* Important line is here */
William Lallemand28a8fce2019-10-04 17:36:55 +02003138 ret = ssl_sock_populate_sni_keytypes_hplr(str, &sni_keytypes_map, n);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003139
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003140 OPENSSL_free(str);
3141 str = NULL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003142 if (ret < 0) {
3143 memprintf(err, "%sunable to allocate SSL context.\n",
3144 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003145 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003146 goto end;
3147 }
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003148 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003149 }
3150 }
3151 }
3152 }
3153#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
3154 }
3155
3156 /* If no files found, return error */
3157 if (eb_is_empty(&sni_keytypes_map)) {
3158 memprintf(err, "%sunable to load SSL certificate file '%s' file does not exist.\n",
3159 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003160 errcode |= ERR_ALERT | ERR_FATAL;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003161 goto end;
3162 }
3163
3164 /* We now have a map of CN/SAN to keytypes that are loaded in
3165 * Iterate through the map to create the SSL_CTX's (if needed)
3166 * and add each CTX to the SNI tree
3167 *
3168 * Some math here:
Joseph Herlant017b3da2018-11-15 09:07:59 -08003169 * There are 2^n - 1 possible combinations, each unique
yanbzhu08ce6ab2015-12-02 13:01:29 -05003170 * combination is denoted by the key in the map. Each key
3171 * has a value between 1 and 2^n - 1. Conveniently, the array
3172 * of SSL_CTX* is sized 2^n. So, we can simply use the i'th
3173 * entry in the array to correspond to the unique combo (key)
3174 * associated with i. This unique key combo (i) will be associated
3175 * with combos[i-1]
3176 */
3177
3178 node = ebmb_first(&sni_keytypes_map);
3179 while (node) {
3180 SSL_CTX *cur_ctx;
Bertrand Jacquin33423092016-11-13 16:37:13 +00003181 char cur_file[MAXPATHLEN+1];
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003182 const struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
yanbzhu08ce6ab2015-12-02 13:01:29 -05003183
3184 str = (char *)container_of(node, struct sni_keytype, name)->name.key;
3185 i = container_of(node, struct sni_keytype, name)->keytypes;
3186 cur_ctx = key_combos[i-1].ctx;
3187
3188 if (cur_ctx == NULL) {
3189 /* need to create SSL_CTX */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003190 cur_ctx = SSL_CTX_new(SSLv23_server_method());
yanbzhu08ce6ab2015-12-02 13:01:29 -05003191 if (cur_ctx == NULL) {
3192 memprintf(err, "%sunable to allocate SSL context.\n",
3193 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003194 errcode |= ERR_ALERT | ERR_FATAL;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003195 goto end;
3196 }
3197
yanbzhube2774d2015-12-10 15:07:30 -05003198 /* Load all required certs/keys/chains/OCSPs info into SSL_CTX */
yanbzhu08ce6ab2015-12-02 13:01:29 -05003199 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3200 if (i & (1<<n)) {
3201 /* Key combo contains ckch[n] */
Bertrand Jacquin33423092016-11-13 16:37:13 +00003202 snprintf(cur_file, MAXPATHLEN+1, "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
Emeric Bruna96b5822019-10-17 13:25:14 +02003203 errcode |= ssl_sock_put_ckch_into_ctx(cur_file, &certs_and_keys[n], cur_ctx, err);
3204 if (errcode & ERR_CODE)
yanbzhu08ce6ab2015-12-02 13:01:29 -05003205 goto end;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003206 }
3207 }
3208
yanbzhu08ce6ab2015-12-02 13:01:29 -05003209 /* Update key_combos */
3210 key_combos[i-1].ctx = cur_ctx;
3211 }
3212
3213 /* Update SNI Tree */
William Lallemand9117de92019-10-04 00:29:42 +02003214
William Lallemand1d29c742019-10-04 00:53:29 +02003215 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 +02003216 kinfo, str, key_combos[i-1].order);
3217 if (key_combos[i-1].order < 0) {
3218 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003219 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandfe49bb32019-10-03 23:46:33 +02003220 goto end;
3221 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003222 node = ebmb_next(node);
3223 }
3224
3225
3226 /* Mark a default context if none exists, using the ctx that has the most shared keys */
3227 if (!bind_conf->default_ctx) {
3228 for (i = SSL_SOCK_POSSIBLE_KT_COMBOS - 1; i >= 0; i--) {
3229 if (key_combos[i].ctx) {
3230 bind_conf->default_ctx = key_combos[i].ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003231 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003232 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003233 SSL_CTX_up_ref(bind_conf->default_ctx);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003234 break;
3235 }
3236 }
3237 }
3238
William Lallemand614ca0d2019-10-07 13:52:11 +02003239 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003240 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003241 ckch_inst->ckch_store = ckchs;
William Lallemand02e19a52020-04-08 16:11:26 +02003242
yanbzhu08ce6ab2015-12-02 13:01:29 -05003243end:
3244
3245 if (names)
3246 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
3247
yanbzhu08ce6ab2015-12-02 13:01:29 -05003248 node = ebmb_first(&sni_keytypes_map);
3249 while (node) {
3250 next = ebmb_next(node);
3251 ebmb_delete(node);
William Lallemand8ed5b962019-10-04 17:24:39 +02003252 free(ebmb_entry(node, struct sni_keytype, name));
yanbzhu08ce6ab2015-12-02 13:01:29 -05003253 node = next;
3254 }
3255
William Lallemand02e19a52020-04-08 16:11:26 +02003256 /* we need to free the ctx since we incremented the refcount where it's used */
3257 for (i = 0; i < SSL_SOCK_POSSIBLE_KT_COMBOS; i++) {
3258 if (key_combos[i].ctx)
3259 SSL_CTX_free(key_combos[i].ctx);
3260 }
3261
Emeric Brun054563d2019-10-17 13:16:58 +02003262 if (errcode & ERR_CODE && ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003263 if (ckch_inst->is_default) {
3264 SSL_CTX_free(bind_conf->default_ctx);
3265 bind_conf->default_ctx = NULL;
3266 }
3267
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003268 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003269 ckch_inst = NULL;
William Lallemand0c6d12f2019-10-04 18:38:51 +02003270 }
3271
Emeric Brun054563d2019-10-17 13:16:58 +02003272 *ckchi = ckch_inst;
3273 return errcode;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003274}
3275#else
3276/* This is a dummy, that just logs an error and returns error */
William Lallemandda8584c2020-05-14 10:14:37 +02003277int ckch_inst_new_load_multi_store(const char *path, struct ckch_store *ckchs,
3278 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
3279 char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
yanbzhu08ce6ab2015-12-02 13:01:29 -05003280{
3281 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3282 err && *err ? *err : "", path, strerror(errno));
Emeric Brun054563d2019-10-17 13:16:58 +02003283 return ERR_ALERT | ERR_FATAL;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003284}
3285
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003286#endif /* #if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL: Support for loading multiple certs into a single SSL_CTX */
yanbzhu488a4d22015-12-01 15:16:07 -05003287
William Lallemand614ca0d2019-10-07 13:52:11 +02003288/*
3289 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003290 *
3291 * Returns a bitfield containing the flags:
3292 * ERR_FATAL in any fatal error case
3293 * ERR_ALERT if the reason of the error is available in err
3294 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003295 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003296int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003297 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003298{
William Lallemandc9402072019-05-15 15:33:54 +02003299 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003300 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003301 int order = 0;
3302 X509_NAME *xname;
3303 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003304 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003305 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003306#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3307 STACK_OF(GENERAL_NAME) *names;
3308#endif
William Lallemand36b84632019-07-18 19:28:17 +02003309 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003310 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003311 int errcode = 0;
3312
3313 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003314
William Lallemande3af8fb2019-10-08 11:36:53 +02003315 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003316 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003317
William Lallemande3af8fb2019-10-08 11:36:53 +02003318 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003319
William Lallemandc9402072019-05-15 15:33:54 +02003320 ctx = SSL_CTX_new(SSLv23_server_method());
3321 if (!ctx) {
3322 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3323 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003324 errcode |= ERR_ALERT | ERR_FATAL;
3325 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003326 }
3327
Emeric Bruna96b5822019-10-17 13:25:14 +02003328 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3329 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003330 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003331
3332 ckch_inst = ckch_inst_new();
3333 if (!ckch_inst) {
3334 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3335 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003336 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003337 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003338 }
3339
William Lallemand36b84632019-07-18 19:28:17 +02003340 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003341 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003342 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003343 switch(EVP_PKEY_base_id(pkey)) {
3344 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003345 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003346 break;
3347 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003348 kinfo.sig = TLSEXT_signature_ecdsa;
3349 break;
3350 case EVP_PKEY_DSA:
3351 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003352 break;
3353 }
3354 EVP_PKEY_free(pkey);
3355 }
3356
Emeric Brun50bcecc2013-04-22 13:05:23 +02003357 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003358 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003359 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 +02003360 if (order < 0) {
3361 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003362 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003363 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003364 }
3365 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003366 }
3367 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003368#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003369 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003370 if (names) {
3371 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3372 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3373 if (name->type == GEN_DNS) {
3374 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003375 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003376 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003377 if (order < 0) {
3378 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003379 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003380 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003381 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003382 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003383 }
3384 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003385 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003386 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003387#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003388 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003389 i = -1;
3390 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3391 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003392 ASN1_STRING *value;
3393
3394 value = X509_NAME_ENTRY_get_data(entry);
3395 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003396 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003397 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003398 if (order < 0) {
3399 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003400 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003401 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003402 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003403 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003404 }
3405 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003406 /* we must not free the SSL_CTX anymore below, since it's already in
3407 * the tree, so it will be discovered and cleaned in time.
3408 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003409
Emeric Brunfc0421f2012-09-07 17:30:07 +02003410#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003411 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003412 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3413 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003414 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003415 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003416 }
3417#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003418 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003419 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003420 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003421 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003422 SSL_CTX_up_ref(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003423 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003424
William Lallemand9117de92019-10-04 00:29:42 +02003425 /* everything succeed, the ckch instance can be used */
3426 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003427 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003428 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003429
William Lallemand02e19a52020-04-08 16:11:26 +02003430 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3431
Emeric Brun054563d2019-10-17 13:16:58 +02003432 *ckchi = ckch_inst;
3433 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003434
3435error:
3436 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003437 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003438 if (ckch_inst->is_default)
3439 SSL_CTX_free(ctx);
3440
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003441 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003442 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003443 }
William Lallemandd9199372019-10-04 15:37:05 +02003444 SSL_CTX_free(ctx);
3445
Emeric Brun054563d2019-10-17 13:16:58 +02003446 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003447}
3448
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003449/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003450static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3451 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003452 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003453{
Emeric Brun054563d2019-10-17 13:16:58 +02003454 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003455
3456 /* we found the ckchs in the tree, we can use it directly */
3457 if (ckchs->multi)
William Lallemand24bde432020-03-09 16:48:43 +01003458 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 +02003459 else
William Lallemand24bde432020-03-09 16:48:43 +01003460 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 +02003461
Emeric Brun054563d2019-10-17 13:16:58 +02003462 if (errcode & ERR_CODE)
3463 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003464
William Lallemand24bde432020-03-09 16:48:43 +01003465 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003466
3467 /* succeed, add the instance to the ckch_store's list of instance */
William Lallemand24bde432020-03-09 16:48:43 +01003468 LIST_ADDQ(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003469 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003470}
3471
William Lallemand6be66ec2020-03-06 22:26:32 +01003472
William Lallemand4c68bba2020-03-30 18:45:10 +02003473
3474
3475/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3476 * done once. Zero is returned if the operation fails. No error is returned
3477 * if the random is said as not implemented, because we expect that openssl
3478 * will use another method once needed.
3479 */
3480static int ssl_initialize_random()
3481{
3482 unsigned char random;
3483 static int random_initialized = 0;
3484
3485 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3486 random_initialized = 1;
3487
3488 return random_initialized;
3489}
3490
William Lallemand2954c472020-03-06 21:54:13 +01003491/* Load a crt-list file, this is done in 2 parts:
3492 * - store the content of the file in a crtlist structure with crtlist_entry structures
3493 * - generate the instances by iterating on entries in the crtlist struct
3494 *
3495 * Nothing is locked there, this function is used in the configuration parser.
3496 *
3497 * Returns a set of ERR_* flags possibly with an error in <err>.
3498 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003499int 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 +01003500{
3501 struct crtlist *crtlist = NULL;
3502 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003503 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003504 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003505 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003506 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003507
William Lallemand79d31ec2020-03-25 15:10:49 +01003508 bind_conf_node = malloc(sizeof(*bind_conf_node));
3509 if (!bind_conf_node) {
3510 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3511 cfgerr |= ERR_FATAL | ERR_ALERT;
3512 goto error;
3513 }
3514 bind_conf_node->next = NULL;
3515 bind_conf_node->bind_conf = bind_conf;
3516
William Lallemand41ca9302020-04-08 13:15:18 +02003517 /* strip trailing slashes, including first one */
3518 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3519 *end = 0;
3520
William Lallemand2954c472020-03-06 21:54:13 +01003521 /* look for an existing crtlist or create one */
3522 eb = ebst_lookup(&crtlists_tree, file);
3523 if (eb) {
3524 crtlist = ebmb_entry(eb, struct crtlist, node);
3525 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003526 /* load a crt-list OR a directory */
3527 if (dir)
3528 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3529 else
3530 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3531
William Lallemand2954c472020-03-06 21:54:13 +01003532 if (!(cfgerr & ERR_CODE))
3533 ebst_insert(&crtlists_tree, &crtlist->node);
3534 }
3535
3536 if (cfgerr & ERR_CODE) {
3537 cfgerr |= ERR_FATAL | ERR_ALERT;
3538 goto error;
3539 }
3540
3541 /* generates ckch instance from the crtlist_entry */
3542 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3543 struct ckch_store *store;
3544 struct ckch_inst *ckch_inst = NULL;
3545
3546 store = entry->node.key;
3547 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3548 if (cfgerr & ERR_CODE) {
3549 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3550 goto error;
3551 }
William Lallemand49398312020-03-30 17:01:33 +02003552 LIST_ADDQ(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003553 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003554 }
William Lallemand2954c472020-03-06 21:54:13 +01003555
William Lallemand79d31ec2020-03-25 15:10:49 +01003556 /* add the bind_conf to the list */
3557 bind_conf_node->next = crtlist->bind_conf;
3558 crtlist->bind_conf = bind_conf_node;
3559
William Lallemand2954c472020-03-06 21:54:13 +01003560 return cfgerr;
3561error:
3562 {
William Lallemand49398312020-03-30 17:01:33 +02003563 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003564 struct ckch_inst *inst, *s_inst;
3565
William Lallemand49398312020-03-30 17:01:33 +02003566 lastentry = entry; /* which entry we tried to generate last */
3567 if (lastentry) {
3568 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3569 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3570 break;
3571
3572 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003573
William Lallemand49398312020-03-30 17:01:33 +02003574 /* this was not generated for this bind_conf, skip */
3575 if (inst->bind_conf != bind_conf)
3576 continue;
3577
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003578 /* free the sni_ctx and instance */
3579 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003580 }
William Lallemand2954c472020-03-06 21:54:13 +01003581 }
William Lallemand2954c472020-03-06 21:54:13 +01003582 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003583 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003584 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003585 return cfgerr;
3586}
3587
William Lallemand06b22a82020-03-16 14:45:55 +01003588/* Returns a set of ERR_* flags possibly with an error in <err>. */
3589int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3590{
3591 struct stat buf;
3592 char fp[MAXPATHLEN+1];
3593 int cfgerr = 0;
3594 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003595 struct ckch_inst *ckch_inst = NULL;
William Lallemand06b22a82020-03-16 14:45:55 +01003596
3597 if ((ckchs = ckchs_lookup(path))) {
3598 /* we found the ckchs in the tree, we can use it directly */
William Lallemand24bde432020-03-09 16:48:43 +01003599 return ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003600 }
3601 if (stat(path, &buf) == 0) {
3602 if (S_ISDIR(buf.st_mode) == 0) {
3603 ckchs = ckchs_load_cert_file(path, 0, err);
3604 if (!ckchs)
3605 return ERR_ALERT | ERR_FATAL;
3606
William Lallemand24bde432020-03-09 16:48:43 +01003607 return ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003608 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003609 return ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003610 }
3611 } else {
3612 /* stat failed, could be a bundle */
3613 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
3614 /* try to load a bundle if it is permitted */
3615 ckchs = ckchs_load_cert_file(path, 1, err);
3616 if (!ckchs)
3617 return ERR_ALERT | ERR_FATAL;
William Lallemand24bde432020-03-09 16:48:43 +01003618 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003619 } else {
3620 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3621 err && *err ? *err : "", fp, strerror(errno));
3622 cfgerr |= ERR_ALERT | ERR_FATAL;
3623 }
3624 }
3625
3626 return cfgerr;
3627}
3628
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003629/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003630static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003631ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003632{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003633 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003634 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003635 SSL_OP_ALL | /* all known workarounds for bugs */
3636 SSL_OP_NO_SSLv2 |
3637 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003638 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003639 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003640 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003641 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003642 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003643 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003644 SSL_MODE_ENABLE_PARTIAL_WRITE |
3645 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003646 SSL_MODE_RELEASE_BUFFERS |
3647 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003648 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003649 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003650 int flags = MC_SSL_O_ALL;
3651 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003652 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003653
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003654 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003655 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003656
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003657 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003658 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3659 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3660 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003661 else
3662 flags = conf_ssl_methods->flags;
3663
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003664 min = conf_ssl_methods->min;
3665 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003666
3667 /* default minimum is TLSV12, */
3668 if (!min) {
3669 if (!max || (max >= default_min_ver)) {
3670 min = default_min_ver;
3671 } else {
3672 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). "
3673 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3674 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3675 min = max;
3676 }
3677 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003678 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003679 if (min)
3680 flags |= (methodVersions[min].flag - 1);
3681 if (max)
3682 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003683 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003684 min = max = CONF_TLSV_NONE;
3685 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003686 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003687 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003688 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003689 if (min) {
3690 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003691 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3692 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3693 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3694 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003695 hole = 0;
3696 }
3697 max = i;
3698 }
3699 else {
3700 min = max = i;
3701 }
3702 }
3703 else {
3704 if (min)
3705 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003706 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003707 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003708 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3709 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003710 cfgerr += 1;
3711 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003712 /* save real min/max in bind_conf */
3713 conf_ssl_methods->min = min;
3714 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003715
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003716#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003717 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003718 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003719 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003720 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003721 else
3722 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
3723 if (flags & methodVersions[i].flag)
3724 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003725#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003726 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003727 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3728 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003729#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003730
3731 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3732 options |= SSL_OP_NO_TICKET;
3733 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3734 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003735
3736#ifdef SSL_OP_NO_RENEGOTIATION
3737 options |= SSL_OP_NO_RENEGOTIATION;
3738#endif
3739
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003740 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003741
Willy Tarreau5db847a2019-05-09 14:13:35 +02003742#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003743 if (global_ssl.async)
3744 mode |= SSL_MODE_ASYNC;
3745#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003746 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003747 if (global_ssl.life_time)
3748 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003749
3750#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3751#ifdef OPENSSL_IS_BORINGSSL
3752 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3753 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003754#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003755 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003756 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003757 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3758 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003759#else
3760 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003761#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003762 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003763#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003764 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003765}
3766
William Lallemand4f45bb92017-10-30 20:08:51 +01003767
3768static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3769{
3770 if (first == block) {
3771 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3772 if (first->len > 0)
3773 sh_ssl_sess_tree_delete(sh_ssl_sess);
3774 }
3775}
3776
3777/* return first block from sh_ssl_sess */
3778static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3779{
3780 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3781
3782}
3783
3784/* store a session into the cache
3785 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3786 * data: asn1 encoded session
3787 * data_len: asn1 encoded session length
3788 * Returns 1 id session was stored (else 0)
3789 */
3790static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3791{
3792 struct shared_block *first;
3793 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3794
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003795 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003796 if (!first) {
3797 /* Could not retrieve enough free blocks to store that session */
3798 return 0;
3799 }
3800
3801 /* STORE the key in the first elem */
3802 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3803 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3804 first->len = sizeof(struct sh_ssl_sess_hdr);
3805
3806 /* it returns the already existing node
3807 or current node if none, never returns null */
3808 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3809 if (oldsh_ssl_sess != sh_ssl_sess) {
3810 /* NOTE: Row couldn't be in use because we lock read & write function */
3811 /* release the reserved row */
3812 shctx_row_dec_hot(ssl_shctx, first);
3813 /* replace the previous session already in the tree */
3814 sh_ssl_sess = oldsh_ssl_sess;
3815 /* ignore the previous session data, only use the header */
3816 first = sh_ssl_sess_first_block(sh_ssl_sess);
3817 shctx_row_inc_hot(ssl_shctx, first);
3818 first->len = sizeof(struct sh_ssl_sess_hdr);
3819 }
3820
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003821 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01003822 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003823 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01003824 }
3825
3826 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003827
3828 return 1;
3829}
William Lallemanded0b5ad2017-10-30 19:36:36 +01003830
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003831/* SSL callback used when a new session is created while connecting to a server */
3832static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
3833{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02003834 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003835 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003836
Willy Tarreau07d94e42018-09-20 10:57:52 +02003837 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003838
Olivier Houcharde6060c52017-11-16 17:42:52 +01003839 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
3840 int len;
3841 unsigned char *ptr;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003842
Olivier Houcharde6060c52017-11-16 17:42:52 +01003843 len = i2d_SSL_SESSION(sess, NULL);
3844 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
3845 ptr = s->ssl_ctx.reused_sess[tid].ptr;
3846 } else {
3847 free(s->ssl_ctx.reused_sess[tid].ptr);
3848 ptr = s->ssl_ctx.reused_sess[tid].ptr = malloc(len);
3849 s->ssl_ctx.reused_sess[tid].allocated_size = len;
3850 }
3851 if (s->ssl_ctx.reused_sess[tid].ptr) {
3852 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
3853 &ptr);
3854 }
3855 } else {
3856 free(s->ssl_ctx.reused_sess[tid].ptr);
3857 s->ssl_ctx.reused_sess[tid].ptr = NULL;
3858 }
3859
3860 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003861}
3862
Olivier Houcharde6060c52017-11-16 17:42:52 +01003863
William Lallemanded0b5ad2017-10-30 19:36:36 +01003864/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01003865int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003866{
3867 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
3868 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
3869 unsigned char *p;
3870 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02003871 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003872 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003873
3874 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003875 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02003876 * note: SSL_SESSION_set1_id is using
3877 * a memcpy so we need to use a different pointer
3878 * than sid_data or sid_ctx_data to avoid valgrind
3879 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01003880 */
3881
3882 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02003883
3884 /* copy value in an other buffer */
3885 memcpy(encid, sid_data, sid_length);
3886
3887 /* pad with 0 */
3888 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
3889 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
3890
3891 /* force length to zero to avoid ASN1 encoding */
3892 SSL_SESSION_set1_id(sess, encid, 0);
3893
3894 /* force length to zero to avoid ASN1 encoding */
3895 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003896
3897 /* check if buffer is large enough for the ASN1 encoded session */
3898 data_len = i2d_SSL_SESSION(sess, NULL);
3899 if (data_len > SHSESS_MAX_DATA_LEN)
3900 goto err;
3901
3902 p = encsess;
3903
3904 /* process ASN1 session encoding before the lock */
3905 i2d_SSL_SESSION(sess, &p);
3906
William Lallemanded0b5ad2017-10-30 19:36:36 +01003907
William Lallemanda3c77cf2017-10-30 23:44:40 +01003908 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003909 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003910 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01003911 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003912err:
3913 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02003914 SSL_SESSION_set1_id(sess, encid, sid_length);
3915 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003916
3917 return 0; /* do not increment session reference count */
3918}
3919
3920/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003921SSL_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 +01003922{
William Lallemand4f45bb92017-10-30 20:08:51 +01003923 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003924 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
3925 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01003926 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01003927 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003928
3929 global.shctx_lookups++;
3930
3931 /* allow the session to be freed automatically by openssl */
3932 *do_copy = 0;
3933
3934 /* tree key is zeros padded sessionid */
3935 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3936 memcpy(tmpkey, key, key_len);
3937 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
3938 key = tmpkey;
3939 }
3940
3941 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003942 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003943
3944 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003945 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
3946 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003947 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003948 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003949 global.shctx_misses++;
3950 return NULL;
3951 }
3952
William Lallemand4f45bb92017-10-30 20:08:51 +01003953 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
3954 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003955
William Lallemand4f45bb92017-10-30 20:08:51 +01003956 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 +01003957
William Lallemanda3c77cf2017-10-30 23:44:40 +01003958 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003959
3960 /* decode ASN1 session */
3961 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01003962 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003963 /* Reset session id and session id contenxt */
3964 if (sess) {
3965 SSL_SESSION_set1_id(sess, key, key_len);
3966 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
3967 }
3968
3969 return sess;
3970}
3971
William Lallemand4f45bb92017-10-30 20:08:51 +01003972
William Lallemanded0b5ad2017-10-30 19:36:36 +01003973/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003974void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003975{
William Lallemand4f45bb92017-10-30 20:08:51 +01003976 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003977 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
3978 unsigned int sid_length;
3979 const unsigned char *sid_data;
3980 (void)ctx;
3981
3982 sid_data = SSL_SESSION_get_id(sess, &sid_length);
3983 /* tree key is zeros padded sessionid */
3984 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3985 memcpy(tmpkey, sid_data, sid_length);
3986 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
3987 sid_data = tmpkey;
3988 }
3989
William Lallemanda3c77cf2017-10-30 23:44:40 +01003990 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003991
3992 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003993 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
3994 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003995 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003996 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003997 }
3998
3999 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004000 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004001}
4002
4003/* Set session cache mode to server and disable openssl internal cache.
4004 * Set shared cache callbacks on an ssl context.
4005 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004006void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004007{
4008 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4009
4010 if (!ssl_shctx) {
4011 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4012 return;
4013 }
4014
4015 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4016 SSL_SESS_CACHE_NO_INTERNAL |
4017 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4018
4019 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004020 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4021 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4022 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004023}
4024
William Lallemand8b453912019-11-21 15:48:10 +01004025/*
4026 * This function applies the SSL configuration on a SSL_CTX
4027 * It returns an error code and fills the <err> buffer
4028 */
4029int 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 +01004030{
4031 struct proxy *curproxy = bind_conf->frontend;
4032 int cfgerr = 0;
4033 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004034 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004035 const char *conf_ciphers;
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004036#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004037 const char *conf_ciphersuites;
4038#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004039 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004040
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004041 if (ssl_conf) {
4042 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4043 int i, min, max;
4044 int flags = MC_SSL_O_ALL;
4045
4046 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004047 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4048 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004049 if (min)
4050 flags |= (methodVersions[min].flag - 1);
4051 if (max)
4052 flags |= ~((methodVersions[max].flag << 1) - 1);
4053 min = max = CONF_TLSV_NONE;
4054 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4055 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4056 if (min)
4057 max = i;
4058 else
4059 min = max = i;
4060 }
4061 /* save real min/max */
4062 conf_ssl_methods->min = min;
4063 conf_ssl_methods->max = max;
4064 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004065 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4066 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004067 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004068 }
4069 }
4070
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004071 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004072 case SSL_SOCK_VERIFY_NONE:
4073 verify = SSL_VERIFY_NONE;
4074 break;
4075 case SSL_SOCK_VERIFY_OPTIONAL:
4076 verify = SSL_VERIFY_PEER;
4077 break;
4078 case SSL_SOCK_VERIFY_REQUIRED:
4079 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4080 break;
4081 }
4082 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4083 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004084 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 +01004085 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 +01004086 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 +01004087 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004088 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004089 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004090 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004091 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004092 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004093 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004094 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4095 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4096 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4097 cfgerr |= ERR_ALERT | ERR_FATAL;
4098 }
4099 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004100 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004101 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 +02004102 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004103 }
Emeric Brun850efd52014-01-29 12:24:34 +01004104 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004105 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4106 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004107 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004108 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004109#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004110 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004111 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4112
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004113 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004114 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4115 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004116 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004117 }
Emeric Brun561e5742012-10-02 15:20:55 +02004118 else {
4119 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4120 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004121 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004122#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004123 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004124 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004125#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004126 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004127 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004128 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4129 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004130 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004131 }
4132 }
4133#endif
4134
William Lallemand4f45bb92017-10-30 20:08:51 +01004135 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004136 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4137 if (conf_ciphers &&
4138 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004139 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4140 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004141 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004142 }
4143
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004144#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004145 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4146 if (conf_ciphersuites &&
4147 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004148 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4149 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004150 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004151 }
4152#endif
4153
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004154#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004155 /* If tune.ssl.default-dh-param has not been set,
4156 neither has ssl-default-dh-file and no static DH
4157 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004158 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004159 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004160 (ssl_dh_ptr_index == -1 ||
4161 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004162 /* default to dh-param 2048 */
4163 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004164 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004165
Willy Tarreauef934602016-12-22 23:12:01 +01004166 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004167 if (local_dh_1024 == NULL) {
4168 local_dh_1024 = ssl_get_dh_1024();
4169 }
Willy Tarreauef934602016-12-22 23:12:01 +01004170 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004171 if (local_dh_2048 == NULL) {
4172 local_dh_2048 = ssl_get_dh_2048();
4173 }
Willy Tarreauef934602016-12-22 23:12:01 +01004174 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004175 if (local_dh_4096 == NULL) {
4176 local_dh_4096 = ssl_get_dh_4096();
4177 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004178 }
4179 }
4180 }
4181#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004182
Emeric Brunfc0421f2012-09-07 17:30:07 +02004183 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004184#if HA_OPENSSL_VERSION_NUMBER >= 0x00907000L
Emeric Brun29f037d2014-04-25 19:05:36 +02004185 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004186#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004187
Bernard Spil13c53f82018-02-15 13:34:58 +01004188#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004189 ssl_conf_cur = NULL;
4190 if (ssl_conf && ssl_conf->npn_str)
4191 ssl_conf_cur = ssl_conf;
4192 else if (bind_conf->ssl_conf.npn_str)
4193 ssl_conf_cur = &bind_conf->ssl_conf;
4194 if (ssl_conf_cur)
4195 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004196#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004197#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004198 ssl_conf_cur = NULL;
4199 if (ssl_conf && ssl_conf->alpn_str)
4200 ssl_conf_cur = ssl_conf;
4201 else if (bind_conf->ssl_conf.alpn_str)
4202 ssl_conf_cur = &bind_conf->ssl_conf;
4203 if (ssl_conf_cur)
4204 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004205#endif
Lukas Tribusd14b49c2019-11-24 18:20:40 +01004206#if ((HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL) || defined(LIBRESSL_VERSION_NUMBER))
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004207 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4208 if (conf_curves) {
4209 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004210 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4211 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004212 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004213 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004214 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004215 }
4216#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004217#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004218 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004219 int i;
4220 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004221#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004222 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004223 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4224 NULL);
4225
4226 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004227 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004228 return cfgerr;
4229 }
4230#else
4231 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4232 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4233 ECDHE_DEFAULT_CURVE);
4234#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004235
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004236 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004237 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004238 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4239 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004240 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004241 }
4242 else {
4243 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4244 EC_KEY_free(ecdh);
4245 }
4246 }
4247#endif
4248
Emeric Brunfc0421f2012-09-07 17:30:07 +02004249 return cfgerr;
4250}
4251
Evan Broderbe554312013-06-27 00:05:25 -07004252static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4253{
4254 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4255 size_t prefixlen, suffixlen;
4256
4257 /* Trivial case */
4258 if (strcmp(pattern, hostname) == 0)
4259 return 1;
4260
Evan Broderbe554312013-06-27 00:05:25 -07004261 /* The rest of this logic is based on RFC 6125, section 6.4.3
4262 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4263
Emeric Bruna848dae2013-10-08 11:27:28 +02004264 pattern_wildcard = NULL;
4265 pattern_left_label_end = pattern;
4266 while (*pattern_left_label_end != '.') {
4267 switch (*pattern_left_label_end) {
4268 case 0:
4269 /* End of label not found */
4270 return 0;
4271 case '*':
4272 /* If there is more than one wildcards */
4273 if (pattern_wildcard)
4274 return 0;
4275 pattern_wildcard = pattern_left_label_end;
4276 break;
4277 }
4278 pattern_left_label_end++;
4279 }
4280
4281 /* If it's not trivial and there is no wildcard, it can't
4282 * match */
4283 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004284 return 0;
4285
4286 /* Make sure all labels match except the leftmost */
4287 hostname_left_label_end = strchr(hostname, '.');
4288 if (!hostname_left_label_end
4289 || strcmp(pattern_left_label_end, hostname_left_label_end) != 0)
4290 return 0;
4291
4292 /* Make sure the leftmost label of the hostname is long enough
4293 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004294 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004295 return 0;
4296
4297 /* Finally compare the string on either side of the
4298 * wildcard */
4299 prefixlen = pattern_wildcard - pattern;
4300 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
Emeric Bruna848dae2013-10-08 11:27:28 +02004301 if ((prefixlen && (memcmp(pattern, hostname, prefixlen) != 0))
4302 || (suffixlen && (memcmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004303 return 0;
4304
4305 return 1;
4306}
4307
4308static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4309{
4310 SSL *ssl;
4311 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004312 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004313 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004314 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004315
4316 int depth;
4317 X509 *cert;
4318 STACK_OF(GENERAL_NAME) *alt_names;
4319 int i;
4320 X509_NAME *cert_subject;
4321 char *str;
4322
4323 if (ok == 0)
4324 return ok;
4325
4326 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004327 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004328 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004329
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004330 /* We're checking if the provided hostnames match the desired one. The
4331 * desired hostname comes from the SNI we presented if any, or if not
4332 * provided then it may have been explicitly stated using a "verifyhost"
4333 * directive. If neither is set, we don't care about the name so the
4334 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004335 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004336 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004337 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004338 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004339 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004340 if (!servername)
4341 return ok;
4342 }
Evan Broderbe554312013-06-27 00:05:25 -07004343
4344 /* We only need to verify the CN on the actual server cert,
4345 * not the indirect CAs */
4346 depth = X509_STORE_CTX_get_error_depth(ctx);
4347 if (depth != 0)
4348 return ok;
4349
4350 /* At this point, the cert is *not* OK unless we can find a
4351 * hostname match */
4352 ok = 0;
4353
4354 cert = X509_STORE_CTX_get_current_cert(ctx);
4355 /* It seems like this might happen if verify peer isn't set */
4356 if (!cert)
4357 return ok;
4358
4359 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4360 if (alt_names) {
4361 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4362 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4363 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004364#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004365 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4366#else
Evan Broderbe554312013-06-27 00:05:25 -07004367 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004368#endif
Evan Broderbe554312013-06-27 00:05:25 -07004369 ok = ssl_sock_srv_hostcheck(str, servername);
4370 OPENSSL_free(str);
4371 }
4372 }
4373 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004374 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004375 }
4376
4377 cert_subject = X509_get_subject_name(cert);
4378 i = -1;
4379 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4380 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004381 ASN1_STRING *value;
4382 value = X509_NAME_ENTRY_get_data(entry);
4383 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004384 ok = ssl_sock_srv_hostcheck(str, servername);
4385 OPENSSL_free(str);
4386 }
4387 }
4388
Willy Tarreau71d058c2017-07-26 20:09:56 +02004389 /* report the mismatch and indicate if SNI was used or not */
4390 if (!ok && !conn->err_code)
4391 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004392 return ok;
4393}
4394
Emeric Brun94324a42012-10-11 14:00:19 +02004395/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004396int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004397{
Willy Tarreau03209342016-12-22 17:08:28 +01004398 struct proxy *curproxy = srv->proxy;
Emeric Brun94324a42012-10-11 14:00:19 +02004399 int cfgerr = 0;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004400 long options =
Emeric Brun94324a42012-10-11 14:00:19 +02004401 SSL_OP_ALL | /* all known workarounds for bugs */
4402 SSL_OP_NO_SSLv2 |
4403 SSL_OP_NO_COMPRESSION;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004404 long mode =
Emeric Brun94324a42012-10-11 14:00:19 +02004405 SSL_MODE_ENABLE_PARTIAL_WRITE |
4406 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004407 SSL_MODE_RELEASE_BUFFERS |
4408 SSL_MODE_SMALL_BUFFERS;
Emeric Brun850efd52014-01-29 12:24:34 +01004409 int verify = SSL_VERIFY_NONE;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004410 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004411 struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004412 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004413 int flags = MC_SSL_O_ALL;
Emeric Brun94324a42012-10-11 14:00:19 +02004414
Thierry Fournier383085f2013-01-24 14:15:43 +01004415 /* Make sure openssl opens /dev/urandom before the chroot */
4416 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004417 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004418 cfgerr++;
4419 }
4420
Willy Tarreaufce03112015-01-15 21:32:40 +01004421 /* Automatic memory computations need to know we use SSL there */
4422 global.ssl_used_backend = 1;
4423
4424 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004425 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004426 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004427 ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4428 curproxy->id, srv->id,
4429 srv->conf.file, srv->conf.line);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004430 cfgerr++;
4431 return cfgerr;
4432 }
4433 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004434 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004435 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004436
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004437 ctx = SSL_CTX_new(SSLv23_client_method());
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004438 if (!ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004439 ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4440 proxy_type_str(curproxy), curproxy->id,
4441 srv->id);
Emeric Brun94324a42012-10-11 14:00:19 +02004442 cfgerr++;
4443 return cfgerr;
4444 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004445
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004446 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004447 ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4448 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4449 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004450 else
4451 flags = conf_ssl_methods->flags;
4452
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004453 /* Real min and max should be determinate with configuration and openssl's capabilities */
4454 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004455 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004456 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004457 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004458
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004459 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004460 min = max = CONF_TLSV_NONE;
4461 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004462 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004463 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004464 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004465 if (min) {
4466 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004467 ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4468 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4469 proxy_type_str(curproxy), curproxy->id, srv->id,
4470 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004471 hole = 0;
4472 }
4473 max = i;
4474 }
4475 else {
4476 min = max = i;
4477 }
4478 }
4479 else {
4480 if (min)
4481 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004482 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004483 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004484 ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4485 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004486 cfgerr += 1;
4487 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004488
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004489#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004490 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004491 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004492 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004493 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004494 else
4495 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4496 if (flags & methodVersions[i].flag)
4497 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004498#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004499 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004500 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4501 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004502#endif
4503
4504 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4505 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004506 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004507
Willy Tarreau5db847a2019-05-09 14:13:35 +02004508#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004509 if (global_ssl.async)
4510 mode |= SSL_MODE_ASYNC;
4511#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004512 SSL_CTX_set_mode(ctx, mode);
4513 srv->ssl_ctx.ctx = ctx;
4514
Emeric Bruna7aa3092012-10-26 12:58:00 +02004515 if (srv->ssl_ctx.client_crt) {
4516 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 +01004517 ha_alert("config : %s '%s', server '%s': unable to load SSL private key from PEM file '%s'.\n",
4518 proxy_type_str(curproxy), curproxy->id,
4519 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004520 cfgerr++;
4521 }
4522 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 +01004523 ha_alert("config : %s '%s', server '%s': unable to load ssl certificate from PEM file '%s'.\n",
4524 proxy_type_str(curproxy), curproxy->id,
4525 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004526 cfgerr++;
4527 }
4528 else if (SSL_CTX_check_private_key(srv->ssl_ctx.ctx) <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004529 ha_alert("config : %s '%s', server '%s': inconsistencies between private key and certificate loaded from PEM file '%s'.\n",
4530 proxy_type_str(curproxy), curproxy->id,
4531 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004532 cfgerr++;
4533 }
4534 }
Emeric Brun94324a42012-10-11 14:00:19 +02004535
Emeric Brun850efd52014-01-29 12:24:34 +01004536 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4537 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004538 switch (srv->ssl_ctx.verify) {
4539 case SSL_SOCK_VERIFY_NONE:
4540 verify = SSL_VERIFY_NONE;
4541 break;
4542 case SSL_SOCK_VERIFY_REQUIRED:
4543 verify = SSL_VERIFY_PEER;
4544 break;
4545 }
Evan Broderbe554312013-06-27 00:05:25 -07004546 SSL_CTX_set_verify(srv->ssl_ctx.ctx,
Emeric Brun850efd52014-01-29 12:24:34 +01004547 verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004548 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004549 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004550 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004551 /* set CAfile to verify */
4552 if (!ssl_set_verify_locations_file(srv->ssl_ctx.ctx, srv->ssl_ctx.ca_file)) {
4553 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to set CA file '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004554 curproxy->id, srv->id,
4555 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004556 cfgerr++;
4557 }
4558 }
Emeric Brun850efd52014-01-29 12:24:34 +01004559 else {
4560 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Christopher Faulet767a84b2017-11-24 16:50:31 +01004561 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",
4562 curproxy->id, srv->id,
4563 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004564 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01004565 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4566 curproxy->id, srv->id,
4567 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004568 cfgerr++;
4569 }
Emeric Brunef42d922012-10-11 16:11:36 +02004570#ifdef X509_V_FLAG_CRL_CHECK
4571 if (srv->ssl_ctx.crl_file) {
4572 X509_STORE *store = SSL_CTX_get_cert_store(srv->ssl_ctx.ctx);
4573
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004574 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004575 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4576 curproxy->id, srv->id,
4577 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004578 cfgerr++;
4579 }
4580 else {
4581 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4582 }
4583 }
4584#endif
4585 }
4586
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004587 SSL_CTX_set_session_cache_mode(srv->ssl_ctx.ctx, SSL_SESS_CACHE_CLIENT |
4588 SSL_SESS_CACHE_NO_INTERNAL_STORE);
4589 SSL_CTX_sess_set_new_cb(srv->ssl_ctx.ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004590 if (srv->ssl_ctx.ciphers &&
4591 !SSL_CTX_set_cipher_list(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphers)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004592 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4593 curproxy->id, srv->id,
4594 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004595 cfgerr++;
4596 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004597
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004598#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004599 if (srv->ssl_ctx.ciphersuites &&
Pierre Cheynierbc34cd12019-03-21 16:15:47 +00004600 !SSL_CTX_set_ciphersuites(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphersuites)) {
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004601 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4602 curproxy->id, srv->id,
4603 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4604 cfgerr++;
4605 }
4606#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004607#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4608 if (srv->ssl_ctx.npn_str)
4609 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, srv);
4610#endif
4611#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4612 if (srv->ssl_ctx.alpn_str)
4613 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4614#endif
4615
Emeric Brun94324a42012-10-11 14:00:19 +02004616
4617 return cfgerr;
4618}
4619
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004620/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004621 * be NULL, in which case nothing is done. Returns the number of errors
4622 * encountered.
4623 */
Willy Tarreau03209342016-12-22 17:08:28 +01004624int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004625{
4626 struct ebmb_node *node;
4627 struct sni_ctx *sni;
4628 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004629 int errcode = 0;
4630 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004631
Willy Tarreaufce03112015-01-15 21:32:40 +01004632 /* Automatic memory computations need to know we use SSL there */
4633 global.ssl_used_frontend = 1;
4634
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004635 /* Make sure openssl opens /dev/urandom before the chroot */
4636 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004637 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004638 err++;
4639 }
4640 /* Create initial_ctx used to start the ssl connection before do switchctx */
4641 if (!bind_conf->initial_ctx) {
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004642 err += ssl_sock_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004643 /* It should not be necessary to call this function, but it's
4644 necessary first to check and move all initialisation related
4645 to initial_ctx in ssl_sock_initial_ctx. */
William Lallemand8b453912019-11-21 15:48:10 +01004646 errcode |= ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004647 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004648 if (bind_conf->default_ctx)
William Lallemand8b453912019-11-21 15:48:10 +01004649 errcode |= ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, &errmsg);
Emeric Brun0bed9942014-10-30 19:25:24 +01004650
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004651 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004652 while (node) {
4653 sni = ebmb_entry(node, struct sni_ctx, name);
Emeric Brun0bed9942014-10-30 19:25:24 +01004654 if (!sni->order && sni->ctx != bind_conf->default_ctx)
4655 /* only initialize the CTX on its first occurrence and
4656 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004657 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004658 node = ebmb_next(node);
4659 }
4660
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004661 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004662 while (node) {
4663 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004664 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004665 /* only initialize the CTX on its first occurrence and
4666 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004667 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
4668 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004669 node = ebmb_next(node);
4670 }
William Lallemand8b453912019-11-21 15:48:10 +01004671
4672 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004673 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004674 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004675 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004676 err++;
4677 }
4678
4679 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004680 return err;
4681}
4682
Willy Tarreau55d37912016-12-21 23:38:39 +01004683/* Prepares all the contexts for a bind_conf and allocates the shared SSL
4684 * context if needed. Returns < 0 on error, 0 on success. The warnings and
4685 * alerts are directly emitted since the rest of the stack does it below.
4686 */
4687int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
4688{
4689 struct proxy *px = bind_conf->frontend;
4690 int alloc_ctx;
4691 int err;
4692
4693 if (!bind_conf->is_ssl) {
4694 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004695 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
4696 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01004697 }
4698 return 0;
4699 }
4700 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004701 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004702 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
4703 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004704 }
4705 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004706 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
4707 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004708 return -1;
4709 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004710 }
William Lallemandc61c0b32017-12-04 18:46:39 +01004711 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004712 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02004713 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01004714 sizeof(*sh_ssl_sess_tree),
4715 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02004716 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004717 if (alloc_ctx == SHCTX_E_INIT_LOCK)
4718 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");
4719 else
4720 ha_alert("Unable to allocate SSL session cache.\n");
4721 return -1;
4722 }
4723 /* free block callback */
4724 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
4725 /* init the root tree within the extra space */
4726 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
4727 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01004728 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004729 err = 0;
4730 /* initialize all certificate contexts */
4731 err += ssl_sock_prepare_all_ctx(bind_conf);
4732
4733 /* initialize CA variables if the certificates generation is enabled */
4734 err += ssl_sock_load_ca(bind_conf);
4735
4736 return -err;
4737}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004738
4739/* release ssl context allocated for servers. */
4740void ssl_sock_free_srv_ctx(struct server *srv)
4741{
Olivier Houchardc7566002018-11-20 23:33:50 +01004742#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4743 if (srv->ssl_ctx.alpn_str)
4744 free(srv->ssl_ctx.alpn_str);
4745#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01004746#ifdef OPENSSL_NPN_NEGOTIATED
Olivier Houchardc7566002018-11-20 23:33:50 +01004747 if (srv->ssl_ctx.npn_str)
4748 free(srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01004749#endif
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004750 if (srv->ssl_ctx.ctx)
4751 SSL_CTX_free(srv->ssl_ctx.ctx);
4752}
4753
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004754/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004755 * be NULL, in which case nothing is done. The default_ctx is nullified too.
4756 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004757void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004758{
4759 struct ebmb_node *node, *back;
4760 struct sni_ctx *sni;
4761
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004762 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004763 while (node) {
4764 sni = ebmb_entry(node, struct sni_ctx, name);
4765 back = ebmb_next(node);
4766 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004767 SSL_CTX_free(sni->ctx);
4768 if (!sni->order) { /* only free the CTX conf on its first occurrence */
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004769 ssl_sock_free_ssl_conf(sni->conf);
4770 free(sni->conf);
4771 sni->conf = NULL;
4772 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004773 free(sni);
4774 node = back;
4775 }
4776
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004777 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004778 while (node) {
4779 sni = ebmb_entry(node, struct sni_ctx, name);
4780 back = ebmb_next(node);
4781 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004782 SSL_CTX_free(sni->ctx);
4783 if (!sni->order) { /* only free the SSL conf its first occurrence */
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004784 ssl_sock_free_ssl_conf(sni->conf);
4785 free(sni->conf);
4786 sni->conf = NULL;
4787 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004788 free(sni);
4789 node = back;
4790 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004791 SSL_CTX_free(bind_conf->initial_ctx);
4792 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02004793 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004794 bind_conf->default_ctx = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004795 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02004796}
4797
Willy Tarreau795cdab2016-12-22 17:30:54 +01004798/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
4799void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
4800{
4801 ssl_sock_free_ca(bind_conf);
4802 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004803 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01004804 free(bind_conf->ca_sign_file);
4805 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02004806 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01004807 free(bind_conf->keys_ref->filename);
4808 free(bind_conf->keys_ref->tlskeys);
4809 LIST_DEL(&bind_conf->keys_ref->list);
4810 free(bind_conf->keys_ref);
4811 }
4812 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004813 bind_conf->ca_sign_pass = NULL;
4814 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004815}
4816
Christopher Faulet31af49d2015-06-09 17:29:50 +02004817/* Load CA cert file and private key used to generate certificates */
4818int
Willy Tarreau03209342016-12-22 17:08:28 +01004819ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02004820{
Willy Tarreau03209342016-12-22 17:08:28 +01004821 struct proxy *px = bind_conf->frontend;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004822 FILE *fp;
4823 X509 *cacert = NULL;
4824 EVP_PKEY *capkey = NULL;
4825 int err = 0;
4826
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02004827 if (!bind_conf->generate_certs)
Christopher Faulet31af49d2015-06-09 17:29:50 +02004828 return err;
4829
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01004830#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02004831 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01004832 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004833 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02004834 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004835 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02004836#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02004837
Christopher Faulet31af49d2015-06-09 17:29:50 +02004838 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004839 ha_alert("Proxy '%s': cannot enable certificate generation, "
4840 "no CA certificate File configured at [%s:%d].\n",
4841 px->id, bind_conf->file, bind_conf->line);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004842 goto load_error;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004843 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004844
4845 /* read in the CA certificate */
4846 if (!(fp = fopen(bind_conf->ca_sign_file, "r"))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004847 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
4848 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004849 goto load_error;
4850 }
4851 if (!(cacert = PEM_read_X509(fp, NULL, NULL, NULL))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004852 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
4853 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004854 goto read_error;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004855 }
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004856 rewind(fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004857 if (!(capkey = PEM_read_PrivateKey(fp, NULL, NULL, bind_conf->ca_sign_pass))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004858 ha_alert("Proxy '%s': Failed to read CA private key file '%s' at [%s:%d].\n",
4859 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004860 goto read_error;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004861 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004862
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004863 fclose (fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004864 bind_conf->ca_sign_cert = cacert;
4865 bind_conf->ca_sign_pkey = capkey;
4866 return err;
4867
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004868 read_error:
4869 fclose (fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004870 if (capkey) EVP_PKEY_free(capkey);
4871 if (cacert) X509_free(cacert);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004872 load_error:
4873 bind_conf->generate_certs = 0;
4874 err++;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004875 return err;
4876}
4877
4878/* Release CA cert and private key used to generate certificated */
4879void
4880ssl_sock_free_ca(struct bind_conf *bind_conf)
4881{
Christopher Faulet31af49d2015-06-09 17:29:50 +02004882 if (bind_conf->ca_sign_pkey)
4883 EVP_PKEY_free(bind_conf->ca_sign_pkey);
4884 if (bind_conf->ca_sign_cert)
4885 X509_free(bind_conf->ca_sign_cert);
Willy Tarreau94ff03a2016-12-22 17:57:46 +01004886 bind_conf->ca_sign_pkey = NULL;
4887 bind_conf->ca_sign_cert = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004888}
4889
Emeric Brun46591952012-05-18 15:47:34 +02004890/*
4891 * This function is called if SSL * context is not yet allocated. The function
4892 * is designed to be called before any other data-layer operation and sets the
4893 * handshake flag on the connection. It is safe to call it multiple times.
4894 * It returns 0 on success and -1 in error case.
4895 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004896static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004897{
Olivier Houchard66ab4982019-02-26 18:37:15 +01004898 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02004899 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004900 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004901 return 0;
4902
Willy Tarreau3c728722014-01-23 13:50:42 +01004903 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02004904 return 0;
4905
Olivier Houchard66ab4982019-02-26 18:37:15 +01004906 ctx = pool_alloc(ssl_sock_ctx_pool);
4907 if (!ctx) {
4908 conn->err_code = CO_ER_SSL_NO_MEM;
4909 return -1;
4910 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004911 ctx->wait_event.tasklet = tasklet_new();
4912 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004913 conn->err_code = CO_ER_SSL_NO_MEM;
4914 pool_free(ssl_sock_ctx_pool, ctx);
4915 return -1;
4916 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004917 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
4918 ctx->wait_event.tasklet->context = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004919 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01004920 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01004921 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004922 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01004923 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02004924 ctx->xprt_st = 0;
4925 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004926
4927 /* Only work with sockets for now, this should be adapted when we'll
4928 * add QUIC support.
4929 */
4930 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02004931 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004932 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
4933 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02004934 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01004935
Willy Tarreau20879a02012-12-03 16:32:10 +01004936 if (global.maxsslconn && sslconns >= global.maxsslconn) {
4937 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004938 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004939 }
Willy Tarreau403edff2012-09-06 11:58:37 +02004940
Emeric Brun46591952012-05-18 15:47:34 +02004941 /* If it is in client mode initiate SSL session
4942 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01004943 if (objt_server(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004944 int may_retry = 1;
4945
4946 retry_connect:
Emeric Brun46591952012-05-18 15:47:34 +02004947 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004948 ctx->ssl = SSL_new(__objt_server(conn->target)->ssl_ctx.ctx);
4949 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004950 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004951 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004952 goto retry_connect;
4953 }
Willy Tarreau20879a02012-12-03 16:32:10 +01004954 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004955 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004956 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004957 ctx->bio = BIO_new(ha_meth);
4958 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01004959 SSL_free(ctx->ssl);
4960 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004961 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004962 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004963 goto retry_connect;
4964 }
Emeric Brun55476152014-11-12 17:35:37 +01004965 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004966 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004967 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004968 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02004969 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02004970
Evan Broderbe554312013-06-27 00:05:25 -07004971 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004972 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
4973 SSL_free(ctx->ssl);
4974 ctx->ssl = NULL;
Emeric Brun55476152014-11-12 17:35:37 +01004975 conn->xprt_ctx = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004976 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004977 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004978 goto retry_connect;
4979 }
Emeric Brun55476152014-11-12 17:35:37 +01004980 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004981 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004982 }
4983
Olivier Houchard66ab4982019-02-26 18:37:15 +01004984 SSL_set_connect_state(ctx->ssl);
Willy Tarreau07d94e42018-09-20 10:57:52 +02004985 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
4986 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
4987 SSL_SESSION *sess = d2i_SSL_SESSION(NULL, &ptr, __objt_server(conn->target)->ssl_ctx.reused_sess[tid].size);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004988 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004989 SSL_SESSION_free(sess);
Willy Tarreau07d94e42018-09-20 10:57:52 +02004990 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
4991 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004992 } else if (sess) {
4993 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01004994 }
4995 }
Evan Broderbe554312013-06-27 00:05:25 -07004996
Emeric Brun46591952012-05-18 15:47:34 +02004997 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02004998 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02004999
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005000 _HA_ATOMIC_ADD(&sslconns, 1);
5001 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005002 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005003 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005004 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005005 return 0;
5006 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005007 else if (objt_listener(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005008 int may_retry = 1;
5009
5010 retry_accept:
Emeric Brun46591952012-05-18 15:47:34 +02005011 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005012 ctx->ssl = SSL_new(__objt_listener(conn->target)->bind_conf->initial_ctx);
5013 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005014 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005015 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005016 goto retry_accept;
5017 }
Willy Tarreau20879a02012-12-03 16:32:10 +01005018 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005019 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005020 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005021 ctx->bio = BIO_new(ha_meth);
5022 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01005023 SSL_free(ctx->ssl);
5024 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005025 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005026 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005027 goto retry_accept;
5028 }
Emeric Brun55476152014-11-12 17:35:37 +01005029 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005030 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005031 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005032 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02005033 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02005034
Emeric Brune1f38db2012-09-03 20:36:47 +02005035 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005036 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
5037 SSL_free(ctx->ssl);
5038 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005039 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005040 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005041 goto retry_accept;
5042 }
Emeric Brun55476152014-11-12 17:35:37 +01005043 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005044 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005045 }
5046
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005047#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5048 if (__objt_listener(conn->target)->bind_conf->ssl_conf.early_data) {
5049 b_alloc(&ctx->early_buf);
5050 SSL_set_max_early_data(ctx->ssl,
5051 /* Only allow early data if we managed to allocate
5052 * a buffer.
5053 */
5054 (!b_is_null(&ctx->early_buf)) ?
5055 global.tune.bufsize - global.tune.maxrewrite : 0);
5056 }
5057#endif
5058
Olivier Houchard66ab4982019-02-26 18:37:15 +01005059 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005060
Emeric Brun46591952012-05-18 15:47:34 +02005061 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005062 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005063#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchardc2aae742017-09-22 18:26:28 +02005064 conn->flags |= CO_FL_EARLY_SSL_HS;
5065#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005066
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005067 _HA_ATOMIC_ADD(&sslconns, 1);
5068 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005069 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005070 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005071 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005072 return 0;
5073 }
5074 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005075 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005076err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005077 if (ctx && ctx->wait_event.tasklet)
5078 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005079 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005080 return -1;
5081}
5082
5083
5084/* This is the callback which is used when an SSL handshake is pending. It
5085 * updates the FD status if it wants some polling before being called again.
5086 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5087 * otherwise it returns non-zero and removes itself from the connection's
5088 * flags (the bit is provided in <flag> by the caller).
5089 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005090static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005091{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005092 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005093 int ret;
5094
Willy Tarreau3c728722014-01-23 13:50:42 +01005095 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005096 return 0;
5097
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005098 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005099 goto out_error;
5100
Willy Tarreau5db847a2019-05-09 14:13:35 +02005101#if HA_OPENSSL_VERSION_NUMBER >= 0x10101000L
Olivier Houchardc2aae742017-09-22 18:26:28 +02005102 /*
5103 * Check if we have early data. If we do, we have to read them
5104 * before SSL_do_handshake() is called, And there's no way to
5105 * detect early data, except to try to read them
5106 */
5107 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005108 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005109
Olivier Houchard54907bb2019-12-19 15:02:39 +01005110 while (1) {
5111 ret = SSL_read_early_data(ctx->ssl,
5112 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5113 &read_data);
5114 if (ret == SSL_READ_EARLY_DATA_ERROR)
5115 goto check_error;
5116 if (read_data > 0) {
5117 conn->flags |= CO_FL_EARLY_DATA;
5118 b_add(&ctx->early_buf, read_data);
5119 }
5120 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5121 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5122 if (!b_data(&ctx->early_buf))
5123 b_free(&ctx->early_buf);
5124 break;
5125 }
5126 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005127 }
5128#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005129 /* If we use SSL_do_handshake to process a reneg initiated by
5130 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5131 * Usually SSL_write and SSL_read are used and process implicitly
5132 * the reneg handshake.
5133 * Here we use SSL_peek as a workaround for reneg.
5134 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005135 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005136 char c;
5137
Olivier Houchard66ab4982019-02-26 18:37:15 +01005138 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005139 if (ret <= 0) {
5140 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005141 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005142
Emeric Brun674b7432012-11-08 19:21:55 +01005143 if (ret == SSL_ERROR_WANT_WRITE) {
5144 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005145 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005146 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005147 return 0;
5148 }
5149 else if (ret == SSL_ERROR_WANT_READ) {
5150 /* handshake may have been completed but we have
5151 * no more data to read.
5152 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005153 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005154 ret = 1;
5155 goto reneg_ok;
5156 }
5157 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005158 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005159 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005160 return 0;
5161 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005162#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005163 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005164 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005165 return 0;
5166 }
5167#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005168 else if (ret == SSL_ERROR_SYSCALL) {
5169 /* if errno is null, then connection was successfully established */
5170 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5171 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005172 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005173#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5174 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005175 conn->err_code = CO_ER_SSL_HANDSHAKE;
5176#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005177 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005178#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005179 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005180 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005181 empty_handshake = state == TLS_ST_BEFORE;
5182#else
Lukas Tribus49799162019-07-08 14:29:15 +02005183 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5184 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005185#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005186 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005187 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005188 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005189 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5190 else
5191 conn->err_code = CO_ER_SSL_EMPTY;
5192 }
5193 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005194 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005195 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5196 else
5197 conn->err_code = CO_ER_SSL_ABORT;
5198 }
5199 }
5200 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005201 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005202 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005203 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005204 conn->err_code = CO_ER_SSL_HANDSHAKE;
5205 }
Lukas Tribus49799162019-07-08 14:29:15 +02005206#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005207 }
Emeric Brun674b7432012-11-08 19:21:55 +01005208 goto out_error;
5209 }
5210 else {
5211 /* Fail on all other handshake errors */
5212 /* Note: OpenSSL may leave unread bytes in the socket's
5213 * buffer, causing an RST to be emitted upon close() on
5214 * TCP sockets. We first try to drain possibly pending
5215 * data to avoid this as much as possible.
5216 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005217 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005218 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005219 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005220 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005221 goto out_error;
5222 }
5223 }
5224 /* read some data: consider handshake completed */
5225 goto reneg_ok;
5226 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005227 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005228check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005229 if (ret != 1) {
5230 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005231 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005232
5233 if (ret == SSL_ERROR_WANT_WRITE) {
5234 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005235 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005236 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005237 return 0;
5238 }
5239 else if (ret == SSL_ERROR_WANT_READ) {
5240 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005241 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005242 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5243 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005244 return 0;
5245 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005246#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005247 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005248 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005249 return 0;
5250 }
5251#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005252 else if (ret == SSL_ERROR_SYSCALL) {
5253 /* if errno is null, then connection was successfully established */
5254 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5255 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005256 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005257#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5258 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005259 conn->err_code = CO_ER_SSL_HANDSHAKE;
5260#else
5261 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005262#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005263 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005264 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005265 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005266#else
Lukas Tribus49799162019-07-08 14:29:15 +02005267 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5268 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005269#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005270 if (empty_handshake) {
5271 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005272 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005273 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5274 else
5275 conn->err_code = CO_ER_SSL_EMPTY;
5276 }
5277 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005278 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005279 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5280 else
5281 conn->err_code = CO_ER_SSL_ABORT;
5282 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005283 }
5284 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005285 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005286 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5287 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005288 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005289 }
Lukas Tribus49799162019-07-08 14:29:15 +02005290#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005291 }
Willy Tarreau89230192012-09-28 20:22:13 +02005292 goto out_error;
5293 }
Emeric Brun46591952012-05-18 15:47:34 +02005294 else {
5295 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005296 /* Note: OpenSSL may leave unread bytes in the socket's
5297 * buffer, causing an RST to be emitted upon close() on
5298 * TCP sockets. We first try to drain possibly pending
5299 * data to avoid this as much as possible.
5300 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005301 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005302 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005303 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005304 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005305 goto out_error;
5306 }
5307 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005308#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchard522eea72017-11-03 16:27:47 +01005309 else {
5310 /*
5311 * If the server refused the early data, we have to send a
5312 * 425 to the client, as we no longer have the data to sent
5313 * them again.
5314 */
5315 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005316 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005317 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5318 goto out_error;
5319 }
5320 }
5321 }
5322#endif
5323
Emeric Brun46591952012-05-18 15:47:34 +02005324
Emeric Brun674b7432012-11-08 19:21:55 +01005325reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005326
Willy Tarreau5db847a2019-05-09 14:13:35 +02005327#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005328 /* ASYNC engine API doesn't support moving read/write
5329 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005330 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005331 */
5332 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005333 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005334#endif
Emeric Brun46591952012-05-18 15:47:34 +02005335 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005336 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005337 if (objt_server(conn->target)) {
5338 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5339 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5340 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005341 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005342 else {
5343 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5344 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5345 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5346 }
Emeric Brun46591952012-05-18 15:47:34 +02005347 }
5348
5349 /* The connection is now established at both layers, it's time to leave */
5350 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5351 return 1;
5352
5353 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005354 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005355 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005356 ERR_clear_error();
5357
Emeric Brun9fa89732012-10-04 17:09:56 +02005358 /* free resumed session if exists */
Willy Tarreau07d94e42018-09-20 10:57:52 +02005359 if (objt_server(conn->target) && __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5360 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
5361 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Emeric Brun9fa89732012-10-04 17:09:56 +02005362 }
5363
Emeric Brun46591952012-05-18 15:47:34 +02005364 /* Fail on all other handshake errors */
5365 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005366 if (!conn->err_code)
5367 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005368 return 0;
5369}
5370
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005371/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5372 * event subscriber <es> is not allowed to change from a previous call as long
5373 * as at least one event is still subscribed. The <event_type> must only be a
5374 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5375 * unless the transport layer was already released.
5376 */
5377static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005378{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005379 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005380
Olivier Houchard0ff28652019-06-24 18:57:39 +02005381 if (!ctx)
5382 return -1;
5383
Willy Tarreau113d52b2020-01-10 09:20:26 +01005384 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005385 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005386
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005387 ctx->subs = es;
5388 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005389
5390 /* we may have to subscribe to lower layers for new events */
5391 event_type &= ~ctx->wait_event.events;
5392 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5393 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005394 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005395}
5396
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005397/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5398 * The <es> pointer is not allowed to differ from the one passed to the
5399 * subscribe() call. It always returns zero.
5400 */
5401static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005402{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005403 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005404
Willy Tarreau113d52b2020-01-10 09:20:26 +01005405 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005406 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005407
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005408 es->events &= ~event_type;
5409 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005410 ctx->subs = NULL;
5411
5412 /* If we subscribed, and we're not doing the handshake,
5413 * then we subscribed because the upper layer asked for it,
5414 * as the upper layer is no longer interested, we can
5415 * unsubscribe too.
5416 */
5417 event_type &= ctx->wait_event.events;
5418 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5419 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005420
5421 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005422}
5423
Olivier Houchard2e055482019-05-27 19:50:12 +02005424/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5425 * Returns 0 on success, and non-zero on failure.
5426 */
5427static 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)
5428{
5429 struct ssl_sock_ctx *ctx = xprt_ctx;
5430
5431 if (oldxprt_ops != NULL)
5432 *oldxprt_ops = ctx->xprt;
5433 if (oldxprt_ctx != NULL)
5434 *oldxprt_ctx = ctx->xprt_ctx;
5435 ctx->xprt = toadd_ops;
5436 ctx->xprt_ctx = toadd_ctx;
5437 return 0;
5438}
5439
Olivier Houchard5149b592019-05-23 17:47:36 +02005440/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5441 * return 0, otherwise just call the remove_xprt method from the underlying
5442 * XPRT.
5443 */
5444static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5445{
5446 struct ssl_sock_ctx *ctx = xprt_ctx;
5447
5448 if (ctx->xprt_ctx == toremove_ctx) {
5449 ctx->xprt_ctx = newctx;
5450 ctx->xprt = newops;
5451 return 0;
5452 }
5453 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5454}
5455
Olivier Houchardea8dd942019-05-20 14:02:16 +02005456static struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned short state)
5457{
5458 struct ssl_sock_ctx *ctx = context;
5459
5460 /* First if we're doing an handshake, try that */
5461 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS)
5462 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
5463 /* If we had an error, or the handshake is done and I/O is available,
5464 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005465 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005466 * we can't be sure conn_fd_handler() will be called again.
5467 */
5468 if ((ctx->conn->flags & CO_FL_ERROR) ||
5469 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5470 int ret = 0;
5471 int woke = 0;
5472
5473 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005474 if (ctx->subs) {
5475 tasklet_wakeup(ctx->subs->tasklet);
5476 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005477 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005478 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005479 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005480
Olivier Houchardea8dd942019-05-20 14:02:16 +02005481 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005482 * upper layers know. If we have no mux, create it,
5483 * and once we have a mux, call its wake method if we didn't
5484 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005485 */
5486 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005487 if (!ctx->conn->mux)
5488 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005489 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
5490 ctx->conn->mux->wake(ctx->conn);
5491 return NULL;
5492 }
5493 }
Olivier Houchard54907bb2019-12-19 15:02:39 +01005494#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5495 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005496 else if (b_data(&ctx->early_buf) && ctx->subs &&
5497 ctx->subs->events & SUB_RETRY_RECV) {
5498 tasklet_wakeup(ctx->subs->tasklet);
5499 ctx->subs->events &= ~SUB_RETRY_RECV;
5500 if (!ctx->subs->events)
5501 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005502 }
5503#endif
Olivier Houchardea8dd942019-05-20 14:02:16 +02005504 return NULL;
5505}
5506
Emeric Brun46591952012-05-18 15:47:34 +02005507/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01005508 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02005509 * buffer wraps, in which case a second call may be performed. The connection's
5510 * flags are updated with whatever special event is detected (error, read0,
5511 * empty). The caller is responsible for taking care of those events and
5512 * avoiding the call if inappropriate. The function does not call the
5513 * connection's polling update function, so the caller is responsible for this.
5514 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005515static 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 +02005516{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005517 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02005518 ssize_t ret;
5519 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02005520
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005521 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005522 goto out_error;
5523
Olivier Houchard54907bb2019-12-19 15:02:39 +01005524#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5525 if (b_data(&ctx->early_buf)) {
5526 try = b_contig_space(buf);
5527 if (try > b_data(&ctx->early_buf))
5528 try = b_data(&ctx->early_buf);
5529 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
5530 b_add(buf, try);
5531 b_del(&ctx->early_buf, try);
5532 if (b_data(&ctx->early_buf) == 0)
5533 b_free(&ctx->early_buf);
5534 return try;
5535 }
5536#endif
5537
Willy Tarreau911db9b2020-01-23 16:27:54 +01005538 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005539 /* a handshake was requested */
5540 return 0;
5541
Emeric Brun46591952012-05-18 15:47:34 +02005542 /* read the largest possible block. For this, we perform only one call
5543 * to recv() unless the buffer wraps and we exactly fill the first hunk,
5544 * in which case we accept to do it once again. A new attempt is made on
5545 * EINTR too.
5546 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01005547 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005548
Willy Tarreau591d4452018-06-15 17:21:00 +02005549 try = b_contig_space(buf);
5550 if (!try)
5551 break;
5552
Willy Tarreauabf08d92014-01-14 11:31:27 +01005553 if (try > count)
5554 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02005555
Olivier Houchard66ab4982019-02-26 18:37:15 +01005556 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005557
Emeric Brune1f38db2012-09-03 20:36:47 +02005558 if (conn->flags & CO_FL_ERROR) {
5559 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005560 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005561 }
Emeric Brun46591952012-05-18 15:47:34 +02005562 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02005563 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005564 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005565 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005566 }
Emeric Brun46591952012-05-18 15:47:34 +02005567 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005568 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005569 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005570 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02005571 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005572 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005573#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005574 /* Async mode can be re-enabled, because we're leaving data state.*/
5575 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005576 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005577#endif
Emeric Brun46591952012-05-18 15:47:34 +02005578 break;
5579 }
5580 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005581 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005582 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5583 SUB_RETRY_RECV,
5584 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01005585 /* handshake is running, and it may need to re-enable read */
5586 conn->flags |= CO_FL_SSL_WAIT_HS;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005587#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005588 /* Async mode can be re-enabled, because we're leaving data state.*/
5589 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005590 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005591#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005592 break;
5593 }
Emeric Brun46591952012-05-18 15:47:34 +02005594 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005595 } else if (ret == SSL_ERROR_ZERO_RETURN)
5596 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005597 /* For SSL_ERROR_SYSCALL, make sure to clear the error
5598 * stack before shutting down the connection for
5599 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005600 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
5601 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02005602 /* otherwise it's a real error */
5603 goto out_error;
5604 }
5605 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005606 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005607 return done;
5608
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005609 clear_ssl_error:
5610 /* Clear openssl global errors stack */
5611 ssl_sock_dump_errors(conn);
5612 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02005613 read0:
5614 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005615 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005616
Emeric Brun46591952012-05-18 15:47:34 +02005617 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005618 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01005619 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005620 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005621 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005622 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005623}
5624
5625
Willy Tarreau787db9a2018-06-14 18:31:46 +02005626/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
5627 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
5628 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02005629 * Only one call to send() is performed, unless the buffer wraps, in which case
5630 * a second call may be performed. The connection's flags are updated with
5631 * whatever special event is detected (error, empty). The caller is responsible
5632 * for taking care of those events and avoiding the call if inappropriate. The
5633 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02005634 * is responsible for this. The buffer's output is not adjusted, it's up to the
5635 * caller to take care of this. It's up to the caller to update the buffer's
5636 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02005637 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005638static 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 +02005639{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005640 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005641 ssize_t ret;
5642 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02005643
5644 done = 0;
5645
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005646 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005647 goto out_error;
5648
Willy Tarreau911db9b2020-01-23 16:27:54 +01005649 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005650 /* a handshake was requested */
5651 return 0;
5652
5653 /* send the largest possible block. For this we perform only one call
5654 * to send() unless the buffer wraps and we exactly fill the first hunk,
5655 * in which case we accept to do it once again.
5656 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02005657 while (count) {
Willy Tarreau5db847a2019-05-09 14:13:35 +02005658#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchardc2aae742017-09-22 18:26:28 +02005659 size_t written_data;
5660#endif
5661
Willy Tarreau787db9a2018-06-14 18:31:46 +02005662 try = b_contig_data(buf, done);
5663 if (try > count)
5664 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01005665
Willy Tarreau7bed9452014-02-02 02:00:24 +01005666 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005667 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01005668 global_ssl.max_record && try > global_ssl.max_record) {
5669 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005670 }
5671 else {
5672 /* we need to keep the information about the fact that
5673 * we're not limiting the upcoming send(), because if it
5674 * fails, we'll have to retry with at least as many data.
5675 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005676 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005677 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01005678
Willy Tarreau5db847a2019-05-09 14:13:35 +02005679#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchard010941f2019-05-03 20:56:19 +02005680 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005681 unsigned int max_early;
5682
Olivier Houchard522eea72017-11-03 16:27:47 +01005683 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01005684 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01005685 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005686 if (SSL_get0_session(ctx->ssl))
5687 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01005688 else
5689 max_early = 0;
5690 }
5691
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005692 if (try + ctx->sent_early_data > max_early) {
5693 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01005694 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02005695 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005696 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005697 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01005698 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005699 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005700 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005701 if (ret == 1) {
5702 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005703 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005704 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005705 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005706 /* Initiate the handshake, now */
5707 tasklet_wakeup(ctx->wait_event.tasklet);
5708 }
Olivier Houchard522eea72017-11-03 16:27:47 +01005709
Olivier Houchardc2aae742017-09-22 18:26:28 +02005710 }
5711
5712 } else
5713#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005714 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01005715
Emeric Brune1f38db2012-09-03 20:36:47 +02005716 if (conn->flags & CO_FL_ERROR) {
5717 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005718 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005719 }
Emeric Brun46591952012-05-18 15:47:34 +02005720 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005721 /* A send succeeded, so we can consider ourself connected */
5722 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005723 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005724 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005725 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005726 }
5727 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005728 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005729
Emeric Brun46591952012-05-18 15:47:34 +02005730 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005731 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01005732 /* handshake is running, and it may need to re-enable write */
5733 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005734 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005735#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005736 /* Async mode can be re-enabled, because we're leaving data state.*/
5737 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005738 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005739#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005740 break;
5741 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005742
Emeric Brun46591952012-05-18 15:47:34 +02005743 break;
5744 }
5745 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005746 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02005747 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005748 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5749 SUB_RETRY_RECV,
5750 &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005751#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005752 /* Async mode can be re-enabled, because we're leaving data state.*/
5753 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005754 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005755#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005756 break;
5757 }
Emeric Brun46591952012-05-18 15:47:34 +02005758 goto out_error;
5759 }
5760 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005761 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005762 return done;
5763
5764 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005765 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005766 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005767 ERR_clear_error();
5768
Emeric Brun46591952012-05-18 15:47:34 +02005769 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005770 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005771}
5772
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005773static void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02005774
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005775 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005776
Olivier Houchardea8dd942019-05-20 14:02:16 +02005777
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005778 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005779 if (ctx->wait_event.events != 0)
5780 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
5781 ctx->wait_event.events,
5782 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01005783 if (ctx->subs) {
5784 ctx->subs->events = 0;
5785 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005786 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005787
Olivier Houchard692c1d02019-05-23 18:41:47 +02005788 if (ctx->xprt->close)
5789 ctx->xprt->close(conn, ctx->xprt_ctx);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005790#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +02005791 if (global_ssl.async) {
5792 OSSL_ASYNC_FD all_fd[32], afd;
5793 size_t num_all_fds = 0;
5794 int i;
5795
Olivier Houchard66ab4982019-02-26 18:37:15 +01005796 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005797 if (num_all_fds > 32) {
5798 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
5799 return;
5800 }
5801
Olivier Houchard66ab4982019-02-26 18:37:15 +01005802 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005803
5804 /* If an async job is pending, we must try to
5805 to catch the end using polling before calling
5806 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005807 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02005808 for (i=0 ; i < num_all_fds ; i++) {
5809 /* switch on an handler designed to
5810 * handle the SSL_free
5811 */
5812 afd = all_fd[i];
5813 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005814 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02005815 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00005816 /* To ensure that the fd cache won't be used
5817 * and we'll catch a real RD event.
5818 */
5819 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02005820 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005821 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005822 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005823 _HA_ATOMIC_ADD(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005824 return;
5825 }
Emeric Brun3854e012017-05-17 20:42:48 +02005826 /* Else we can remove the fds from the fdtab
5827 * and call SSL_free.
5828 * note: we do a fd_remove and not a delete
5829 * because the fd is owned by the engine.
5830 * the engine is responsible to close
5831 */
5832 for (i=0 ; i < num_all_fds ; i++)
5833 fd_remove(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005834 }
5835#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005836 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01005837 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005838 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005839 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005840 _HA_ATOMIC_SUB(&sslconns, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005841 }
Emeric Brun46591952012-05-18 15:47:34 +02005842}
5843
5844/* This function tries to perform a clean shutdown on an SSL connection, and in
5845 * any case, flags the connection as reusable if no handshake was in progress.
5846 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005847static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02005848{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005849 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005850
Willy Tarreau911db9b2020-01-23 16:27:54 +01005851 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005852 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01005853 if (!clean)
5854 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005855 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005856 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005857 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01005858 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005859 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005860 ERR_clear_error();
5861 }
Emeric Brun46591952012-05-18 15:47:34 +02005862}
5863
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01005864
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005865/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01005866int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
5867{
5868 struct ssl_sock_ctx *ctx;
5869 X509 *crt;
5870
5871 if (!ssl_sock_is_ssl(conn))
5872 return 0;
5873
5874 ctx = conn->xprt_ctx;
5875
5876 crt = SSL_get_certificate(ctx->ssl);
5877 if (!crt)
5878 return 0;
5879
5880 return cert_get_pkey_algo(crt, out);
5881}
5882
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005883/* used for ppv2 cert signature (can be used for logging) */
5884const char *ssl_sock_get_cert_sig(struct connection *conn)
5885{
Christopher Faulet82004142019-09-10 10:12:03 +02005886 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005887
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005888 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
5889 X509 *crt;
5890
5891 if (!ssl_sock_is_ssl(conn))
5892 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005893 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005894 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005895 if (!crt)
5896 return NULL;
5897 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
5898 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
5899}
5900
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005901/* used for ppv2 authority */
5902const char *ssl_sock_get_sni(struct connection *conn)
5903{
5904#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02005905 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005906
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005907 if (!ssl_sock_is_ssl(conn))
5908 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005909 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005910 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005911#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01005912 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005913#endif
5914}
5915
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005916/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005917const char *ssl_sock_get_cipher_name(struct connection *conn)
5918{
Christopher Faulet82004142019-09-10 10:12:03 +02005919 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005920
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005921 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005922 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005923 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005924 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005925}
5926
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005927/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005928const char *ssl_sock_get_proto_version(struct connection *conn)
5929{
Christopher Faulet82004142019-09-10 10:12:03 +02005930 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005931
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005932 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005933 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005934 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005935 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005936}
5937
Olivier Houchardab28a322018-12-21 19:45:40 +01005938void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
5939{
5940#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02005941 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005942
Olivier Houcharde488ea82019-06-28 14:10:33 +02005943 if (!ssl_sock_is_ssl(conn))
5944 return;
Christopher Faulet82004142019-09-10 10:12:03 +02005945 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005946 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01005947#endif
5948}
5949
Willy Tarreau119a4082016-12-22 21:58:38 +01005950/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
5951 * to disable SNI.
5952 */
Willy Tarreau63076412015-07-10 11:33:32 +02005953void ssl_sock_set_servername(struct connection *conn, const char *hostname)
5954{
5955#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02005956 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005957
Willy Tarreau119a4082016-12-22 21:58:38 +01005958 char *prev_name;
5959
Willy Tarreau63076412015-07-10 11:33:32 +02005960 if (!ssl_sock_is_ssl(conn))
5961 return;
Christopher Faulet82004142019-09-10 10:12:03 +02005962 ctx = conn->xprt_ctx;
Willy Tarreau63076412015-07-10 11:33:32 +02005963
Willy Tarreau119a4082016-12-22 21:58:38 +01005964 /* if the SNI changes, we must destroy the reusable context so that a
5965 * new connection will present a new SNI. As an optimization we could
5966 * later imagine having a small cache of ssl_ctx to hold a few SNI per
5967 * server.
5968 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005969 prev_name = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau119a4082016-12-22 21:58:38 +01005970 if ((!prev_name && hostname) ||
5971 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01005972 SSL_set_session(ctx->ssl, NULL);
Willy Tarreau119a4082016-12-22 21:58:38 +01005973
Olivier Houchard66ab4982019-02-26 18:37:15 +01005974 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02005975#endif
5976}
5977
Emeric Brun0abf8362014-06-24 18:26:41 +02005978/* Extract peer certificate's common name into the chunk dest
5979 * Returns
5980 * the len of the extracted common name
5981 * or 0 if no CN found in DN
5982 * or -1 on error case (i.e. no peer certificate)
5983 */
Willy Tarreau83061a82018-07-13 11:56:34 +02005984int ssl_sock_get_remote_common_name(struct connection *conn,
5985 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04005986{
Christopher Faulet82004142019-09-10 10:12:03 +02005987 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04005988 X509 *crt = NULL;
5989 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04005990 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02005991 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005992 .area = (char *)&find_cn,
5993 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04005994 };
Emeric Brun0abf8362014-06-24 18:26:41 +02005995 int result = -1;
David Safb76832014-05-08 23:42:08 -04005996
5997 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02005998 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02005999 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006000
6001 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006002 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006003 if (!crt)
6004 goto out;
6005
6006 name = X509_get_subject_name(crt);
6007 if (!name)
6008 goto out;
David Safb76832014-05-08 23:42:08 -04006009
Emeric Brun0abf8362014-06-24 18:26:41 +02006010 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6011out:
David Safb76832014-05-08 23:42:08 -04006012 if (crt)
6013 X509_free(crt);
6014
6015 return result;
6016}
6017
Dave McCowan328fb582014-07-30 10:39:13 -04006018/* returns 1 if client passed a certificate for this session, 0 if not */
6019int ssl_sock_get_cert_used_sess(struct connection *conn)
6020{
Christopher Faulet82004142019-09-10 10:12:03 +02006021 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006022 X509 *crt = NULL;
6023
6024 if (!ssl_sock_is_ssl(conn))
6025 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006026 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006027
6028 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006029 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006030 if (!crt)
6031 return 0;
6032
6033 X509_free(crt);
6034 return 1;
6035}
6036
6037/* returns 1 if client passed a certificate for this connection, 0 if not */
6038int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006039{
Christopher Faulet82004142019-09-10 10:12:03 +02006040 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006041
David Safb76832014-05-08 23:42:08 -04006042 if (!ssl_sock_is_ssl(conn))
6043 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006044 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006045 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006046}
6047
6048/* returns result from SSL verify */
6049unsigned int ssl_sock_get_verify_result(struct connection *conn)
6050{
Christopher Faulet82004142019-09-10 10:12:03 +02006051 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006052
David Safb76832014-05-08 23:42:08 -04006053 if (!ssl_sock_is_ssl(conn))
6054 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006055 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006056 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006057}
6058
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006059/* Returns the application layer protocol name in <str> and <len> when known.
6060 * Zero is returned if the protocol name was not found, otherwise non-zero is
6061 * returned. The string is allocated in the SSL context and doesn't have to be
6062 * freed by the caller. NPN is also checked if available since older versions
6063 * of openssl (1.0.1) which are more common in field only support this one.
6064 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006065static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006066{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006067#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6068 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006069 struct ssl_sock_ctx *ctx = xprt_ctx;
6070 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006071 return 0;
6072
6073 *str = NULL;
6074
6075#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006076 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006077 if (*str)
6078 return 1;
6079#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006080#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006081 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006082 if (*str)
6083 return 1;
6084#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006085#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006086 return 0;
6087}
6088
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006089/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006090int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006091{
6092 X509 *ca;
6093 X509_NAME *name = NULL;
6094 ASN1_OCTET_STRING *skid = NULL;
6095 STACK_OF(X509) *chain = NULL;
6096 struct issuer_chain *issuer;
6097 struct eb64_node *node;
6098 char *path;
6099 u64 key;
6100 int ret = 0;
6101
6102 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6103 if (chain == NULL) {
6104 chain = sk_X509_new_null();
6105 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6106 name = X509_get_subject_name(ca);
6107 }
6108 if (!sk_X509_push(chain, ca)) {
6109 X509_free(ca);
6110 goto end;
6111 }
6112 }
6113 if (!chain) {
6114 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6115 goto end;
6116 }
6117 if (!skid) {
6118 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6119 goto end;
6120 }
6121 if (!name) {
6122 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6123 goto end;
6124 }
6125 key = XXH64(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006126 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006127 issuer = container_of(node, typeof(*issuer), node);
6128 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6129 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6130 goto end;
6131 }
6132 }
6133 issuer = calloc(1, sizeof *issuer);
6134 path = strdup(fp);
6135 if (!issuer || !path) {
6136 free(issuer);
6137 free(path);
6138 goto end;
6139 }
6140 issuer->node.key = key;
6141 issuer->path = path;
6142 issuer->chain = chain;
6143 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006144 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006145 ret = 1;
6146 end:
6147 if (skid)
6148 ASN1_OCTET_STRING_free(skid);
6149 if (chain)
6150 sk_X509_pop_free(chain, X509_free);
6151 return ret;
6152}
6153
William Lallemandda8584c2020-05-14 10:14:37 +02006154 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006155{
6156 AUTHORITY_KEYID *akid;
6157 struct issuer_chain *issuer = NULL;
6158
6159 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
6160 if (akid) {
6161 struct eb64_node *node;
6162 u64 hk;
6163 hk = XXH64(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
6164 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6165 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6166 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6167 issuer = ti;
6168 break;
6169 }
6170 }
6171 AUTHORITY_KEYID_free(akid);
6172 }
6173 return issuer;
6174}
6175
William Lallemanddad31052020-05-14 17:47:32 +02006176void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006177{
6178 struct eb64_node *node, *back;
6179 struct issuer_chain *issuer;
6180
William Lallemande0f3fd52020-02-25 14:53:06 +01006181 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006182 while (node) {
6183 issuer = container_of(node, typeof(*issuer), node);
6184 back = eb64_next(node);
6185 eb64_delete(node);
6186 free(issuer->path);
6187 sk_X509_pop_free(issuer->chain, X509_free);
6188 free(issuer);
6189 node = back;
6190 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006191}
6192
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006193#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006194static int ssl_check_async_engine_count(void) {
6195 int err_code = 0;
6196
Emeric Brun3854e012017-05-17 20:42:48 +02006197 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006198 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006199 err_code = ERR_ABORT;
6200 }
6201 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006202}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006203#endif
6204
William Lallemand32af2032016-10-29 18:09:35 +02006205/* This function is used with TLS ticket keys management. It permits to browse
6206 * each reference. The variable <getnext> must contain the current node,
6207 * <end> point to the root node.
6208 */
6209#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6210static inline
6211struct tls_keys_ref *tlskeys_list_get_next(struct tls_keys_ref *getnext, struct list *end)
6212{
6213 struct tls_keys_ref *ref = getnext;
6214
6215 while (1) {
6216
6217 /* Get next list entry. */
6218 ref = LIST_NEXT(&ref->list, struct tls_keys_ref *, list);
6219
6220 /* If the entry is the last of the list, return NULL. */
6221 if (&ref->list == end)
6222 return NULL;
6223
6224 return ref;
6225 }
6226}
6227
6228static inline
6229struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6230{
6231 int id;
6232 char *error;
6233
6234 /* If the reference starts by a '#', this is numeric id. */
6235 if (reference[0] == '#') {
6236 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6237 id = strtol(reference + 1, &error, 10);
6238 if (*error != '\0')
6239 return NULL;
6240
6241 /* Perform the unique id lookup. */
6242 return tlskeys_ref_lookupid(id);
6243 }
6244
6245 /* Perform the string lookup. */
6246 return tlskeys_ref_lookup(reference);
6247}
6248#endif
6249
6250
6251#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6252
6253static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6254
6255static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6256 return cli_io_handler_tlskeys_files(appctx);
6257}
6258
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006259/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6260 * (next index to be dumped), and cli.p0 (next key reference).
6261 */
William Lallemand32af2032016-10-29 18:09:35 +02006262static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6263
6264 struct stream_interface *si = appctx->owner;
6265
6266 switch (appctx->st2) {
6267 case STAT_ST_INIT:
6268 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006269 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006270 * later and restart at the state "STAT_ST_INIT".
6271 */
6272 chunk_reset(&trash);
6273
6274 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6275 chunk_appendf(&trash, "# id secret\n");
6276 else
6277 chunk_appendf(&trash, "# id (file)\n");
6278
Willy Tarreau06d80a92017-10-19 14:32:15 +02006279 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006280 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006281 return 0;
6282 }
6283
William Lallemand32af2032016-10-29 18:09:35 +02006284 /* Now, we start the browsing of the references lists.
6285 * Note that the following call to LIST_ELEM return bad pointer. The only
6286 * available field of this pointer is <list>. It is used with the function
6287 * tlskeys_list_get_next() for retruning the first available entry
6288 */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006289 if (appctx->ctx.cli.p0 == NULL) {
6290 appctx->ctx.cli.p0 = LIST_ELEM(&tlskeys_reference, struct tls_keys_ref *, list);
6291 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006292 }
6293
6294 appctx->st2 = STAT_ST_LIST;
6295 /* fall through */
6296
6297 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006298 while (appctx->ctx.cli.p0) {
6299 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006300
6301 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006302 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006303 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006304
6305 if (appctx->ctx.cli.i1 == 0)
6306 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6307
William Lallemand32af2032016-10-29 18:09:35 +02006308 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006309 int head;
6310
6311 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6312 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006313 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006314 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006315
6316 chunk_reset(t2);
6317 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006318 if (ref->key_size_bits == 128) {
6319 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6320 sizeof(struct tls_sess_key_128),
6321 t2->area, t2->size);
6322 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6323 t2->area);
6324 }
6325 else if (ref->key_size_bits == 256) {
6326 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6327 sizeof(struct tls_sess_key_256),
6328 t2->area, t2->size);
6329 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6330 t2->area);
6331 }
6332 else {
6333 /* This case should never happen */
6334 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6335 }
William Lallemand32af2032016-10-29 18:09:35 +02006336
Willy Tarreau06d80a92017-10-19 14:32:15 +02006337 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006338 /* let's try again later from this stream. We add ourselves into
6339 * this stream's users so that it can remove us upon termination.
6340 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006341 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006342 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006343 return 0;
6344 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006345 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006346 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006347 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006348 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006349 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006350 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006351 /* let's try again later from this stream. We add ourselves into
6352 * this stream's users so that it can remove us upon termination.
6353 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006354 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006355 return 0;
6356 }
6357
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006358 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006359 break;
6360
6361 /* get next list entry and check the end of the list */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006362 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006363 }
6364
6365 appctx->st2 = STAT_ST_FIN;
6366 /* fall through */
6367
6368 default:
6369 appctx->st2 = STAT_ST_FIN;
6370 return 1;
6371 }
6372 return 0;
6373}
6374
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006375/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006376static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006377{
William Lallemand32af2032016-10-29 18:09:35 +02006378 /* no parameter, shows only file list */
6379 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006380 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006381 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006382 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006383 }
6384
6385 if (args[2][0] == '*') {
6386 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006387 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006388 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006389 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006390 if (!appctx->ctx.cli.p0)
6391 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006392 }
William Lallemand32af2032016-10-29 18:09:35 +02006393 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006394 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006395}
6396
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006397static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006398{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006399 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006400 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006401
William Lallemand32af2032016-10-29 18:09:35 +02006402 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006403 if (!*args[3] || !*args[4])
6404 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 +02006405
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006406 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006407 if (!ref)
6408 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006409
Willy Tarreau1c913e42018-08-22 05:26:57 +02006410 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006411 if (ret < 0)
6412 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006413
Willy Tarreau1c913e42018-08-22 05:26:57 +02006414 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006415 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6416 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006417
Willy Tarreau9d008692019-08-09 11:21:01 +02006418 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006419}
William Lallemandd4f946c2019-12-05 10:26:40 +01006420#endif
William Lallemand419e6342020-04-08 12:05:39 +02006421
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006422static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006423{
6424#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6425 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006426 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006427
6428 if (!payload)
6429 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006430
6431 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006432 if (!*payload)
6433 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006434
6435 /* remove \r and \n from the payload */
6436 for (i = 0, j = 0; payload[i]; i++) {
6437 if (payload[i] == '\r' || payload[i] == '\n')
6438 continue;
6439 payload[j++] = payload[i];
6440 }
6441 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006442
Willy Tarreau1c913e42018-08-22 05:26:57 +02006443 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006444 if (ret < 0)
6445 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006446
Willy Tarreau1c913e42018-08-22 05:26:57 +02006447 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02006448 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02006449 if (err)
6450 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
6451 else
6452 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006453 }
Willy Tarreau9d008692019-08-09 11:21:01 +02006454
6455 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006456#else
Willy Tarreau9d008692019-08-09 11:21:01 +02006457 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 +02006458#endif
6459
Elliot Otchet71f82972020-01-15 08:12:14 -05006460}
6461
William Lallemand32af2032016-10-29 18:09:35 +02006462/* register cli keywords */
6463static struct cli_kw_list cli_kws = {{ },{
6464#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6465 { { "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 +02006466 { { "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 +02006467#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006468 { { "set", "ssl", "ocsp-response", NULL }, NULL, cli_parse_set_ocspresponse, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02006469 { { NULL }, NULL, NULL, NULL }
6470}};
6471
Willy Tarreau0108d902018-11-25 19:14:37 +01006472INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02006473
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02006474/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02006475struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02006476 .snd_buf = ssl_sock_from_buf,
6477 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01006478 .subscribe = ssl_subscribe,
6479 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02006480 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02006481 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02006482 .rcv_pipe = NULL,
6483 .snd_pipe = NULL,
6484 .shutr = NULL,
6485 .shutw = ssl_sock_shutw,
6486 .close = ssl_sock_close,
6487 .init = ssl_sock_init,
Willy Tarreau55d37912016-12-21 23:38:39 +01006488 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01006489 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01006490 .prepare_srv = ssl_sock_prepare_srv_ctx,
6491 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006492 .get_alpn = ssl_sock_get_alpn,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01006493 .name = "SSL",
Emeric Brun46591952012-05-18 15:47:34 +02006494};
6495
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006496enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
6497 struct session *sess, struct stream *s, int flags)
6498{
6499 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006500 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006501
6502 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006503 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006504
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006505 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006506 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006507 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006508 s->req.flags |= CF_READ_NULL;
6509 return ACT_RET_YIELD;
6510 }
6511 }
6512 return (ACT_RET_CONT);
6513}
6514
6515static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
6516{
6517 rule->action_ptr = ssl_action_wait_for_hs;
6518
6519 return ACT_RET_PRS_OK;
6520}
6521
6522static struct action_kw_list http_req_actions = {ILH, {
6523 { "wait-for-handshake", ssl_parse_wait_for_hs },
6524 { /* END */ }
6525}};
6526
Willy Tarreau0108d902018-11-25 19:14:37 +01006527INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
6528
Willy Tarreau5db847a2019-05-09 14:13:35 +02006529#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006530
6531static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6532{
6533 if (ptr) {
6534 chunk_destroy(ptr);
6535 free(ptr);
6536 }
6537}
6538
6539#endif
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006540static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6541{
Willy Tarreaubafbe012017-11-24 17:34:44 +01006542 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006543}
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006544
Emeric Brun46591952012-05-18 15:47:34 +02006545__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02006546static void __ssl_sock_init(void)
6547{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006548#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006549 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006550 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006551#endif
Emeric Brun46591952012-05-18 15:47:34 +02006552
Willy Tarreauef934602016-12-22 23:12:01 +01006553 if (global_ssl.listen_default_ciphers)
6554 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
6555 if (global_ssl.connect_default_ciphers)
6556 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Emmanuel Hocdet839af572019-05-14 16:27:35 +02006557#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02006558 if (global_ssl.listen_default_ciphersuites)
6559 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
6560 if (global_ssl.connect_default_ciphersuites)
6561 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
6562#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01006563
Willy Tarreau13e14102016-12-22 20:25:26 +01006564 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006565#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02006566 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08006567#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006568#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006569 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006570 n = sk_SSL_COMP_num(cm);
6571 while (n--) {
6572 (void) sk_SSL_COMP_pop(cm);
6573 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006574#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006575
Willy Tarreau5db847a2019-05-09 14:13:35 +02006576#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006577 ssl_locking_init();
6578#endif
Willy Tarreau5db847a2019-05-09 14:13:35 +02006579#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006580 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
6581#endif
Thierry FOURNIER28962c92018-06-17 21:37:05 +02006582 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02006583 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 +02006584#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006585 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006586 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006587#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01006588#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6589 hap_register_post_check(tlskeys_finalize_config);
6590#endif
Willy Tarreau80713382018-11-26 10:19:54 +01006591
6592 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
6593 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
6594
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006595 hap_register_post_deinit(ssl_free_global_issuers);
6596
Willy Tarreau80713382018-11-26 10:19:54 +01006597#ifndef OPENSSL_NO_DH
6598 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
6599 hap_register_post_deinit(ssl_free_dh);
6600#endif
6601#ifndef OPENSSL_NO_ENGINE
6602 hap_register_post_deinit(ssl_free_engines);
6603#endif
6604 /* Load SSL string for the verbose & debug mode. */
6605 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02006606 ha_meth = BIO_meth_new(0x666, "ha methods");
6607 BIO_meth_set_write(ha_meth, ha_ssl_write);
6608 BIO_meth_set_read(ha_meth, ha_ssl_read);
6609 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
6610 BIO_meth_set_create(ha_meth, ha_ssl_new);
6611 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
6612 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
6613 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02006614
6615 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006616
Dragan Dosen9ac98092020-05-11 15:51:45 +02006617 /* Try to register dedicated SSL/TLS protocol message callbacks for
6618 * heartbleed attack (CVE-2014-0160) and clienthello.
6619 */
6620 hap_register_post_check(ssl_sock_register_msg_callbacks);
6621
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006622 /* Try to free all callbacks that were registered by using
6623 * ssl_sock_register_msg_callback().
6624 */
6625 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01006626}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01006627
Willy Tarreau80713382018-11-26 10:19:54 +01006628/* Compute and register the version string */
6629static void ssl_register_build_options()
6630{
6631 char *ptr = NULL;
6632 int i;
6633
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006634 memprintf(&ptr, "Built with OpenSSL version : "
6635#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006636 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006637#else /* OPENSSL_IS_BORINGSSL */
6638 OPENSSL_VERSION_TEXT
6639 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08006640 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02006641 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006642#endif
6643 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006644#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006645 "no (library version too old)"
6646#elif defined(OPENSSL_NO_TLSEXT)
6647 "no (disabled via OPENSSL_NO_TLSEXT)"
6648#else
6649 "yes"
6650#endif
6651 "", ptr);
6652
6653 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
6654#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
6655 "yes"
6656#else
6657#ifdef OPENSSL_NO_TLSEXT
6658 "no (because of OPENSSL_NO_TLSEXT)"
6659#else
6660 "no (version might be too old, 0.9.8f min needed)"
6661#endif
6662#endif
6663 "", ptr);
6664
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02006665 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
6666 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
6667 if (methodVersions[i].option)
6668 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006669
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006670 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01006671}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006672
Willy Tarreau80713382018-11-26 10:19:54 +01006673INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02006674
Emeric Brun46591952012-05-18 15:47:34 +02006675
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006676#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006677void ssl_free_engines(void) {
6678 struct ssl_engine_list *wl, *wlb;
6679 /* free up engine list */
6680 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
6681 ENGINE_finish(wl->e);
6682 ENGINE_free(wl->e);
6683 LIST_DEL(&wl->list);
6684 free(wl);
6685 }
6686}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006687#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02006688
Remi Gacogned3a23c32015-05-28 16:39:47 +02006689#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00006690void ssl_free_dh(void) {
6691 if (local_dh_1024) {
6692 DH_free(local_dh_1024);
6693 local_dh_1024 = NULL;
6694 }
6695 if (local_dh_2048) {
6696 DH_free(local_dh_2048);
6697 local_dh_2048 = NULL;
6698 }
6699 if (local_dh_4096) {
6700 DH_free(local_dh_4096);
6701 local_dh_4096 = NULL;
6702 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02006703 if (global_dh) {
6704 DH_free(global_dh);
6705 global_dh = NULL;
6706 }
Grant Zhang872f9c22017-01-21 01:10:18 +00006707}
6708#endif
6709
6710__attribute__((destructor))
6711static void __ssl_sock_deinit(void)
6712{
6713#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006714 if (ssl_ctx_lru_tree) {
6715 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01006716 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02006717 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02006718#endif
6719
Willy Tarreau5db847a2019-05-09 14:13:35 +02006720#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006721 ERR_remove_state(0);
6722 ERR_free_strings();
6723
6724 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08006725#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02006726
Willy Tarreau5db847a2019-05-09 14:13:35 +02006727#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006728 CRYPTO_cleanup_all_ex_data();
6729#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02006730 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02006731}
6732
Emeric Brun46591952012-05-18 15:47:34 +02006733/*
6734 * Local variables:
6735 * c-indent-level: 8
6736 * c-basic-offset: 8
6737 * End:
6738 */