blob: 95db8f519571a5bb2197523a925681f1a0d3a0c0 [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
Christopher Faulet31af49d2015-06-09 17:29:50 +020043#include <import/lru.h>
44#include <import/xxhash.h>
45
Emeric Brun46591952012-05-18 15:47:34 +020046#include <common/buffer.h>
Willy Tarreau843b7cb2018-07-13 10:54:26 +020047#include <common/chunk.h>
Emeric Brun46591952012-05-18 15:47:34 +020048#include <common/compat.h>
49#include <common/config.h>
50#include <common/debug.h>
Willy Tarreau79eeafa2012-09-14 07:53:05 +020051#include <common/errors.h>
Willy Tarreau0108d902018-11-25 19:14:37 +010052#include <common/initcall.h>
Willy Tarreau55994562019-05-09 14:52:44 +020053#include <common/openssl-compat.h>
Emeric Brun46591952012-05-18 15:47:34 +020054#include <common/standard.h>
55#include <common/ticks.h>
56#include <common/time.h>
Nenad Merdanovic05552d42015-02-27 19:56:49 +010057#include <common/base64.h>
Emeric Brun46591952012-05-18 15:47:34 +020058
William Lallemand2954c472020-03-06 21:54:13 +010059#include <ebpttree.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020060#include <ebsttree.h>
61
William Lallemand32af2032016-10-29 18:09:35 +020062#include <types/applet.h>
63#include <types/cli.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020064#include <types/global.h>
65#include <types/ssl_sock.h>
William Lallemand32af2032016-10-29 18:09:35 +020066#include <types/stats.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020067
Willy Tarreau7875d092012-09-10 08:20:03 +020068#include <proto/acl.h>
69#include <proto/arg.h>
William Lallemand32af2032016-10-29 18:09:35 +020070#include <proto/channel.h>
Emeric Brun46591952012-05-18 15:47:34 +020071#include <proto/connection.h>
William Lallemand32af2032016-10-29 18:09:35 +020072#include <proto/cli.h>
Emeric Brun46591952012-05-18 15:47:34 +020073#include <proto/fd.h>
74#include <proto/freq_ctr.h>
75#include <proto/frontend.h>
Willy Tarreau61c112a2018-10-02 16:43:32 +020076#include <proto/http_rules.h>
Willy Tarreau79eeafa2012-09-14 07:53:05 +020077#include <proto/listener.h>
Thierry FOURNIERed66c292013-11-28 11:05:19 +010078#include <proto/pattern.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020079#include <proto/proto_tcp.h>
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020080#include <proto/http_ana.h>
Willy Tarreau92faadf2012-10-10 23:04:25 +020081#include <proto/server.h>
William Lallemand32af2032016-10-29 18:09:35 +020082#include <proto/stream_interface.h>
Emeric Brun46591952012-05-18 15:47:34 +020083#include <proto/log.h>
Emeric Brun94324a42012-10-11 14:00:19 +020084#include <proto/proxy.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020085#include <proto/shctx.h>
William Lallemandc69973f2020-05-12 17:42:42 +020086#include <proto/ssl_ckch.h>
William Lallemand6e9556b2020-05-12 17:52:44 +020087#include <proto/ssl_crtlist.h>
Emeric Brun46591952012-05-18 15:47:34 +020088#include <proto/ssl_sock.h>
Willy Tarreau9ad7bd42015-04-03 19:19:59 +020089#include <proto/stream.h>
Emeric Brun46591952012-05-18 15:47:34 +020090#include <proto/task.h>
Nenad Merdanovicc31499d2019-03-23 11:00:32 +010091#include <proto/vars.h>
Emeric Brun46591952012-05-18 15:47:34 +020092
Willy Tarreau9356dac2019-05-10 09:22:53 +020093/* ***** READ THIS before adding code here! *****
94 *
95 * Due to API incompatibilities between multiple OpenSSL versions and their
96 * derivatives, it's often tempting to add macros to (re-)define certain
97 * symbols. Please do not do this here, and do it in common/openssl-compat.h
98 * exclusively so that the whole code consistently uses the same macros.
99 *
100 * Whenever possible if a macro is missing in certain versions, it's better
101 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
102 */
103
Willy Tarreau71b734c2014-01-28 15:19:44 +0100104int sslconns = 0;
105int totalsslconns = 0;
Emeric Brunece0c332017-12-06 13:51:49 +0100106int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +0200107
William Lallemande0f3fd52020-02-25 14:53:06 +0100108static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
109
William Lallemand7fd8b452020-05-07 15:20:43 +0200110struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100111#ifdef LISTEN_DEFAULT_CIPHERS
112 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
113#endif
114#ifdef CONNECT_DEFAULT_CIPHERS
115 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
116#endif
Emmanuel Hocdet839af572019-05-14 16:27:35 +0200117#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200118#ifdef LISTEN_DEFAULT_CIPHERSUITES
119 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
120#endif
121#ifdef CONNECT_DEFAULT_CIPHERSUITES
122 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
123#endif
124#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100125 .listen_default_ssloptions = BC_SSL_O_NONE,
126 .connect_default_ssloptions = SRV_SSL_O_NONE,
127
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200128 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
129 .listen_default_sslmethods.min = CONF_TLSV_NONE,
130 .listen_default_sslmethods.max = CONF_TLSV_NONE,
131 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
132 .connect_default_sslmethods.min = CONF_TLSV_NONE,
133 .connect_default_sslmethods.max = CONF_TLSV_NONE,
134
Willy Tarreauef934602016-12-22 23:12:01 +0100135#ifdef DEFAULT_SSL_MAX_RECORD
136 .max_record = DEFAULT_SSL_MAX_RECORD,
137#endif
138 .default_dh_param = SSL_DEFAULT_DH_PARAM,
139 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Thierry FOURNIER5bf77322017-02-25 12:45:22 +0100140 .capture_cipherlist = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100141 .extra_files = SSL_GF_ALL,
Willy Tarreauef934602016-12-22 23:12:01 +0100142};
143
Olivier Houcharda8955d52019-04-07 22:00:38 +0200144static BIO_METHOD *ha_meth;
145
Olivier Houchard66ab4982019-02-26 18:37:15 +0100146DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
147
Olivier Houchardea8dd942019-05-20 14:02:16 +0200148static struct task *ssl_sock_io_cb(struct task *, void *, unsigned short);
Olivier Houchard000694c2019-05-23 14:45:12 +0200149static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200150
Olivier Houcharda8955d52019-04-07 22:00:38 +0200151/* Methods to implement OpenSSL BIO */
152static int ha_ssl_write(BIO *h, const char *buf, int num)
153{
154 struct buffer tmpbuf;
155 struct ssl_sock_ctx *ctx;
156 int ret;
157
158 ctx = BIO_get_data(h);
159 tmpbuf.size = num;
160 tmpbuf.area = (void *)(uintptr_t)buf;
161 tmpbuf.data = num;
162 tmpbuf.head = 0;
163 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200164 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200165 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200166 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200167 } else if (ret == 0)
168 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200169 return ret;
170}
171
172static int ha_ssl_gets(BIO *h, char *buf, int size)
173{
174
175 return 0;
176}
177
178static int ha_ssl_puts(BIO *h, const char *str)
179{
180
181 return ha_ssl_write(h, str, strlen(str));
182}
183
184static int ha_ssl_read(BIO *h, char *buf, int size)
185{
186 struct buffer tmpbuf;
187 struct ssl_sock_ctx *ctx;
188 int ret;
189
190 ctx = BIO_get_data(h);
191 tmpbuf.size = size;
192 tmpbuf.area = buf;
193 tmpbuf.data = 0;
194 tmpbuf.head = 0;
195 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200196 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200197 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200198 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200199 } else if (ret == 0)
200 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200201
202 return ret;
203}
204
205static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
206{
207 int ret = 0;
208 switch (cmd) {
209 case BIO_CTRL_DUP:
210 case BIO_CTRL_FLUSH:
211 ret = 1;
212 break;
213 }
214 return ret;
215}
216
217static int ha_ssl_new(BIO *h)
218{
219 BIO_set_init(h, 1);
220 BIO_set_data(h, NULL);
221 BIO_clear_flags(h, ~0);
222 return 1;
223}
224
225static int ha_ssl_free(BIO *data)
226{
227
228 return 1;
229}
230
231
Willy Tarreau5db847a2019-05-09 14:13:35 +0200232#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100233
Emeric Brun821bb9b2017-06-15 16:37:39 +0200234static HA_RWLOCK_T *ssl_rwlocks;
235
236
237unsigned long ssl_id_function(void)
238{
239 return (unsigned long)tid;
240}
241
242void ssl_locking_function(int mode, int n, const char * file, int line)
243{
244 if (mode & CRYPTO_LOCK) {
245 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100246 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200247 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100248 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200249 }
250 else {
251 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100252 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200253 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100254 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200255 }
256}
257
258static int ssl_locking_init(void)
259{
260 int i;
261
262 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
263 if (!ssl_rwlocks)
264 return -1;
265
266 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100267 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200268
269 CRYPTO_set_id_callback(ssl_id_function);
270 CRYPTO_set_locking_callback(ssl_locking_function);
271
272 return 0;
273}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100274
Emeric Brun821bb9b2017-06-15 16:37:39 +0200275#endif
276
William Lallemand150bfa82019-09-19 17:12:49 +0200277__decl_hathreads(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200278
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100279
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200280/*
Emmanuel Hocdetb270e812019-11-21 19:09:31 +0100281 * deduplicate cafile (and crlfile)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200282 */
283struct cafile_entry {
284 X509_STORE *ca_store;
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200285 STACK_OF(X509_NAME) *ca_list;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200286 struct ebmb_node node;
287 char path[0];
288};
289
290static struct eb_root cafile_tree = EB_ROOT_UNIQUE;
291
292static X509_STORE* ssl_store_get0_locations_file(char *path)
293{
294 struct ebmb_node *eb;
295
296 eb = ebst_lookup(&cafile_tree, path);
297 if (eb) {
298 struct cafile_entry *ca_e;
299 ca_e = ebmb_entry(eb, struct cafile_entry, node);
300 return ca_e->ca_store;
301 }
302 return NULL;
303}
304
William Lallemanddad31052020-05-14 17:47:32 +0200305int ssl_store_load_locations_file(char *path)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200306{
307 if (ssl_store_get0_locations_file(path) == NULL) {
308 struct cafile_entry *ca_e;
309 X509_STORE *store = X509_STORE_new();
310 if (X509_STORE_load_locations(store, path, NULL)) {
311 int pathlen;
312 pathlen = strlen(path);
313 ca_e = calloc(1, sizeof(*ca_e) + pathlen + 1);
314 if (ca_e) {
315 memcpy(ca_e->path, path, pathlen + 1);
316 ca_e->ca_store = store;
317 ebst_insert(&cafile_tree, &ca_e->node);
318 return 1;
319 }
320 }
321 X509_STORE_free(store);
322 return 0;
323 }
324 return 1;
325}
326
327/* mimic what X509_STORE_load_locations do with store_ctx */
328static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
329{
330 X509_STORE *store;
331 store = ssl_store_get0_locations_file(path);
332 if (store_ctx && store) {
333 int i;
334 X509_OBJECT *obj;
335 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
336 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
337 obj = sk_X509_OBJECT_value(objs, i);
338 switch (X509_OBJECT_get_type(obj)) {
339 case X509_LU_X509:
340 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
341 break;
342 case X509_LU_CRL:
343 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
344 break;
345 default:
346 break;
347 }
348 }
349 return 1;
350 }
351 return 0;
352}
353
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500354/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200355static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
356{
357 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
358 return ssl_set_cert_crl_file(store_ctx, path);
359}
360
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200361/*
362 Extract CA_list from CA_file already in tree.
363 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
364 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
365*/
366static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
367{
368 struct ebmb_node *eb;
369 struct cafile_entry *ca_e;
370
371 eb = ebst_lookup(&cafile_tree, path);
372 if (!eb)
373 return NULL;
374 ca_e = ebmb_entry(eb, struct cafile_entry, node);
375
376 if (ca_e->ca_list == NULL) {
377 int i;
378 unsigned long key;
379 struct eb_root ca_name_tree = EB_ROOT;
380 struct eb64_node *node, *back;
381 struct {
382 struct eb64_node node;
383 X509_NAME *xname;
384 } *ca_name;
385 STACK_OF(X509_OBJECT) *objs;
386 STACK_OF(X509_NAME) *skn;
387 X509 *x;
388 X509_NAME *xn;
389
390 skn = sk_X509_NAME_new_null();
391 /* take x509 from cafile_tree */
392 objs = X509_STORE_get0_objects(ca_e->ca_store);
393 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
394 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
395 if (!x)
396 continue;
397 xn = X509_get_subject_name(x);
398 if (!xn)
399 continue;
400 /* Check for duplicates. */
401 key = X509_NAME_hash(xn);
402 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
403 node && ca_name == NULL;
404 node = eb64_next(node)) {
405 ca_name = container_of(node, typeof(*ca_name), node);
406 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
407 ca_name = NULL;
408 }
409 /* find a duplicate */
410 if (ca_name)
411 continue;
412 ca_name = calloc(1, sizeof *ca_name);
413 xn = X509_NAME_dup(xn);
414 if (!ca_name ||
415 !xn ||
416 !sk_X509_NAME_push(skn, xn)) {
417 free(ca_name);
418 X509_NAME_free(xn);
419 sk_X509_NAME_pop_free(skn, X509_NAME_free);
420 sk_X509_NAME_free(skn);
421 skn = NULL;
422 break;
423 }
424 ca_name->node.key = key;
425 ca_name->xname = xn;
426 eb64_insert(&ca_name_tree, &ca_name->node);
427 }
428 ca_e->ca_list = skn;
429 /* remove temporary ca_name tree */
430 node = eb64_first(&ca_name_tree);
431 while (node) {
432 ca_name = container_of(node, typeof(*ca_name), node);
433 back = eb64_next(node);
434 eb64_delete(node);
435 free(ca_name);
436 node = back;
437 }
438 }
439 return ca_e->ca_list;
440}
441
Willy Tarreaubafbe012017-11-24 17:34:44 +0100442struct pool_head *pool_head_ssl_capture = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200443int ssl_capture_ptr_index = -1;
Thierry FOURNIER28962c92018-06-17 21:37:05 +0200444static int ssl_app_data_index = -1;
Willy Tarreauef934602016-12-22 23:12:01 +0100445
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200446#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
447struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
448#endif
449
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200450#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200451unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000452struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
453struct ssl_engine_list {
454 struct list list;
455 ENGINE *e;
456};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200457#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000458
Remi Gacogne8de54152014-07-15 11:36:40 +0200459#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200460static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200461static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200462static DH *local_dh_1024 = NULL;
463static DH *local_dh_2048 = NULL;
464static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100465static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200466#endif /* OPENSSL_NO_DH */
467
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100468#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200469/* X509V3 Extensions that will be added on generated certificates */
470#define X509V3_EXT_SIZE 5
471static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
472 "basicConstraints",
473 "nsComment",
474 "subjectKeyIdentifier",
475 "authorityKeyIdentifier",
476 "keyUsage",
477};
478static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
479 "CA:FALSE",
480 "\"OpenSSL Generated Certificate\"",
481 "hash",
482 "keyid,issuer:always",
483 "nonRepudiation,digitalSignature,keyEncipherment"
484};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200485/* LRU cache to store generated certificate */
486static struct lru64_head *ssl_ctx_lru_tree = NULL;
487static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200488static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100489__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200490
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200491#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
492
Willy Tarreau9a1ab082019-05-09 13:26:41 +0200493#if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
yanbzhube2774d2015-12-10 15:07:30 -0500494/* The order here matters for picking a default context,
495 * keep the most common keytype at the bottom of the list
496 */
497const char *SSL_SOCK_KEYTYPE_NAMES[] = {
498 "dsa",
499 "ecdsa",
500 "rsa"
501};
yanbzhube2774d2015-12-10 15:07:30 -0500502#endif
503
William Lallemandc3cd35f2017-11-28 11:04:43 +0100504static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100505static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
506
Dragan Dosen9ac98092020-05-11 15:51:45 +0200507/* Dedicated callback functions for heartbeat and clienthello.
508 */
509#ifdef TLS1_RT_HEARTBEAT
510static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
511 int content_type, const void *buf, size_t len,
512 SSL *ssl);
513#endif
514static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
515 int content_type, const void *buf, size_t len,
516 SSL *ssl);
517
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200518/* List head of all registered SSL/TLS protocol message callbacks. */
519struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
520
521/* Registers the function <func> in order to be called on SSL/TLS protocol
522 * message processing. It will return 0 if the function <func> is not set
523 * or if it fails to allocate memory.
524 */
525int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
526{
527 struct ssl_sock_msg_callback *cbk;
528
529 if (!func)
530 return 0;
531
532 cbk = calloc(1, sizeof(*cbk));
533 if (!cbk) {
534 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
535 return 0;
536 }
537
538 cbk->func = func;
539
540 LIST_ADDQ(&ssl_sock_msg_callbacks, &cbk->list);
541
542 return 1;
543}
544
Dragan Dosen9ac98092020-05-11 15:51:45 +0200545/* Used to register dedicated SSL/TLS protocol message callbacks.
546 */
547static int ssl_sock_register_msg_callbacks(void)
548{
549#ifdef TLS1_RT_HEARTBEAT
550 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
551 return ERR_ABORT;
552#endif
553 if (global_ssl.capture_cipherlist > 0) {
554 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
555 return ERR_ABORT;
556 }
557 return 0;
558}
559
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200560/* Used to free all SSL/TLS protocol message callbacks that were
561 * registered by using ssl_sock_register_msg_callback().
562 */
563static void ssl_sock_unregister_msg_callbacks(void)
564{
565 struct ssl_sock_msg_callback *cbk, *cbkback;
566
567 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
568 LIST_DEL(&cbk->list);
569 free(cbk);
570 }
571}
572
Dragan Doseneb607fe2020-05-11 17:17:06 +0200573SSL *ssl_sock_get_ssl_object(struct connection *conn)
574{
575 if (!ssl_sock_is_ssl(conn))
576 return NULL;
577
578 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
579}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100580/*
581 * This function gives the detail of the SSL error. It is used only
582 * if the debug mode and the verbose mode are activated. It dump all
583 * the SSL error until the stack was empty.
584 */
585static forceinline void ssl_sock_dump_errors(struct connection *conn)
586{
587 unsigned long ret;
588
589 if (unlikely(global.mode & MODE_DEBUG)) {
590 while(1) {
591 ret = ERR_get_error();
592 if (ret == 0)
593 return;
594 fprintf(stderr, "fd[%04x] OpenSSL error[0x%lx] %s: %s\n",
Willy Tarreau585744b2017-08-24 14:31:19 +0200595 (unsigned short)conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100596 ERR_func_error_string(ret), ERR_reason_error_string(ret));
597 }
598 }
599}
600
yanbzhube2774d2015-12-10 15:07:30 -0500601
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200602#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200603int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000604{
605 int err_code = ERR_ABORT;
606 ENGINE *engine;
607 struct ssl_engine_list *el;
608
609 /* grab the structural reference to the engine */
610 engine = ENGINE_by_id(engine_id);
611 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100612 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000613 goto fail_get;
614 }
615
616 if (!ENGINE_init(engine)) {
617 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100618 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000619 goto fail_init;
620 }
621
622 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100623 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000624 goto fail_set_method;
625 }
626
627 el = calloc(1, sizeof(*el));
628 el->e = engine;
629 LIST_ADD(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100630 nb_engines++;
631 if (global_ssl.async)
632 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000633 return 0;
634
635fail_set_method:
636 /* release the functional reference from ENGINE_init() */
637 ENGINE_finish(engine);
638
639fail_init:
640 /* release the structural reference from ENGINE_by_id() */
641 ENGINE_free(engine);
642
643fail_get:
644 return err_code;
645}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200646#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000647
Willy Tarreau5db847a2019-05-09 14:13:35 +0200648#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +0200649/*
650 * openssl async fd handler
651 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200652void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000653{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200654 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000655
Emeric Brun3854e012017-05-17 20:42:48 +0200656 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000657 * to poll this fd until it is requested
658 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000659 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000660 fd_cant_recv(fd);
661
662 /* crypto engine is available, let's notify the associated
663 * connection that it can pursue its processing.
664 */
Olivier Houchard03abf2d2019-05-28 10:12:02 +0200665 ssl_sock_io_cb(NULL, ctx, 0);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000666}
667
Emeric Brun3854e012017-05-17 20:42:48 +0200668/*
669 * openssl async delayed SSL_free handler
670 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200671void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000672{
673 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200674 OSSL_ASYNC_FD all_fd[32];
675 size_t num_all_fds = 0;
676 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000677
Emeric Brun3854e012017-05-17 20:42:48 +0200678 /* We suppose that the async job for a same SSL *
679 * are serialized. So if we are awake it is
680 * because the running job has just finished
681 * and we can remove all async fds safely
682 */
683 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
684 if (num_all_fds > 32) {
685 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
686 return;
687 }
688
689 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
690 for (i=0 ; i < num_all_fds ; i++)
691 fd_remove(all_fd[i]);
692
693 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000694 SSL_free(ssl);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +0100695 _HA_ATOMIC_SUB(&sslconns, 1);
696 _HA_ATOMIC_SUB(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000697}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000698/*
Emeric Brun3854e012017-05-17 20:42:48 +0200699 * function used to manage a returned SSL_ERROR_WANT_ASYNC
700 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000701 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200702static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000703{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100704 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200705 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200706 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000707 size_t num_add_fds = 0;
708 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200709 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000710
711 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
712 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200713 if (num_add_fds > 32 || num_del_fds > 32) {
714 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 +0000715 return;
716 }
717
Emeric Brun3854e012017-05-17 20:42:48 +0200718 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000719
Emeric Brun3854e012017-05-17 20:42:48 +0200720 /* We remove unused fds from the fdtab */
721 for (i=0 ; i < num_del_fds ; i++)
722 fd_remove(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000723
Emeric Brun3854e012017-05-17 20:42:48 +0200724 /* We add new fds to the fdtab */
725 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200726 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000727 }
728
Emeric Brun3854e012017-05-17 20:42:48 +0200729 num_add_fds = 0;
730 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
731 if (num_add_fds > 32) {
732 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
733 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000734 }
Emeric Brun3854e012017-05-17 20:42:48 +0200735
736 /* We activate the polling for all known async fds */
737 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000738 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200739 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000740 /* To ensure that the fd cache won't be used
741 * We'll prefer to catch a real RD event
742 * because handling an EAGAIN on this fd will
743 * result in a context switch and also
744 * some engines uses a fd in blocking mode.
745 */
746 fd_cant_recv(add_fd[i]);
747 }
Emeric Brun3854e012017-05-17 20:42:48 +0200748
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000749}
750#endif
751
William Lallemand104a7a62019-10-14 14:14:59 +0200752#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200753/*
754 * This function returns the number of seconds elapsed
755 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
756 * date presented un ASN1_GENERALIZEDTIME.
757 *
758 * In parsing error case, it returns -1.
759 */
760static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
761{
762 long epoch;
763 char *p, *end;
764 const unsigned short month_offset[12] = {
765 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
766 };
767 int year, month;
768
769 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
770
771 p = (char *)d->data;
772 end = p + d->length;
773
774 if (end - p < 4) return -1;
775 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
776 p += 4;
777 if (end - p < 2) return -1;
778 month = 10 * (p[0] - '0') + p[1] - '0';
779 if (month < 1 || month > 12) return -1;
780 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
781 We consider leap years and the current month (<marsh or not) */
782 epoch = ( ((year - 1970) * 365)
783 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
784 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
785 + month_offset[month-1]
786 ) * 24 * 60 * 60;
787 p += 2;
788 if (end - p < 2) return -1;
789 /* Add the number of seconds of completed days of current month */
790 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
791 p += 2;
792 if (end - p < 2) return -1;
793 /* Add the completed hours of the current day */
794 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
795 p += 2;
796 if (end - p < 2) return -1;
797 /* Add the completed minutes of the current hour */
798 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
799 p += 2;
800 if (p == end) return -1;
801 /* Test if there is available seconds */
802 if (p[0] < '0' || p[0] > '9')
803 goto nosec;
804 if (end - p < 2) return -1;
805 /* Add the seconds of the current minute */
806 epoch += 10 * (p[0] - '0') + p[1] - '0';
807 p += 2;
808 if (p == end) return -1;
809 /* Ignore seconds float part if present */
810 if (p[0] == '.') {
811 do {
812 if (++p == end) return -1;
813 } while (p[0] >= '0' && p[0] <= '9');
814 }
815
816nosec:
817 if (p[0] == 'Z') {
818 if (end - p != 1) return -1;
819 return epoch;
820 }
821 else if (p[0] == '+') {
822 if (end - p != 5) return -1;
823 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700824 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 +0200825 }
826 else if (p[0] == '-') {
827 if (end - p != 5) return -1;
828 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700829 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 +0200830 }
831
832 return -1;
833}
834
William Lallemand104a7a62019-10-14 14:14:59 +0200835/*
836 * struct alignment works here such that the key.key is the same as key_data
837 * Do not change the placement of key_data
838 */
839struct certificate_ocsp {
840 struct ebmb_node key;
841 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
842 struct buffer response;
843 long expire;
844};
845
846struct ocsp_cbk_arg {
847 int is_single;
848 int single_kt;
849 union {
850 struct certificate_ocsp *s_ocsp;
851 /*
852 * m_ocsp will have multiple entries dependent on key type
853 * Entry 0 - DSA
854 * Entry 1 - ECDSA
855 * Entry 2 - RSA
856 */
857 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
858 };
859};
860
Emeric Brun1d3865b2014-06-20 15:37:32 +0200861static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200862
863/* This function starts to check if the OCSP response (in DER format) contained
864 * in chunk 'ocsp_response' is valid (else exits on error).
865 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
866 * contained in the OCSP Response and exits on error if no match.
867 * If it's a valid OCSP Response:
868 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
869 * pointed by 'ocsp'.
870 * If 'ocsp' is NULL, the function looks up into the OCSP response's
871 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
872 * from the response) and exits on error if not found. Finally, If an OCSP response is
873 * already present in the container, it will be overwritten.
874 *
875 * Note: OCSP response containing more than one OCSP Single response is not
876 * considered valid.
877 *
878 * Returns 0 on success, 1 in error case.
879 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200880static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
881 struct certificate_ocsp *ocsp,
882 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200883{
884 OCSP_RESPONSE *resp;
885 OCSP_BASICRESP *bs = NULL;
886 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200887 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200888 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200889 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200890 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200891 int reason;
892 int ret = 1;
893
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200894 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
895 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200896 if (!resp) {
897 memprintf(err, "Unable to parse OCSP response");
898 goto out;
899 }
900
901 rc = OCSP_response_status(resp);
902 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
903 memprintf(err, "OCSP response status not successful");
904 goto out;
905 }
906
907 bs = OCSP_response_get1_basic(resp);
908 if (!bs) {
909 memprintf(err, "Failed to get basic response from OCSP Response");
910 goto out;
911 }
912
913 count_sr = OCSP_resp_count(bs);
914 if (count_sr > 1) {
915 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
916 goto out;
917 }
918
919 sr = OCSP_resp_get0(bs, 0);
920 if (!sr) {
921 memprintf(err, "Failed to get OCSP single response");
922 goto out;
923 }
924
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200925 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
926
Emeric Brun4147b2e2014-06-16 18:36:30 +0200927 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200928 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200929 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200930 goto out;
931 }
932
Emeric Brun13a6b482014-06-20 15:44:34 +0200933 if (!nextupd) {
934 memprintf(err, "OCSP single response: missing nextupdate");
935 goto out;
936 }
937
Emeric Brunc8b27b62014-06-19 14:16:17 +0200938 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200939 if (!rc) {
940 memprintf(err, "OCSP single response: no longer valid.");
941 goto out;
942 }
943
944 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200945 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +0200946 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
947 goto out;
948 }
949 }
950
951 if (!ocsp) {
952 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
953 unsigned char *p;
954
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200955 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200956 if (!rc) {
957 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
958 goto out;
959 }
960
961 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
962 memprintf(err, "OCSP single response: Certificate ID too long");
963 goto out;
964 }
965
966 p = key;
967 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200968 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200969 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
970 if (!ocsp) {
971 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
972 goto out;
973 }
974 }
975
976 /* According to comments on "chunk_dup", the
977 previous chunk buffer will be freed */
978 if (!chunk_dup(&ocsp->response, ocsp_response)) {
979 memprintf(err, "OCSP response: Memory allocation error");
980 goto out;
981 }
982
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200983 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
984
Emeric Brun4147b2e2014-06-16 18:36:30 +0200985 ret = 0;
986out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +0100987 ERR_clear_error();
988
Emeric Brun4147b2e2014-06-16 18:36:30 +0200989 if (bs)
990 OCSP_BASICRESP_free(bs);
991
992 if (resp)
993 OCSP_RESPONSE_free(resp);
994
995 return ret;
996}
997/*
998 * External function use to update the OCSP response in the OCSP response's
999 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1000 * to update in DER format.
1001 *
1002 * Returns 0 on success, 1 in error case.
1003 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001004int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001005{
1006 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1007}
1008
William Lallemand4a660132019-10-14 14:51:41 +02001009#endif
1010
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001011#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1012static 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)
1013{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001014 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001015 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001016 struct connection *conn;
1017 int head;
1018 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001019 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001020
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001021 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001022 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001023 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1024
1025 keys = ref->tlskeys;
1026 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001027
1028 if (enc) {
1029 memcpy(key_name, keys[head].name, 16);
1030
1031 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001032 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001033
Emeric Brun9e754772019-01-10 17:51:55 +01001034 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001035
Emeric Brun9e754772019-01-10 17:51:55 +01001036 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1037 goto end;
1038
Willy Tarreau9356dac2019-05-10 09:22:53 +02001039 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001040 ret = 1;
1041 }
1042 else if (ref->key_size_bits == 256 ) {
1043
1044 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1045 goto end;
1046
Willy Tarreau9356dac2019-05-10 09:22:53 +02001047 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001048 ret = 1;
1049 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001050 } else {
1051 for (i = 0; i < TLS_TICKETS_NO; i++) {
1052 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1053 goto found;
1054 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001055 ret = 0;
1056 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001057
Christopher Faulet16f45c82018-02-16 11:23:49 +01001058 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001059 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001060 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 +01001061 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1062 goto end;
1063 /* 2 for key renewal, 1 if current key is still valid */
1064 ret = i ? 2 : 1;
1065 }
1066 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001067 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 +01001068 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1069 goto end;
1070 /* 2 for key renewal, 1 if current key is still valid */
1071 ret = i ? 2 : 1;
1072 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001073 }
Emeric Brun9e754772019-01-10 17:51:55 +01001074
Christopher Faulet16f45c82018-02-16 11:23:49 +01001075 end:
1076 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1077 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001078}
1079
1080struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1081{
1082 struct tls_keys_ref *ref;
1083
1084 list_for_each_entry(ref, &tlskeys_reference, list)
1085 if (ref->filename && strcmp(filename, ref->filename) == 0)
1086 return ref;
1087 return NULL;
1088}
1089
1090struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1091{
1092 struct tls_keys_ref *ref;
1093
1094 list_for_each_entry(ref, &tlskeys_reference, list)
1095 if (ref->unique_id == unique_id)
1096 return ref;
1097 return NULL;
1098}
1099
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001100/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001101 * match existing ones, this function returns -1
1102 * else it returns 0 on success.
1103 */
1104int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001105 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001106{
Emeric Brun9e754772019-01-10 17:51:55 +01001107 if (ref->key_size_bits == 128) {
1108 if (tlskey->data != sizeof(struct tls_sess_key_128))
1109 return -1;
1110 }
1111 else if (ref->key_size_bits == 256) {
1112 if (tlskey->data != sizeof(struct tls_sess_key_256))
1113 return -1;
1114 }
1115 else
1116 return -1;
1117
Christopher Faulet16f45c82018-02-16 11:23:49 +01001118 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001119 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1120 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001121 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1122 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001123
1124 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001125}
1126
Willy Tarreau83061a82018-07-13 11:56:34 +02001127int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001128{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001129 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1130
1131 if(!ref) {
1132 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1133 return 1;
1134 }
Emeric Brun9e754772019-01-10 17:51:55 +01001135 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1136 memprintf(err, "Invalid key size");
1137 return 1;
1138 }
1139
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001140 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001141}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001142
1143/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001144 * automatic ids. It's called just after the basic checks. It returns
1145 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001146 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001147static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001148{
1149 int i = 0;
1150 struct tls_keys_ref *ref, *ref2, *ref3;
1151 struct list tkr = LIST_HEAD_INIT(tkr);
1152
1153 list_for_each_entry(ref, &tlskeys_reference, list) {
1154 if (ref->unique_id == -1) {
1155 /* Look for the first free id. */
1156 while (1) {
1157 list_for_each_entry(ref2, &tlskeys_reference, list) {
1158 if (ref2->unique_id == i) {
1159 i++;
1160 break;
1161 }
1162 }
1163 if (&ref2->list == &tlskeys_reference)
1164 break;
1165 }
1166
1167 /* Uses the unique id and increment it for the next entry. */
1168 ref->unique_id = i;
1169 i++;
1170 }
1171 }
1172
1173 /* This sort the reference list by id. */
1174 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
1175 LIST_DEL(&ref->list);
1176 list_for_each_entry(ref3, &tkr, list) {
1177 if (ref->unique_id < ref3->unique_id) {
1178 LIST_ADDQ(&ref3->list, &ref->list);
1179 break;
1180 }
1181 }
1182 if (&ref3->list == &tkr)
1183 LIST_ADDQ(&tkr, &ref->list);
1184 }
1185
1186 /* swap root */
1187 LIST_ADD(&tkr, &tlskeys_reference);
1188 LIST_DEL(&tkr);
Willy Tarreaud1c57502016-12-22 22:46:15 +01001189 return 0;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001190}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001191#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1192
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001193#ifndef OPENSSL_NO_OCSP
yanbzhube2774d2015-12-10 15:07:30 -05001194int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1195{
1196 switch (evp_keytype) {
1197 case EVP_PKEY_RSA:
1198 return 2;
1199 case EVP_PKEY_DSA:
1200 return 0;
1201 case EVP_PKEY_EC:
1202 return 1;
1203 }
1204
1205 return -1;
1206}
1207
Emeric Brun4147b2e2014-06-16 18:36:30 +02001208/*
1209 * Callback used to set OCSP status extension content in server hello.
1210 */
1211int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1212{
yanbzhube2774d2015-12-10 15:07:30 -05001213 struct certificate_ocsp *ocsp;
1214 struct ocsp_cbk_arg *ocsp_arg;
1215 char *ssl_buf;
1216 EVP_PKEY *ssl_pkey;
1217 int key_type;
1218 int index;
1219
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001220 ocsp_arg = arg;
yanbzhube2774d2015-12-10 15:07:30 -05001221
1222 ssl_pkey = SSL_get_privatekey(ssl);
1223 if (!ssl_pkey)
1224 return SSL_TLSEXT_ERR_NOACK;
1225
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001226 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001227
1228 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1229 ocsp = ocsp_arg->s_ocsp;
1230 else {
1231 /* For multiple certs per context, we have to find the correct OCSP response based on
1232 * the certificate type
1233 */
1234 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1235
1236 if (index < 0)
1237 return SSL_TLSEXT_ERR_NOACK;
1238
1239 ocsp = ocsp_arg->m_ocsp[index];
1240
1241 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001242
1243 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001244 !ocsp->response.area ||
1245 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001246 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001247 return SSL_TLSEXT_ERR_NOACK;
1248
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001249 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001250 if (!ssl_buf)
1251 return SSL_TLSEXT_ERR_NOACK;
1252
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001253 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1254 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001255
1256 return SSL_TLSEXT_ERR_OK;
1257}
1258
William Lallemand4a660132019-10-14 14:51:41 +02001259#endif
1260
1261#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001262/*
1263 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001264 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1265 * status extension, the issuer's certificate is mandatory. It should be
1266 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001267 *
William Lallemand246c0242019-10-11 08:59:13 +02001268 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1269 * OCSP response. If file is empty or content is not a valid OCSP response,
1270 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1271 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001272 *
1273 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001274 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001275 */
William Lallemand4a660132019-10-14 14:51:41 +02001276#ifndef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001277static 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 +02001278{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001279 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001280 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001281 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001282 struct certificate_ocsp *ocsp = NULL, *iocsp;
1283 char *warn = NULL;
1284 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001285 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001286
Emeric Brun4147b2e2014-06-16 18:36:30 +02001287
William Lallemand246c0242019-10-11 08:59:13 +02001288 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001289 if (!x)
1290 goto out;
1291
William Lallemand246c0242019-10-11 08:59:13 +02001292 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001293 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1294 if (chain) {
1295 /* check if one of the certificate of the chain is the issuer */
1296 for (i = 0; i < sk_X509_num(chain); i++) {
1297 X509 *ti = sk_X509_value(chain, i);
1298 if (X509_check_issued(ti, x) == X509_V_OK) {
1299 issuer = ti;
1300 break;
1301 }
1302 }
1303 }
William Lallemand246c0242019-10-11 08:59:13 +02001304 if (!issuer)
1305 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001306
1307 cid = OCSP_cert_to_id(0, x, issuer);
1308 if (!cid)
1309 goto out;
1310
1311 i = i2d_OCSP_CERTID(cid, NULL);
1312 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1313 goto out;
1314
Vincent Bernat02779b62016-04-03 13:48:43 +02001315 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001316 if (!ocsp)
1317 goto out;
1318
1319 p = ocsp->key_data;
1320 i2d_OCSP_CERTID(cid, &p);
1321
1322 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1323 if (iocsp == ocsp)
1324 ocsp = NULL;
1325
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001326#ifndef SSL_CTX_get_tlsext_status_cb
1327# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1328 *cb = (void (*) (void))ctx->tlsext_status_cb;
1329#endif
1330 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1331
1332 if (!callback) {
Vincent Bernat02779b62016-04-03 13:48:43 +02001333 struct ocsp_cbk_arg *cb_arg = calloc(1, sizeof(*cb_arg));
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001334 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001335
1336 cb_arg->is_single = 1;
1337 cb_arg->s_ocsp = iocsp;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001338
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001339 pkey = X509_get_pubkey(x);
1340 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1341 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001342
1343 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
1344 SSL_CTX_set_tlsext_status_arg(ctx, cb_arg);
1345 } else {
1346 /*
1347 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1348 * Update that cb_arg with the new cert's staple
1349 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001350 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001351 struct certificate_ocsp *tmp_ocsp;
1352 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001353 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001354 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001355
1356#ifdef SSL_CTX_get_tlsext_status_arg
1357 SSL_CTX_ctrl(ctx, SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG, 0, &cb_arg);
1358#else
1359 cb_arg = ctx->tlsext_status_arg;
1360#endif
yanbzhube2774d2015-12-10 15:07:30 -05001361
1362 /*
1363 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1364 * the order of operations below matter, take care when changing it
1365 */
1366 tmp_ocsp = cb_arg->s_ocsp;
1367 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1368 cb_arg->s_ocsp = NULL;
1369 cb_arg->m_ocsp[index] = tmp_ocsp;
1370 cb_arg->is_single = 0;
1371 cb_arg->single_kt = 0;
1372
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001373 pkey = X509_get_pubkey(x);
1374 key_type = EVP_PKEY_base_id(pkey);
1375 EVP_PKEY_free(pkey);
1376
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001377 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
yanbzhube2774d2015-12-10 15:07:30 -05001378 if (index >= 0 && !cb_arg->m_ocsp[index])
1379 cb_arg->m_ocsp[index] = iocsp;
1380
1381 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001382
1383 ret = 0;
1384
1385 warn = NULL;
William Lallemand246c0242019-10-11 08:59:13 +02001386 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, ocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001387 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001388 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001389 }
1390
1391out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001392 if (cid)
1393 OCSP_CERTID_free(cid);
1394
1395 if (ocsp)
1396 free(ocsp);
1397
1398 if (warn)
1399 free(warn);
1400
Emeric Brun4147b2e2014-06-16 18:36:30 +02001401 return ret;
1402}
William Lallemand4a660132019-10-14 14:51:41 +02001403#else /* OPENSSL_IS_BORINGSSL */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001404static 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 +02001405{
William Lallemand4a660132019-10-14 14:51:41 +02001406 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 +02001407}
1408#endif
1409
William Lallemand4a660132019-10-14 14:51:41 +02001410#endif
1411
1412
Willy Tarreau5db847a2019-05-09 14:13:35 +02001413#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001414
1415#define CT_EXTENSION_TYPE 18
1416
William Lallemand03c331c2020-05-13 10:10:01 +02001417int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001418
1419int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1420{
Willy Tarreau83061a82018-07-13 11:56:34 +02001421 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001422
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001423 *out = (unsigned char *) sctl->area;
1424 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001425
1426 return 1;
1427}
1428
1429int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1430{
1431 return 1;
1432}
1433
William Lallemanda17f4112019-10-10 15:16:44 +02001434static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001435{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001436 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001437
William Lallemanda17f4112019-10-10 15:16:44 +02001438 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 +01001439 goto out;
1440
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001441 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1442
1443 ret = 0;
1444
1445out:
1446 return ret;
1447}
1448
1449#endif
1450
Emeric Brune1f38db2012-09-03 20:36:47 +02001451void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1452{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001453 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001454 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001455 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001456 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001457
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001458#ifndef SSL_OP_NO_RENEGOTIATION
1459 /* Please note that BoringSSL defines this macro to zero so don't
1460 * change this to #if and do not assign a default value to this macro!
1461 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001462 if (where & SSL_CB_HANDSHAKE_START) {
1463 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001464 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 +02001465 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001466 conn->err_code = CO_ER_SSL_RENEG;
1467 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001468 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001469#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001470
1471 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001472 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001473 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001474 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001475 consider that the buffering was activated,
1476 so we rise the output buffer size from 4k
1477 to 16k */
1478 write_bio = SSL_get_wbio(ssl);
1479 if (write_bio != SSL_get_rbio(ssl)) {
1480 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001481 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001482 }
1483 }
1484 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001485}
1486
Emeric Brune64aef12012-09-21 13:15:06 +02001487/* Callback is called for each certificate of the chain during a verify
1488 ok is set to 1 if preverify detect no error on current certificate.
1489 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001490int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001491{
1492 SSL *ssl;
1493 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001494 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001495 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001496
1497 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001498 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001499
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001500 ctx = conn->xprt_ctx;
1501
1502 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001503
Emeric Brun81c00f02012-09-21 14:31:21 +02001504 if (ok) /* no errors */
1505 return ok;
1506
1507 depth = X509_STORE_CTX_get_error_depth(x_store);
1508 err = X509_STORE_CTX_get_error(x_store);
1509
1510 /* check if CA error needs to be ignored */
1511 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001512 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1513 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1514 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001515 }
1516
Willy Tarreau731248f2020-02-04 14:02:02 +01001517 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001518 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001519 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001520 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001521 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001522
Willy Tarreau20879a02012-12-03 16:32:10 +01001523 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001524 return 0;
1525 }
1526
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001527 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1528 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001529
Emeric Brun81c00f02012-09-21 14:31:21 +02001530 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001531 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001532 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001533 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001534 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001535 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001536
Willy Tarreau20879a02012-12-03 16:32:10 +01001537 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001538 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001539}
1540
Dragan Dosen9ac98092020-05-11 15:51:45 +02001541#ifdef TLS1_RT_HEARTBEAT
1542static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1543 int content_type, const void *buf, size_t len,
1544 SSL *ssl)
1545{
1546 /* test heartbeat received (write_p is set to 0
1547 for a received record) */
1548 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1549 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1550 const unsigned char *p = buf;
1551 unsigned int payload;
1552
1553 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1554
1555 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1556 if (*p != TLS1_HB_REQUEST)
1557 return;
1558
1559 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1560 goto kill_it;
1561
1562 payload = (p[1] * 256) + p[2];
1563 if (3 + payload + 16 <= len)
1564 return; /* OK no problem */
1565 kill_it:
1566 /* We have a clear heartbleed attack (CVE-2014-0160), the
1567 * advertised payload is larger than the advertised packet
1568 * length, so we have garbage in the buffer between the
1569 * payload and the end of the buffer (p+len). We can't know
1570 * if the SSL stack is patched, and we don't know if we can
1571 * safely wipe out the area between p+3+len and payload.
1572 * So instead, we prevent the response from being sent by
1573 * setting the max_send_fragment to 0 and we report an SSL
1574 * error, which will kill this connection. It will be reported
1575 * above as SSL_ERROR_SSL while an other handshake failure with
1576 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1577 */
1578 ssl->max_send_fragment = 0;
1579 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1580 }
1581}
1582#endif
1583
1584static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1585 int content_type, const void *buf, size_t len,
1586 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001587{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001588 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001589 unsigned char *msg;
1590 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001591 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001592
1593 /* This function is called for "from client" and "to server"
1594 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001595 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001596 */
1597
1598 /* "write_p" is set to 0 is the bytes are received messages,
1599 * otherwise it is set to 1.
1600 */
1601 if (write_p != 0)
1602 return;
1603
1604 /* content_type contains the type of message received or sent
1605 * according with the SSL/TLS protocol spec. This message is
1606 * encoded with one byte. The value 256 (two bytes) is used
1607 * for designing the SSL/TLS record layer. According with the
1608 * rfc6101, the expected message (other than 256) are:
1609 * - change_cipher_spec(20)
1610 * - alert(21)
1611 * - handshake(22)
1612 * - application_data(23)
1613 * - (255)
1614 * We are interessed by the handshake and specially the client
1615 * hello.
1616 */
1617 if (content_type != 22)
1618 return;
1619
1620 /* The message length is at least 4 bytes, containing the
1621 * message type and the message length.
1622 */
1623 if (len < 4)
1624 return;
1625
1626 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001627 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001628 * - hello_request(0)
1629 * - client_hello(1)
1630 * - server_hello(2)
1631 * - certificate(11)
1632 * - server_key_exchange (12)
1633 * - certificate_request(13)
1634 * - server_hello_done(14)
1635 * We are interested by the client hello.
1636 */
1637 msg = (unsigned char *)buf;
1638 if (msg[0] != 1)
1639 return;
1640
1641 /* Next three bytes are the length of the message. The total length
1642 * must be this decoded length + 4. If the length given as argument
1643 * is not the same, we abort the protocol dissector.
1644 */
1645 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1646 if (len < rec_len + 4)
1647 return;
1648 msg += 4;
1649 end = msg + rec_len;
1650 if (end < msg)
1651 return;
1652
1653 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1654 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001655 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1656 */
1657 msg += 1 + 1 + 4 + 28;
1658 if (msg > end)
1659 return;
1660
1661 /* Next, is session id:
1662 * if present, we have to jump by length + 1 for the size information
1663 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001664 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001665 if (msg[0] > 0)
1666 msg += msg[0];
1667 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001668 if (msg > end)
1669 return;
1670
1671 /* Next two bytes are the ciphersuite length. */
1672 if (msg + 2 > end)
1673 return;
1674 rec_len = (msg[0] << 8) + msg[1];
1675 msg += 2;
1676 if (msg + rec_len > end || msg + rec_len < msg)
1677 return;
1678
Willy Tarreaubafbe012017-11-24 17:34:44 +01001679 capture = pool_alloc_dirty(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001680 if (!capture)
1681 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001682 /* Compute the xxh64 of the ciphersuite. */
1683 capture->xxh64 = XXH64(msg, rec_len, 0);
1684
1685 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001686 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1687 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001688 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001689
1690 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001691}
1692
Emeric Brun29f037d2014-04-25 19:05:36 +02001693/* Callback is called for ssl protocol analyse */
1694void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1695{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001696 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1697 struct ssl_sock_msg_callback *cbk;
1698
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001699 /* Try to call all callback functions that were registered by using
1700 * ssl_sock_register_msg_callback().
1701 */
1702 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1703 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1704 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001705}
1706
Bernard Spil13c53f82018-02-15 13:34:58 +01001707#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001708static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1709 const unsigned char *in, unsigned int inlen,
1710 void *arg)
1711{
1712 struct server *srv = arg;
1713
1714 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1715 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1716 return SSL_TLSEXT_ERR_OK;
1717 return SSL_TLSEXT_ERR_NOACK;
1718}
1719#endif
1720
1721#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001722/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001723 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001724 */
1725static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1726 unsigned int *len, void *arg)
1727{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001728 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001729
1730 *data = (const unsigned char *)conf->npn_str;
1731 *len = conf->npn_len;
1732 return SSL_TLSEXT_ERR_OK;
1733}
1734#endif
1735
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001736#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001737/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001738 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001739 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001740static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1741 unsigned char *outlen,
1742 const unsigned char *server,
1743 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001744{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001745 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001746
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001747 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1748 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1749 return SSL_TLSEXT_ERR_NOACK;
1750 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001751 return SSL_TLSEXT_ERR_OK;
1752}
1753#endif
1754
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001755#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001756#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001757
Christopher Faulet30548802015-06-11 13:39:32 +02001758/* Create a X509 certificate with the specified servername and serial. This
1759 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001760static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001761ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001762{
Christopher Faulet7969a332015-10-09 11:15:03 +02001763 X509 *cacert = bind_conf->ca_sign_cert;
1764 EVP_PKEY *capkey = bind_conf->ca_sign_pkey;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001765 SSL_CTX *ssl_ctx = NULL;
1766 X509 *newcrt = NULL;
1767 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001768 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001769 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001770 X509_NAME *name;
1771 const EVP_MD *digest;
1772 X509V3_CTX ctx;
1773 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001774 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001775
Christopher Faulet48a83322017-07-28 16:56:09 +02001776 /* Get the private key of the default certificate and use it */
Willy Tarreau5db847a2019-05-09 14:13:35 +02001777#if (HA_OPENSSL_VERSION_NUMBER >= 0x10002000L)
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001778 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1779#else
1780 tmp_ssl = SSL_new(bind_conf->default_ctx);
1781 if (tmp_ssl)
1782 pkey = SSL_get_privatekey(tmp_ssl);
1783#endif
1784 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001785 goto mkcert_error;
1786
1787 /* Create the certificate */
1788 if (!(newcrt = X509_new()))
1789 goto mkcert_error;
1790
1791 /* Set version number for the certificate (X509v3) and the serial
1792 * number */
1793 if (X509_set_version(newcrt, 2L) != 1)
1794 goto mkcert_error;
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01001795 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001796
1797 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001798 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1799 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001800 goto mkcert_error;
1801
1802 /* set public key in the certificate */
1803 if (X509_set_pubkey(newcrt, pkey) != 1)
1804 goto mkcert_error;
1805
1806 /* Set issuer name from the CA */
1807 if (!(name = X509_get_subject_name(cacert)))
1808 goto mkcert_error;
1809 if (X509_set_issuer_name(newcrt, name) != 1)
1810 goto mkcert_error;
1811
1812 /* Set the subject name using the same, but the CN */
1813 name = X509_NAME_dup(name);
1814 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1815 (const unsigned char *)servername,
1816 -1, -1, 0) != 1) {
1817 X509_NAME_free(name);
1818 goto mkcert_error;
1819 }
1820 if (X509_set_subject_name(newcrt, name) != 1) {
1821 X509_NAME_free(name);
1822 goto mkcert_error;
1823 }
1824 X509_NAME_free(name);
1825
1826 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001827 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001828 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1829 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1830 X509_EXTENSION *ext;
1831
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001832 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001833 goto mkcert_error;
1834 if (!X509_add_ext(newcrt, ext, -1)) {
1835 X509_EXTENSION_free(ext);
1836 goto mkcert_error;
1837 }
1838 X509_EXTENSION_free(ext);
1839 }
1840
1841 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001842
1843 key_type = EVP_PKEY_base_id(capkey);
1844
1845 if (key_type == EVP_PKEY_DSA)
1846 digest = EVP_sha1();
1847 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001848 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001849 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001850 digest = EVP_sha256();
1851 else {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02001852#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000000fL) && !defined(OPENSSL_IS_BORINGSSL)
Christopher Faulet7969a332015-10-09 11:15:03 +02001853 int nid;
1854
1855 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1856 goto mkcert_error;
1857 if (!(digest = EVP_get_digestbynid(nid)))
1858 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02001859#else
1860 goto mkcert_error;
1861#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02001862 }
1863
Christopher Faulet31af49d2015-06-09 17:29:50 +02001864 if (!(X509_sign(newcrt, capkey, digest)))
1865 goto mkcert_error;
1866
1867 /* Create and set the new SSL_CTX */
1868 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
1869 goto mkcert_error;
1870 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1871 goto mkcert_error;
1872 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
1873 goto mkcert_error;
1874 if (!SSL_CTX_check_private_key(ssl_ctx))
1875 goto mkcert_error;
1876
1877 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02001878
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01001879#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001880 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01001881#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001882#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
1883 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001884 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001885 EC_KEY *ecc;
1886 int nid;
1887
1888 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
1889 goto end;
1890 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
1891 goto end;
1892 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
1893 EC_KEY_free(ecc);
1894 }
1895#endif
1896 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02001897 return ssl_ctx;
1898
1899 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001900 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001901 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001902 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
1903 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001904 return NULL;
1905}
1906
Christopher Faulet7969a332015-10-09 11:15:03 +02001907SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001908ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02001909{
Willy Tarreau07d94e42018-09-20 10:57:52 +02001910 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01001911 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001912
Olivier Houchard66ab4982019-02-26 18:37:15 +01001913 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02001914}
1915
Christopher Faulet30548802015-06-11 13:39:32 +02001916/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02001917 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02001918SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02001919ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02001920{
1921 struct lru64 *lru = NULL;
1922
1923 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001924 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001925 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02001926 if (lru && lru->domain) {
1927 if (ssl)
1928 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001929 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02001930 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02001931 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001932 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02001933 }
1934 return NULL;
1935}
1936
Emeric Brun821bb9b2017-06-15 16:37:39 +02001937/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
1938 * function is not thread-safe, it should only be used to check if a certificate
1939 * exists in the lru cache (with no warranty it will not be removed by another
1940 * thread). It is kept for backward compatibility. */
1941SSL_CTX *
1942ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
1943{
1944 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
1945}
1946
Christopher Fauletd2cab922015-07-28 16:03:47 +02001947/* Set a certificate int the LRU cache used to store generated
1948 * certificate. Return 0 on success, otherwise -1 */
1949int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001950ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02001951{
1952 struct lru64 *lru = NULL;
1953
1954 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001955 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001956 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02001957 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001958 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001959 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02001960 }
Christopher Faulet30548802015-06-11 13:39:32 +02001961 if (lru->domain && lru->data)
1962 lru->free((SSL_CTX *)lru->data);
Christopher Faulet7969a332015-10-09 11:15:03 +02001963 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001964 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001965 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02001966 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02001967 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02001968}
1969
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001970/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02001971unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001972ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02001973{
1974 return XXH32(data, len, ssl_ctx_lru_seed);
1975}
1976
Willy Tarreau2f63ef42015-10-20 15:16:01 +02001977/* Generate a cert and immediately assign it to the SSL session so that the cert's
1978 * refcount is maintained regardless of the cert's presence in the LRU cache.
1979 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02001980static int
Christopher Faulet7969a332015-10-09 11:15:03 +02001981ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001982{
1983 X509 *cacert = bind_conf->ca_sign_cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001984 SSL_CTX *ssl_ctx = NULL;
1985 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001986 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001987
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001988 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001989 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001990 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001991 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001992 if (lru && lru->domain)
1993 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02001994 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001995 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001996 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001997 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02001998 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001999 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002000 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002001 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002002 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002003 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002004 SSL_set_SSL_CTX(ssl, ssl_ctx);
2005 /* No LRU cache, this CTX will be released as soon as the session dies */
2006 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002007 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002008 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002009 return 0;
2010}
2011static int
2012ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2013{
2014 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002015 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002016
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002017 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002018 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002019 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002020 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002021 }
2022 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002023}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002024#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002025
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002026#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002027
2028static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002029{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002030#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002031 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002032 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2033#endif
2034}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002035static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2036 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002037 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2038}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002039static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002040#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002041 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002042 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2043#endif
2044}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002045static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002046#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002047 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002048 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2049#endif
2050}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002051/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002052static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2053/* Unusable in this context. */
2054static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2055static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2056static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2057static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2058static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002059#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002060
2061static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2062 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002063 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2064}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002065static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2066 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2067 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2068}
2069static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2070 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002071 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2072}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002073static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2074 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2075 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2076}
2077static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2078 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002079 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2080}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002081static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2082 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2083 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2084}
2085static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2086 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002087 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2088}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002089static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2090 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2091 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2092}
2093static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002094#if SSL_OP_NO_TLSv1_3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002095 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002096 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2097#endif
2098}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002099static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
2100#if SSL_OP_NO_TLSv1_3
2101 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2102 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002103#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002104}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002105#endif
2106static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2107static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002108
William Lallemand7fd8b452020-05-07 15:20:43 +02002109struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002110 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2111 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2112 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2113 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2114 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2115 {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 +02002116};
2117
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002118static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2119{
2120 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2121 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2122 SSL_set_SSL_CTX(ssl, ctx);
2123}
2124
Willy Tarreau5db847a2019-05-09 14:13:35 +02002125#if ((HA_OPENSSL_VERSION_NUMBER >= 0x10101000L) || defined(OPENSSL_IS_BORINGSSL))
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002126
2127static int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
2128{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002129 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002130 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002131
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002132 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2133 return SSL_TLSEXT_ERR_OK;
2134 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002135}
2136
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002137#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002138static int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
2139{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002140 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002141#else
2142static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
2143{
2144#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002145 struct connection *conn;
2146 struct bind_conf *s;
2147 const uint8_t *extension_data;
2148 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002149 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002150
2151 char *wildp = NULL;
2152 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002153 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002154 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002155 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002156 int i;
2157
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002158 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002159 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002160
Olivier Houchard9679ac92017-10-27 14:58:08 +02002161 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002162 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002163#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002164 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2165 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002166#else
2167 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2168#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002169 /*
2170 * The server_name extension was given too much extensibility when it
2171 * was written, so parsing the normal case is a bit complex.
2172 */
2173 size_t len;
2174 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002175 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002176 /* Extract the length of the supplied list of names. */
2177 len = (*extension_data++) << 8;
2178 len |= *extension_data++;
2179 if (len + 2 != extension_len)
2180 goto abort;
2181 /*
2182 * The list in practice only has a single element, so we only consider
2183 * the first one.
2184 */
2185 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2186 goto abort;
2187 extension_len = len - 1;
2188 /* Now we can finally pull out the byte array with the actual hostname. */
2189 if (extension_len <= 2)
2190 goto abort;
2191 len = (*extension_data++) << 8;
2192 len |= *extension_data++;
2193 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2194 || memchr(extension_data, 0, len) != NULL)
2195 goto abort;
2196 servername = extension_data;
2197 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002198 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002199#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2200 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002201 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002202 }
2203#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002204 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002205 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002206 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002207 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002208 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002209 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002210 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002211 goto abort;
2212 }
2213
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002214 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002215#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002216 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002217#else
2218 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2219#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002220 uint8_t sign;
2221 size_t len;
2222 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002223 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002224 len = (*extension_data++) << 8;
2225 len |= *extension_data++;
2226 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002227 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002228 if (len % 2 != 0)
2229 goto abort;
2230 for (; len > 0; len -= 2) {
2231 extension_data++; /* hash */
2232 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002233 switch (sign) {
2234 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002235 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002236 break;
2237 case TLSEXT_signature_ecdsa:
2238 has_ecdsa_sig = 1;
2239 break;
2240 default:
2241 continue;
2242 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002243 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002244 break;
2245 }
2246 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002247 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002248 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002249 }
2250 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002251 const SSL_CIPHER *cipher;
2252 size_t len;
2253 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002254 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002255#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002256 len = ctx->cipher_suites_len;
2257 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002258#else
2259 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2260#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002261 if (len % 2 != 0)
2262 goto abort;
2263 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002264#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002265 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002266 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002267#else
2268 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2269#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002270 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002271 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002272 break;
2273 }
2274 }
2275 }
2276
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002277 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002278 trash.area[i] = tolower(servername[i]);
2279 if (!wildp && (trash.area[i] == '.'))
2280 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002281 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002282 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002283
William Lallemand150bfa82019-09-19 17:12:49 +02002284 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002285
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002286 for (i = 0; i < 2; i++) {
2287 if (i == 0) /* lookup in full qualified names */
2288 node = ebst_lookup(&s->sni_ctx, trash.area);
2289 else if (i == 1 && wildp) /* lookup in wildcards names */
2290 node = ebst_lookup(&s->sni_w_ctx, wildp);
2291 else
2292 break;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002293 for (n = node; n; n = ebmb_next_dup(n)) {
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002294 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002295 if (!container_of(n, struct sni_ctx, name)->neg) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002296 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002297 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002298 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002299 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002300 break;
2301 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002302 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002303 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002304 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002305 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002306 if (!node_anonymous)
2307 node_anonymous = n;
2308 break;
2309 }
2310 }
2311 }
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002312 /* select by key_signature priority order */
2313 node = (has_ecdsa_sig && node_ecdsa) ? node_ecdsa
2314 : ((has_rsa_sig && node_rsa) ? node_rsa
2315 : (node_anonymous ? node_anonymous
2316 : (node_ecdsa ? node_ecdsa /* no ecdsa signature case (< TLSv1.2) */
2317 : node_rsa /* no rsa signature case (far far away) */
2318 )));
2319 if (node) {
2320 /* switch ctx */
2321 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2322 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
Olivier Houchard35a63cc2017-11-02 19:04:38 +01002323 if (conf) {
2324 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2325 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2326 if (conf->early_data)
2327 allow_early = 1;
2328 }
William Lallemand02010472019-10-18 11:02:19 +02002329 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchard35a63cc2017-11-02 19:04:38 +01002330 goto allow_early;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002331 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002332 }
William Lallemand150bfa82019-09-19 17:12:49 +02002333
William Lallemand02010472019-10-18 11:02:19 +02002334 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002335#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002336 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002337 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002338 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002339 }
2340#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002341 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002342 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002343 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002344 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002345 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002346 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02002347allow_early:
2348#ifdef OPENSSL_IS_BORINGSSL
2349 if (allow_early)
2350 SSL_set_early_data_enabled(ssl, 1);
2351#else
2352 if (!allow_early)
2353 SSL_set_max_early_data(ssl, 0);
2354#endif
2355 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002356 abort:
2357 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2358 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002359#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002360 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002361#else
2362 *al = SSL_AD_UNRECOGNIZED_NAME;
2363 return 0;
2364#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002365}
2366
2367#else /* OPENSSL_IS_BORINGSSL */
2368
Emeric Brunfc0421f2012-09-07 17:30:07 +02002369/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2370 * warning when no match is found, which implies the default (first) cert
2371 * will keep being used.
2372 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002373static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002374{
2375 const char *servername;
2376 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002377 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002378 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002379 int i;
2380 (void)al; /* shut gcc stupid warning */
2381
2382 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002383 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002384#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002385 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2386 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002387#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002388 if (s->strict_sni)
2389 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002390 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002391 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002392 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002393 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002394 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002395
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002396 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002397 if (!servername[i])
2398 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002399 trash.area[i] = tolower(servername[i]);
2400 if (!wildp && (trash.area[i] == '.'))
2401 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002402 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002403 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002404
William Lallemand150bfa82019-09-19 17:12:49 +02002405 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002406 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002407 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002408 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2409 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002410 if (!container_of(n, struct sni_ctx, name)->neg) {
2411 node = n;
2412 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002413 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002414 }
2415 if (!node && wildp) {
2416 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002417 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2418 /* lookup a not neg filter */
2419 if (!container_of(n, struct sni_ctx, name)->neg) {
2420 node = n;
2421 break;
2422 }
2423 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002424 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002425 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002426#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002427 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2428 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002429 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002430 return SSL_TLSEXT_ERR_OK;
2431 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002432#endif
William Lallemand21724f02019-11-04 17:56:13 +01002433 if (s->strict_sni) {
2434 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002435 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002436 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002437 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002438 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002439 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002440 }
2441
2442 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002443 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002444 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002445 return SSL_TLSEXT_ERR_OK;
2446}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002447#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002448#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2449
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002450#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002451
2452static DH * ssl_get_dh_1024(void)
2453{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002454 static unsigned char dh1024_p[]={
2455 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2456 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2457 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2458 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2459 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2460 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2461 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2462 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2463 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2464 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2465 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2466 };
2467 static unsigned char dh1024_g[]={
2468 0x02,
2469 };
2470
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002471 BIGNUM *p;
2472 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002473 DH *dh = DH_new();
2474 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002475 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2476 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002477
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002478 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002479 DH_free(dh);
2480 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002481 } else {
2482 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002483 }
2484 }
2485 return dh;
2486}
2487
2488static DH *ssl_get_dh_2048(void)
2489{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002490 static unsigned char dh2048_p[]={
2491 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2492 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2493 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2494 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2495 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2496 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2497 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2498 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2499 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2500 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2501 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2502 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2503 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2504 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2505 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2506 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2507 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2508 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2509 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2510 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2511 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2512 0xB7,0x1F,0x77,0xF3,
2513 };
2514 static unsigned char dh2048_g[]={
2515 0x02,
2516 };
2517
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002518 BIGNUM *p;
2519 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002520 DH *dh = DH_new();
2521 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002522 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2523 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002524
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002525 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002526 DH_free(dh);
2527 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002528 } else {
2529 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002530 }
2531 }
2532 return dh;
2533}
2534
2535static DH *ssl_get_dh_4096(void)
2536{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002537 static unsigned char dh4096_p[]={
2538 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2539 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2540 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2541 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2542 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2543 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2544 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2545 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2546 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2547 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2548 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2549 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2550 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2551 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2552 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2553 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2554 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2555 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2556 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2557 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2558 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2559 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2560 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2561 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2562 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2563 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2564 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2565 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2566 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2567 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2568 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2569 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2570 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2571 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2572 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2573 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2574 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2575 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2576 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2577 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2578 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2579 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2580 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002581 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002582 static unsigned char dh4096_g[]={
2583 0x02,
2584 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002585
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002586 BIGNUM *p;
2587 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002588 DH *dh = DH_new();
2589 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002590 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2591 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002592
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002593 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002594 DH_free(dh);
2595 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002596 } else {
2597 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002598 }
2599 }
2600 return dh;
2601}
2602
2603/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002604 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002605static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2606{
2607 DH *dh = NULL;
2608 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002609 int type;
2610
2611 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002612
2613 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2614 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2615 */
2616 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2617 keylen = EVP_PKEY_bits(pkey);
2618 }
2619
Willy Tarreauef934602016-12-22 23:12:01 +01002620 if (keylen > global_ssl.default_dh_param) {
2621 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002622 }
2623
Remi Gacogned3a341a2015-05-29 16:26:17 +02002624 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002625 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002626 }
2627 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002628 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002629 }
2630 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002631 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002632 }
2633
2634 return dh;
2635}
2636
Remi Gacogne47783ef2015-05-29 15:53:22 +02002637static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002638{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002639 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002640 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002641
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002642 if (in == NULL)
2643 goto end;
2644
Remi Gacogne47783ef2015-05-29 15:53:22 +02002645 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002646 goto end;
2647
Remi Gacogne47783ef2015-05-29 15:53:22 +02002648 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2649
2650end:
2651 if (in)
2652 BIO_free(in);
2653
Emeric Brune1b4ed42018-08-16 15:14:12 +02002654 ERR_clear_error();
2655
Remi Gacogne47783ef2015-05-29 15:53:22 +02002656 return dh;
2657}
2658
2659int ssl_sock_load_global_dh_param_from_file(const char *filename)
2660{
2661 global_dh = ssl_sock_get_dh_from_file(filename);
2662
2663 if (global_dh) {
2664 return 0;
2665 }
2666
2667 return -1;
2668}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002669#endif
2670
William Lallemand9117de92019-10-04 00:29:42 +02002671/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002672static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002673 struct bind_conf *s, struct ssl_bind_conf *conf,
2674 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002675{
2676 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002677 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002678
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002679 if (*name == '!') {
2680 neg = 1;
2681 name++;
2682 }
2683 if (*name == '*') {
2684 wild = 1;
2685 name++;
2686 }
2687 /* !* filter is a nop */
2688 if (neg && wild)
2689 return order;
2690 if (*name) {
2691 int j, len;
2692 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002693 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002694 trash.area[j] = tolower(name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002695 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002696 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002697 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002698
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002699 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002700 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002701 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002702 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002703 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002704 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002705 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002706 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002707 sc->order = order++;
2708 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002709 sc->wild = wild;
2710 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002711 sc->ckch_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02002712 LIST_ADDQ(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002713 }
2714 return order;
2715}
2716
William Lallemand6af03992019-07-23 15:00:54 +02002717/*
William Lallemand1d29c742019-10-04 00:53:29 +02002718 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2719 * This function can't return an error.
2720 *
2721 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2722 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002723void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002724{
2725
2726 struct sni_ctx *sc0, *sc0b, *sc1;
2727 struct ebmb_node *node;
William Lallemand21724f02019-11-04 17:56:13 +01002728 int def = 0;
William Lallemand1d29c742019-10-04 00:53:29 +02002729
2730 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2731
2732 /* ignore if sc0 was already inserted in a tree */
2733 if (sc0->name.node.leaf_p)
2734 continue;
2735
2736 /* Check for duplicates. */
2737 if (sc0->wild)
2738 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2739 else
2740 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2741
2742 for (; node; node = ebmb_next_dup(node)) {
2743 sc1 = ebmb_entry(node, struct sni_ctx, name);
2744 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2745 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2746 /* it's a duplicate, we should remove and free it */
2747 LIST_DEL(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002748 SSL_CTX_free(sc0->ctx);
William Lallemand1d29c742019-10-04 00:53:29 +02002749 free(sc0);
2750 sc0 = NULL;
William Lallemande15029b2019-10-14 10:46:58 +02002751 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002752 }
2753 }
2754
2755 /* if duplicate, ignore the insertion */
2756 if (!sc0)
2757 continue;
2758
2759 if (sc0->wild)
2760 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
2761 else
2762 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
William Lallemand21724f02019-11-04 17:56:13 +01002763
2764 /* replace the default_ctx if required with the first ctx */
2765 if (ckch_inst->is_default && !def) {
William Lallemand02e19a52020-04-08 16:11:26 +02002766 SSL_CTX_free(bind_conf->default_ctx);
2767 SSL_CTX_up_ref(sc0->ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002768 bind_conf->default_ctx = sc0->ctx;
2769 def = 1;
2770 }
William Lallemand1d29c742019-10-04 00:53:29 +02002771 }
2772}
2773
2774/*
William Lallemande3af8fb2019-10-08 11:36:53 +02002775 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02002776 */
William Lallemande3af8fb2019-10-08 11:36:53 +02002777struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02002778
William Lallemand2954c472020-03-06 21:54:13 +01002779/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02002780struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02002781
Emeric Brun7a883362019-10-17 13:27:40 +02002782/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002783 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02002784 * DH parameter is loaded into the SSL_CTX and if there is no
2785 * DH parameter available in ckchs nor in global, the default
2786 * DH parameters are applied on the SSL_CTX.
2787 * Returns a bitfield containing the flags:
2788 * ERR_FATAL in any fatal error case
2789 * ERR_ALERT if a reason of the error is availabine in err
2790 * ERR_WARN if a warning is available into err
2791 * The value 0 means there is no error nor warning and
2792 * the operation succeed.
2793 */
William Lallemandfa892222019-07-23 16:06:08 +02002794#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02002795static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
2796 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02002797{
Emeric Brun7a883362019-10-17 13:27:40 +02002798 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02002799 DH *dh = NULL;
2800
William Lallemanda8c73742019-07-31 18:31:34 +02002801 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02002802 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02002803 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
2804 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
2805 err && *err ? *err : "", path);
2806#if defined(SSL_CTX_set_dh_auto)
2807 SSL_CTX_set_dh_auto(ctx, 1);
2808 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2809 err && *err ? *err : "");
2810#else
2811 memprintf(err, "%s, DH ciphers won't be available.\n",
2812 err && *err ? *err : "");
2813#endif
2814 ret |= ERR_WARN;
2815 goto end;
2816 }
William Lallemandfa892222019-07-23 16:06:08 +02002817
2818 if (ssl_dh_ptr_index >= 0) {
2819 /* store a pointer to the DH params to avoid complaining about
2820 ssl-default-dh-param not being set for this SSL_CTX */
2821 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
2822 }
2823 }
2824 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02002825 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
2826 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
2827 err && *err ? *err : "", path);
2828#if defined(SSL_CTX_set_dh_auto)
2829 SSL_CTX_set_dh_auto(ctx, 1);
2830 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2831 err && *err ? *err : "");
2832#else
2833 memprintf(err, "%s, DH ciphers won't be available.\n",
2834 err && *err ? *err : "");
2835#endif
2836 ret |= ERR_WARN;
2837 goto end;
2838 }
William Lallemandfa892222019-07-23 16:06:08 +02002839 }
2840 else {
2841 /* Clear openssl global errors stack */
2842 ERR_clear_error();
2843
2844 if (global_ssl.default_dh_param <= 1024) {
2845 /* we are limited to DH parameter of 1024 bits anyway */
2846 if (local_dh_1024 == NULL)
2847 local_dh_1024 = ssl_get_dh_1024();
2848
Emeric Brun7a883362019-10-17 13:27:40 +02002849 if (local_dh_1024 == NULL) {
2850 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
2851 err && *err ? *err : "", path);
2852 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02002853 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02002854 }
William Lallemandfa892222019-07-23 16:06:08 +02002855
Emeric Bruna9363eb2019-10-17 14:53:03 +02002856 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
2857 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
2858 err && *err ? *err : "", path);
2859#if defined(SSL_CTX_set_dh_auto)
2860 SSL_CTX_set_dh_auto(ctx, 1);
2861 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2862 err && *err ? *err : "");
2863#else
2864 memprintf(err, "%s, DH ciphers won't be available.\n",
2865 err && *err ? *err : "");
2866#endif
2867 ret |= ERR_WARN;
2868 goto end;
2869 }
William Lallemandfa892222019-07-23 16:06:08 +02002870 }
2871 else {
2872 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
2873 }
William Lallemand8d0f8932019-10-17 18:03:58 +02002874 }
2875
William Lallemandf9568fc2019-10-16 18:27:58 +02002876end:
William Lallemandf9568fc2019-10-16 18:27:58 +02002877 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02002878 return ret;
2879}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02002880#endif
William Lallemandfa892222019-07-23 16:06:08 +02002881
yanbzhu488a4d22015-12-01 15:16:07 -05002882/* Loads the info in ckch into ctx
Emeric Bruna96b5822019-10-17 13:25:14 +02002883 * Returns a bitfield containing the flags:
2884 * ERR_FATAL in any fatal error case
2885 * ERR_ALERT if the reason of the error is available in err
2886 * ERR_WARN if a warning is available into err
2887 * The value 0 means there is no error nor warning and
2888 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05002889 */
2890static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
2891{
Emeric Bruna96b5822019-10-17 13:25:14 +02002892 int errcode = 0;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002893 STACK_OF(X509) *find_chain = NULL;
Emeric Bruna96b5822019-10-17 13:25:14 +02002894
yanbzhu488a4d22015-12-01 15:16:07 -05002895 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
2896 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
2897 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002898 errcode |= ERR_ALERT | ERR_FATAL;
2899 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05002900 }
2901
2902 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
2903 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
2904 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002905 errcode |= ERR_ALERT | ERR_FATAL;
2906 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05002907 }
2908
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002909 if (ckch->chain) {
2910 find_chain = ckch->chain;
2911 } else {
2912 /* Find Certificate Chain in global */
2913 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01002914 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002915 if (issuer)
2916 find_chain = issuer->chain;
2917 }
William Lallemand85888572020-02-27 14:48:35 +01002918
Emmanuel Hocdet16739772020-02-28 16:00:34 +01002919 /* Load all certs from chain, except Root, in the ssl_ctx */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002920 if (find_chain) {
2921 int i;
2922 X509 *ca;
2923 for (i = 0; i < sk_X509_num(find_chain); i++) {
2924 ca = sk_X509_value(find_chain, i);
Emmanuel Hocdet16739772020-02-28 16:00:34 +01002925 /* skip self issued (Root CA) */
Emmanuel Hocdetc3b7e742020-04-22 11:06:19 +02002926 if (global_ssl.skip_self_issued_ca && !X509_NAME_cmp(X509_get_subject_name(ca), X509_get_issuer_name(ca)))
Emmanuel Hocdet16739772020-02-28 16:00:34 +01002927 continue;
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002928 /*
2929 SSL_CTX_add1_chain_cert could be used with openssl >= 1.0.2
2930 Used SSL_CTX_add_extra_chain_cert for compat (aka SSL_CTX_add0_chain_cert)
2931 */
2932 X509_up_ref(ca);
2933 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
2934 X509_free(ca);
2935 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
2936 err && *err ? *err : "", path);
2937 errcode |= ERR_ALERT | ERR_FATAL;
2938 goto end;
2939 }
Emmanuel Hocdetf4f14ea2020-03-23 10:31:47 +01002940 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002941 }
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;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003652
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003653 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003654 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003655
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003656 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003657 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3658 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3659 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003660 else
3661 flags = conf_ssl_methods->flags;
3662
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003663 min = conf_ssl_methods->min;
3664 max = conf_ssl_methods->max;
3665 /* start with TLSv10 to remove SSLv3 per default */
3666 if (!min && (!max || max >= CONF_TLSV10))
3667 min = CONF_TLSV10;
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003668 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003669 if (min)
3670 flags |= (methodVersions[min].flag - 1);
3671 if (max)
3672 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003673 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003674 min = max = CONF_TLSV_NONE;
3675 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003676 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003677 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003678 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003679 if (min) {
3680 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003681 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3682 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3683 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3684 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003685 hole = 0;
3686 }
3687 max = i;
3688 }
3689 else {
3690 min = max = i;
3691 }
3692 }
3693 else {
3694 if (min)
3695 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003696 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003697 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003698 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3699 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003700 cfgerr += 1;
3701 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003702 /* save real min/max in bind_conf */
3703 conf_ssl_methods->min = min;
3704 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003705
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003706#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003707 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003708 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003709 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003710 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003711 else
3712 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
3713 if (flags & methodVersions[i].flag)
3714 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003715#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003716 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003717 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3718 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003719#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003720
3721 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3722 options |= SSL_OP_NO_TICKET;
3723 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3724 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003725
3726#ifdef SSL_OP_NO_RENEGOTIATION
3727 options |= SSL_OP_NO_RENEGOTIATION;
3728#endif
3729
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003730 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003731
Willy Tarreau5db847a2019-05-09 14:13:35 +02003732#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003733 if (global_ssl.async)
3734 mode |= SSL_MODE_ASYNC;
3735#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003736 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003737 if (global_ssl.life_time)
3738 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003739
3740#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3741#ifdef OPENSSL_IS_BORINGSSL
3742 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3743 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003744#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003745 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003746 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003747 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3748 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003749#else
3750 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003751#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003752 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003753#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003754 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003755}
3756
William Lallemand4f45bb92017-10-30 20:08:51 +01003757
3758static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3759{
3760 if (first == block) {
3761 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3762 if (first->len > 0)
3763 sh_ssl_sess_tree_delete(sh_ssl_sess);
3764 }
3765}
3766
3767/* return first block from sh_ssl_sess */
3768static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3769{
3770 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3771
3772}
3773
3774/* store a session into the cache
3775 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3776 * data: asn1 encoded session
3777 * data_len: asn1 encoded session length
3778 * Returns 1 id session was stored (else 0)
3779 */
3780static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3781{
3782 struct shared_block *first;
3783 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3784
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003785 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003786 if (!first) {
3787 /* Could not retrieve enough free blocks to store that session */
3788 return 0;
3789 }
3790
3791 /* STORE the key in the first elem */
3792 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3793 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3794 first->len = sizeof(struct sh_ssl_sess_hdr);
3795
3796 /* it returns the already existing node
3797 or current node if none, never returns null */
3798 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3799 if (oldsh_ssl_sess != sh_ssl_sess) {
3800 /* NOTE: Row couldn't be in use because we lock read & write function */
3801 /* release the reserved row */
3802 shctx_row_dec_hot(ssl_shctx, first);
3803 /* replace the previous session already in the tree */
3804 sh_ssl_sess = oldsh_ssl_sess;
3805 /* ignore the previous session data, only use the header */
3806 first = sh_ssl_sess_first_block(sh_ssl_sess);
3807 shctx_row_inc_hot(ssl_shctx, first);
3808 first->len = sizeof(struct sh_ssl_sess_hdr);
3809 }
3810
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003811 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01003812 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003813 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01003814 }
3815
3816 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003817
3818 return 1;
3819}
William Lallemanded0b5ad2017-10-30 19:36:36 +01003820
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003821/* SSL callback used when a new session is created while connecting to a server */
3822static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
3823{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02003824 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003825 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003826
Willy Tarreau07d94e42018-09-20 10:57:52 +02003827 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003828
Olivier Houcharde6060c52017-11-16 17:42:52 +01003829 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
3830 int len;
3831 unsigned char *ptr;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003832
Olivier Houcharde6060c52017-11-16 17:42:52 +01003833 len = i2d_SSL_SESSION(sess, NULL);
3834 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
3835 ptr = s->ssl_ctx.reused_sess[tid].ptr;
3836 } else {
3837 free(s->ssl_ctx.reused_sess[tid].ptr);
3838 ptr = s->ssl_ctx.reused_sess[tid].ptr = malloc(len);
3839 s->ssl_ctx.reused_sess[tid].allocated_size = len;
3840 }
3841 if (s->ssl_ctx.reused_sess[tid].ptr) {
3842 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
3843 &ptr);
3844 }
3845 } else {
3846 free(s->ssl_ctx.reused_sess[tid].ptr);
3847 s->ssl_ctx.reused_sess[tid].ptr = NULL;
3848 }
3849
3850 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003851}
3852
Olivier Houcharde6060c52017-11-16 17:42:52 +01003853
William Lallemanded0b5ad2017-10-30 19:36:36 +01003854/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01003855int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003856{
3857 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
3858 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
3859 unsigned char *p;
3860 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02003861 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003862 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003863
3864 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003865 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02003866 * note: SSL_SESSION_set1_id is using
3867 * a memcpy so we need to use a different pointer
3868 * than sid_data or sid_ctx_data to avoid valgrind
3869 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01003870 */
3871
3872 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02003873
3874 /* copy value in an other buffer */
3875 memcpy(encid, sid_data, sid_length);
3876
3877 /* pad with 0 */
3878 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
3879 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
3880
3881 /* force length to zero to avoid ASN1 encoding */
3882 SSL_SESSION_set1_id(sess, encid, 0);
3883
3884 /* force length to zero to avoid ASN1 encoding */
3885 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003886
3887 /* check if buffer is large enough for the ASN1 encoded session */
3888 data_len = i2d_SSL_SESSION(sess, NULL);
3889 if (data_len > SHSESS_MAX_DATA_LEN)
3890 goto err;
3891
3892 p = encsess;
3893
3894 /* process ASN1 session encoding before the lock */
3895 i2d_SSL_SESSION(sess, &p);
3896
William Lallemanded0b5ad2017-10-30 19:36:36 +01003897
William Lallemanda3c77cf2017-10-30 23:44:40 +01003898 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003899 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003900 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01003901 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003902err:
3903 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02003904 SSL_SESSION_set1_id(sess, encid, sid_length);
3905 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003906
3907 return 0; /* do not increment session reference count */
3908}
3909
3910/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003911SSL_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 +01003912{
William Lallemand4f45bb92017-10-30 20:08:51 +01003913 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003914 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
3915 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01003916 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01003917 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003918
3919 global.shctx_lookups++;
3920
3921 /* allow the session to be freed automatically by openssl */
3922 *do_copy = 0;
3923
3924 /* tree key is zeros padded sessionid */
3925 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3926 memcpy(tmpkey, key, key_len);
3927 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
3928 key = tmpkey;
3929 }
3930
3931 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003932 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003933
3934 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003935 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
3936 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003937 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003938 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003939 global.shctx_misses++;
3940 return NULL;
3941 }
3942
William Lallemand4f45bb92017-10-30 20:08:51 +01003943 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
3944 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003945
William Lallemand4f45bb92017-10-30 20:08:51 +01003946 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 +01003947
William Lallemanda3c77cf2017-10-30 23:44:40 +01003948 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003949
3950 /* decode ASN1 session */
3951 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01003952 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003953 /* Reset session id and session id contenxt */
3954 if (sess) {
3955 SSL_SESSION_set1_id(sess, key, key_len);
3956 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
3957 }
3958
3959 return sess;
3960}
3961
William Lallemand4f45bb92017-10-30 20:08:51 +01003962
William Lallemanded0b5ad2017-10-30 19:36:36 +01003963/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003964void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003965{
William Lallemand4f45bb92017-10-30 20:08:51 +01003966 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003967 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
3968 unsigned int sid_length;
3969 const unsigned char *sid_data;
3970 (void)ctx;
3971
3972 sid_data = SSL_SESSION_get_id(sess, &sid_length);
3973 /* tree key is zeros padded sessionid */
3974 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3975 memcpy(tmpkey, sid_data, sid_length);
3976 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
3977 sid_data = tmpkey;
3978 }
3979
William Lallemanda3c77cf2017-10-30 23:44:40 +01003980 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003981
3982 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003983 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
3984 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003985 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003986 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003987 }
3988
3989 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003990 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003991}
3992
3993/* Set session cache mode to server and disable openssl internal cache.
3994 * Set shared cache callbacks on an ssl context.
3995 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01003996void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003997{
3998 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
3999
4000 if (!ssl_shctx) {
4001 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4002 return;
4003 }
4004
4005 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4006 SSL_SESS_CACHE_NO_INTERNAL |
4007 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4008
4009 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004010 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4011 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4012 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004013}
4014
William Lallemand8b453912019-11-21 15:48:10 +01004015/*
4016 * This function applies the SSL configuration on a SSL_CTX
4017 * It returns an error code and fills the <err> buffer
4018 */
4019int 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 +01004020{
4021 struct proxy *curproxy = bind_conf->frontend;
4022 int cfgerr = 0;
4023 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004024 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004025 const char *conf_ciphers;
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004026#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004027 const char *conf_ciphersuites;
4028#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004029 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004030
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004031 if (ssl_conf) {
4032 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4033 int i, min, max;
4034 int flags = MC_SSL_O_ALL;
4035
4036 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004037 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4038 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004039 if (min)
4040 flags |= (methodVersions[min].flag - 1);
4041 if (max)
4042 flags |= ~((methodVersions[max].flag << 1) - 1);
4043 min = max = CONF_TLSV_NONE;
4044 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4045 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4046 if (min)
4047 max = i;
4048 else
4049 min = max = i;
4050 }
4051 /* save real min/max */
4052 conf_ssl_methods->min = min;
4053 conf_ssl_methods->max = max;
4054 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004055 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4056 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004057 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004058 }
4059 }
4060
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004061 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004062 case SSL_SOCK_VERIFY_NONE:
4063 verify = SSL_VERIFY_NONE;
4064 break;
4065 case SSL_SOCK_VERIFY_OPTIONAL:
4066 verify = SSL_VERIFY_PEER;
4067 break;
4068 case SSL_SOCK_VERIFY_REQUIRED:
4069 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4070 break;
4071 }
4072 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4073 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004074 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 +01004075 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 +01004076 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 +01004077 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004078 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004079 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004080 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004081 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004082 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004083 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004084 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4085 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4086 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4087 cfgerr |= ERR_ALERT | ERR_FATAL;
4088 }
4089 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004090 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004091 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 +02004092 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004093 }
Emeric Brun850efd52014-01-29 12:24:34 +01004094 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004095 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4096 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004097 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004098 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004099#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004100 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004101 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4102
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004103 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004104 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4105 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004106 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004107 }
Emeric Brun561e5742012-10-02 15:20:55 +02004108 else {
4109 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4110 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004111 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004112#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004113 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004114 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004115#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004116 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004117 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004118 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4119 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004120 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004121 }
4122 }
4123#endif
4124
William Lallemand4f45bb92017-10-30 20:08:51 +01004125 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004126 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4127 if (conf_ciphers &&
4128 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004129 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4130 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004131 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004132 }
4133
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004134#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004135 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4136 if (conf_ciphersuites &&
4137 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004138 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4139 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004140 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004141 }
4142#endif
4143
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004144#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004145 /* If tune.ssl.default-dh-param has not been set,
4146 neither has ssl-default-dh-file and no static DH
4147 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004148 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004149 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004150 (ssl_dh_ptr_index == -1 ||
4151 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004152 /* default to dh-param 2048 */
4153 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004154 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004155
Willy Tarreauef934602016-12-22 23:12:01 +01004156 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004157 if (local_dh_1024 == NULL) {
4158 local_dh_1024 = ssl_get_dh_1024();
4159 }
Willy Tarreauef934602016-12-22 23:12:01 +01004160 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004161 if (local_dh_2048 == NULL) {
4162 local_dh_2048 = ssl_get_dh_2048();
4163 }
Willy Tarreauef934602016-12-22 23:12:01 +01004164 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004165 if (local_dh_4096 == NULL) {
4166 local_dh_4096 = ssl_get_dh_4096();
4167 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004168 }
4169 }
4170 }
4171#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004172
Emeric Brunfc0421f2012-09-07 17:30:07 +02004173 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004174#if HA_OPENSSL_VERSION_NUMBER >= 0x00907000L
Emeric Brun29f037d2014-04-25 19:05:36 +02004175 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004176#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004177
Bernard Spil13c53f82018-02-15 13:34:58 +01004178#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004179 ssl_conf_cur = NULL;
4180 if (ssl_conf && ssl_conf->npn_str)
4181 ssl_conf_cur = ssl_conf;
4182 else if (bind_conf->ssl_conf.npn_str)
4183 ssl_conf_cur = &bind_conf->ssl_conf;
4184 if (ssl_conf_cur)
4185 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004186#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004187#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004188 ssl_conf_cur = NULL;
4189 if (ssl_conf && ssl_conf->alpn_str)
4190 ssl_conf_cur = ssl_conf;
4191 else if (bind_conf->ssl_conf.alpn_str)
4192 ssl_conf_cur = &bind_conf->ssl_conf;
4193 if (ssl_conf_cur)
4194 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004195#endif
Lukas Tribusd14b49c2019-11-24 18:20:40 +01004196#if ((HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL) || defined(LIBRESSL_VERSION_NUMBER))
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004197 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4198 if (conf_curves) {
4199 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004200 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4201 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004202 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004203 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004204 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004205 }
4206#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004207#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004208 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004209 int i;
4210 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004211#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004212 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004213 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4214 NULL);
4215
4216 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004217 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004218 return cfgerr;
4219 }
4220#else
4221 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4222 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4223 ECDHE_DEFAULT_CURVE);
4224#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004225
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004226 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004227 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004228 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4229 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004230 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004231 }
4232 else {
4233 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4234 EC_KEY_free(ecdh);
4235 }
4236 }
4237#endif
4238
Emeric Brunfc0421f2012-09-07 17:30:07 +02004239 return cfgerr;
4240}
4241
Evan Broderbe554312013-06-27 00:05:25 -07004242static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4243{
4244 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4245 size_t prefixlen, suffixlen;
4246
4247 /* Trivial case */
4248 if (strcmp(pattern, hostname) == 0)
4249 return 1;
4250
Evan Broderbe554312013-06-27 00:05:25 -07004251 /* The rest of this logic is based on RFC 6125, section 6.4.3
4252 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4253
Emeric Bruna848dae2013-10-08 11:27:28 +02004254 pattern_wildcard = NULL;
4255 pattern_left_label_end = pattern;
4256 while (*pattern_left_label_end != '.') {
4257 switch (*pattern_left_label_end) {
4258 case 0:
4259 /* End of label not found */
4260 return 0;
4261 case '*':
4262 /* If there is more than one wildcards */
4263 if (pattern_wildcard)
4264 return 0;
4265 pattern_wildcard = pattern_left_label_end;
4266 break;
4267 }
4268 pattern_left_label_end++;
4269 }
4270
4271 /* If it's not trivial and there is no wildcard, it can't
4272 * match */
4273 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004274 return 0;
4275
4276 /* Make sure all labels match except the leftmost */
4277 hostname_left_label_end = strchr(hostname, '.');
4278 if (!hostname_left_label_end
4279 || strcmp(pattern_left_label_end, hostname_left_label_end) != 0)
4280 return 0;
4281
4282 /* Make sure the leftmost label of the hostname is long enough
4283 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004284 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004285 return 0;
4286
4287 /* Finally compare the string on either side of the
4288 * wildcard */
4289 prefixlen = pattern_wildcard - pattern;
4290 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
Emeric Bruna848dae2013-10-08 11:27:28 +02004291 if ((prefixlen && (memcmp(pattern, hostname, prefixlen) != 0))
4292 || (suffixlen && (memcmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004293 return 0;
4294
4295 return 1;
4296}
4297
4298static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4299{
4300 SSL *ssl;
4301 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004302 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004303 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004304 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004305
4306 int depth;
4307 X509 *cert;
4308 STACK_OF(GENERAL_NAME) *alt_names;
4309 int i;
4310 X509_NAME *cert_subject;
4311 char *str;
4312
4313 if (ok == 0)
4314 return ok;
4315
4316 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004317 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004318 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004319
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004320 /* We're checking if the provided hostnames match the desired one. The
4321 * desired hostname comes from the SNI we presented if any, or if not
4322 * provided then it may have been explicitly stated using a "verifyhost"
4323 * directive. If neither is set, we don't care about the name so the
4324 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004325 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004326 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004327 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004328 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004329 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004330 if (!servername)
4331 return ok;
4332 }
Evan Broderbe554312013-06-27 00:05:25 -07004333
4334 /* We only need to verify the CN on the actual server cert,
4335 * not the indirect CAs */
4336 depth = X509_STORE_CTX_get_error_depth(ctx);
4337 if (depth != 0)
4338 return ok;
4339
4340 /* At this point, the cert is *not* OK unless we can find a
4341 * hostname match */
4342 ok = 0;
4343
4344 cert = X509_STORE_CTX_get_current_cert(ctx);
4345 /* It seems like this might happen if verify peer isn't set */
4346 if (!cert)
4347 return ok;
4348
4349 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4350 if (alt_names) {
4351 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4352 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4353 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004354#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004355 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4356#else
Evan Broderbe554312013-06-27 00:05:25 -07004357 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004358#endif
Evan Broderbe554312013-06-27 00:05:25 -07004359 ok = ssl_sock_srv_hostcheck(str, servername);
4360 OPENSSL_free(str);
4361 }
4362 }
4363 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004364 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004365 }
4366
4367 cert_subject = X509_get_subject_name(cert);
4368 i = -1;
4369 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4370 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004371 ASN1_STRING *value;
4372 value = X509_NAME_ENTRY_get_data(entry);
4373 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004374 ok = ssl_sock_srv_hostcheck(str, servername);
4375 OPENSSL_free(str);
4376 }
4377 }
4378
Willy Tarreau71d058c2017-07-26 20:09:56 +02004379 /* report the mismatch and indicate if SNI was used or not */
4380 if (!ok && !conn->err_code)
4381 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004382 return ok;
4383}
4384
Emeric Brun94324a42012-10-11 14:00:19 +02004385/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004386int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004387{
Willy Tarreau03209342016-12-22 17:08:28 +01004388 struct proxy *curproxy = srv->proxy;
Emeric Brun94324a42012-10-11 14:00:19 +02004389 int cfgerr = 0;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004390 long options =
Emeric Brun94324a42012-10-11 14:00:19 +02004391 SSL_OP_ALL | /* all known workarounds for bugs */
4392 SSL_OP_NO_SSLv2 |
4393 SSL_OP_NO_COMPRESSION;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004394 long mode =
Emeric Brun94324a42012-10-11 14:00:19 +02004395 SSL_MODE_ENABLE_PARTIAL_WRITE |
4396 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004397 SSL_MODE_RELEASE_BUFFERS |
4398 SSL_MODE_SMALL_BUFFERS;
Emeric Brun850efd52014-01-29 12:24:34 +01004399 int verify = SSL_VERIFY_NONE;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004400 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004401 struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004402 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004403 int flags = MC_SSL_O_ALL;
Emeric Brun94324a42012-10-11 14:00:19 +02004404
Thierry Fournier383085f2013-01-24 14:15:43 +01004405 /* Make sure openssl opens /dev/urandom before the chroot */
4406 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004407 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004408 cfgerr++;
4409 }
4410
Willy Tarreaufce03112015-01-15 21:32:40 +01004411 /* Automatic memory computations need to know we use SSL there */
4412 global.ssl_used_backend = 1;
4413
4414 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004415 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004416 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004417 ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4418 curproxy->id, srv->id,
4419 srv->conf.file, srv->conf.line);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004420 cfgerr++;
4421 return cfgerr;
4422 }
4423 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004424 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004425 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004426
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004427 ctx = SSL_CTX_new(SSLv23_client_method());
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004428 if (!ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004429 ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4430 proxy_type_str(curproxy), curproxy->id,
4431 srv->id);
Emeric Brun94324a42012-10-11 14:00:19 +02004432 cfgerr++;
4433 return cfgerr;
4434 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004435
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004436 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004437 ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4438 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4439 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004440 else
4441 flags = conf_ssl_methods->flags;
4442
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004443 /* Real min and max should be determinate with configuration and openssl's capabilities */
4444 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004445 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004446 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004447 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004448
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004449 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004450 min = max = CONF_TLSV_NONE;
4451 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004452 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004453 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004454 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004455 if (min) {
4456 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004457 ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4458 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4459 proxy_type_str(curproxy), curproxy->id, srv->id,
4460 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004461 hole = 0;
4462 }
4463 max = i;
4464 }
4465 else {
4466 min = max = i;
4467 }
4468 }
4469 else {
4470 if (min)
4471 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004472 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004473 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004474 ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4475 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004476 cfgerr += 1;
4477 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004478
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004479#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004480 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004481 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004482 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004483 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004484 else
4485 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4486 if (flags & methodVersions[i].flag)
4487 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004488#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004489 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004490 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4491 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004492#endif
4493
4494 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4495 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004496 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004497
Willy Tarreau5db847a2019-05-09 14:13:35 +02004498#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004499 if (global_ssl.async)
4500 mode |= SSL_MODE_ASYNC;
4501#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004502 SSL_CTX_set_mode(ctx, mode);
4503 srv->ssl_ctx.ctx = ctx;
4504
Emeric Bruna7aa3092012-10-26 12:58:00 +02004505 if (srv->ssl_ctx.client_crt) {
4506 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 +01004507 ha_alert("config : %s '%s', server '%s': unable to load SSL private key from PEM file '%s'.\n",
4508 proxy_type_str(curproxy), curproxy->id,
4509 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004510 cfgerr++;
4511 }
4512 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 +01004513 ha_alert("config : %s '%s', server '%s': unable to load ssl certificate from PEM file '%s'.\n",
4514 proxy_type_str(curproxy), curproxy->id,
4515 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004516 cfgerr++;
4517 }
4518 else if (SSL_CTX_check_private_key(srv->ssl_ctx.ctx) <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004519 ha_alert("config : %s '%s', server '%s': inconsistencies between private key and certificate loaded from PEM file '%s'.\n",
4520 proxy_type_str(curproxy), curproxy->id,
4521 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004522 cfgerr++;
4523 }
4524 }
Emeric Brun94324a42012-10-11 14:00:19 +02004525
Emeric Brun850efd52014-01-29 12:24:34 +01004526 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4527 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004528 switch (srv->ssl_ctx.verify) {
4529 case SSL_SOCK_VERIFY_NONE:
4530 verify = SSL_VERIFY_NONE;
4531 break;
4532 case SSL_SOCK_VERIFY_REQUIRED:
4533 verify = SSL_VERIFY_PEER;
4534 break;
4535 }
Evan Broderbe554312013-06-27 00:05:25 -07004536 SSL_CTX_set_verify(srv->ssl_ctx.ctx,
Emeric Brun850efd52014-01-29 12:24:34 +01004537 verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004538 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004539 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004540 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004541 /* set CAfile to verify */
4542 if (!ssl_set_verify_locations_file(srv->ssl_ctx.ctx, srv->ssl_ctx.ca_file)) {
4543 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to set CA file '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004544 curproxy->id, srv->id,
4545 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004546 cfgerr++;
4547 }
4548 }
Emeric Brun850efd52014-01-29 12:24:34 +01004549 else {
4550 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Christopher Faulet767a84b2017-11-24 16:50:31 +01004551 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",
4552 curproxy->id, srv->id,
4553 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004554 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01004555 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4556 curproxy->id, srv->id,
4557 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004558 cfgerr++;
4559 }
Emeric Brunef42d922012-10-11 16:11:36 +02004560#ifdef X509_V_FLAG_CRL_CHECK
4561 if (srv->ssl_ctx.crl_file) {
4562 X509_STORE *store = SSL_CTX_get_cert_store(srv->ssl_ctx.ctx);
4563
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004564 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004565 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4566 curproxy->id, srv->id,
4567 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004568 cfgerr++;
4569 }
4570 else {
4571 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4572 }
4573 }
4574#endif
4575 }
4576
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004577 SSL_CTX_set_session_cache_mode(srv->ssl_ctx.ctx, SSL_SESS_CACHE_CLIENT |
4578 SSL_SESS_CACHE_NO_INTERNAL_STORE);
4579 SSL_CTX_sess_set_new_cb(srv->ssl_ctx.ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004580 if (srv->ssl_ctx.ciphers &&
4581 !SSL_CTX_set_cipher_list(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphers)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004582 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4583 curproxy->id, srv->id,
4584 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004585 cfgerr++;
4586 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004587
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004588#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004589 if (srv->ssl_ctx.ciphersuites &&
Pierre Cheynierbc34cd12019-03-21 16:15:47 +00004590 !SSL_CTX_set_ciphersuites(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphersuites)) {
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004591 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4592 curproxy->id, srv->id,
4593 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4594 cfgerr++;
4595 }
4596#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004597#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4598 if (srv->ssl_ctx.npn_str)
4599 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, srv);
4600#endif
4601#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4602 if (srv->ssl_ctx.alpn_str)
4603 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4604#endif
4605
Emeric Brun94324a42012-10-11 14:00:19 +02004606
4607 return cfgerr;
4608}
4609
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004610/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004611 * be NULL, in which case nothing is done. Returns the number of errors
4612 * encountered.
4613 */
Willy Tarreau03209342016-12-22 17:08:28 +01004614int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004615{
4616 struct ebmb_node *node;
4617 struct sni_ctx *sni;
4618 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004619 int errcode = 0;
4620 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004621
Willy Tarreaufce03112015-01-15 21:32:40 +01004622 /* Automatic memory computations need to know we use SSL there */
4623 global.ssl_used_frontend = 1;
4624
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004625 /* Make sure openssl opens /dev/urandom before the chroot */
4626 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004627 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004628 err++;
4629 }
4630 /* Create initial_ctx used to start the ssl connection before do switchctx */
4631 if (!bind_conf->initial_ctx) {
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004632 err += ssl_sock_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004633 /* It should not be necessary to call this function, but it's
4634 necessary first to check and move all initialisation related
4635 to initial_ctx in ssl_sock_initial_ctx. */
William Lallemand8b453912019-11-21 15:48:10 +01004636 errcode |= ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004637 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004638 if (bind_conf->default_ctx)
William Lallemand8b453912019-11-21 15:48:10 +01004639 errcode |= ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, &errmsg);
Emeric Brun0bed9942014-10-30 19:25:24 +01004640
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004641 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004642 while (node) {
4643 sni = ebmb_entry(node, struct sni_ctx, name);
Emeric Brun0bed9942014-10-30 19:25:24 +01004644 if (!sni->order && sni->ctx != bind_conf->default_ctx)
4645 /* only initialize the CTX on its first occurrence and
4646 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004647 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004648 node = ebmb_next(node);
4649 }
4650
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004651 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004652 while (node) {
4653 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004654 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004655 /* 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);
4658 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004659 node = ebmb_next(node);
4660 }
William Lallemand8b453912019-11-21 15:48:10 +01004661
4662 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004663 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004664 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004665 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004666 err++;
4667 }
4668
4669 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004670 return err;
4671}
4672
Willy Tarreau55d37912016-12-21 23:38:39 +01004673/* Prepares all the contexts for a bind_conf and allocates the shared SSL
4674 * context if needed. Returns < 0 on error, 0 on success. The warnings and
4675 * alerts are directly emitted since the rest of the stack does it below.
4676 */
4677int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
4678{
4679 struct proxy *px = bind_conf->frontend;
4680 int alloc_ctx;
4681 int err;
4682
4683 if (!bind_conf->is_ssl) {
4684 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004685 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
4686 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01004687 }
4688 return 0;
4689 }
4690 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004691 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004692 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
4693 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004694 }
4695 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004696 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
4697 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004698 return -1;
4699 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004700 }
William Lallemandc61c0b32017-12-04 18:46:39 +01004701 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004702 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02004703 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01004704 sizeof(*sh_ssl_sess_tree),
4705 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02004706 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004707 if (alloc_ctx == SHCTX_E_INIT_LOCK)
4708 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");
4709 else
4710 ha_alert("Unable to allocate SSL session cache.\n");
4711 return -1;
4712 }
4713 /* free block callback */
4714 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
4715 /* init the root tree within the extra space */
4716 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
4717 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01004718 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004719 err = 0;
4720 /* initialize all certificate contexts */
4721 err += ssl_sock_prepare_all_ctx(bind_conf);
4722
4723 /* initialize CA variables if the certificates generation is enabled */
4724 err += ssl_sock_load_ca(bind_conf);
4725
4726 return -err;
4727}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004728
4729/* release ssl context allocated for servers. */
4730void ssl_sock_free_srv_ctx(struct server *srv)
4731{
Olivier Houchardc7566002018-11-20 23:33:50 +01004732#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4733 if (srv->ssl_ctx.alpn_str)
4734 free(srv->ssl_ctx.alpn_str);
4735#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01004736#ifdef OPENSSL_NPN_NEGOTIATED
Olivier Houchardc7566002018-11-20 23:33:50 +01004737 if (srv->ssl_ctx.npn_str)
4738 free(srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01004739#endif
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004740 if (srv->ssl_ctx.ctx)
4741 SSL_CTX_free(srv->ssl_ctx.ctx);
4742}
4743
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004744/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004745 * be NULL, in which case nothing is done. The default_ctx is nullified too.
4746 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004747void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004748{
4749 struct ebmb_node *node, *back;
4750 struct sni_ctx *sni;
4751
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004752 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004753 while (node) {
4754 sni = ebmb_entry(node, struct sni_ctx, name);
4755 back = ebmb_next(node);
4756 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004757 SSL_CTX_free(sni->ctx);
4758 if (!sni->order) { /* only free the CTX conf on its first occurrence */
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004759 ssl_sock_free_ssl_conf(sni->conf);
4760 free(sni->conf);
4761 sni->conf = NULL;
4762 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004763 free(sni);
4764 node = back;
4765 }
4766
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004767 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004768 while (node) {
4769 sni = ebmb_entry(node, struct sni_ctx, name);
4770 back = ebmb_next(node);
4771 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004772 SSL_CTX_free(sni->ctx);
4773 if (!sni->order) { /* only free the SSL conf its first occurrence */
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004774 ssl_sock_free_ssl_conf(sni->conf);
4775 free(sni->conf);
4776 sni->conf = NULL;
4777 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004778 free(sni);
4779 node = back;
4780 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004781 SSL_CTX_free(bind_conf->initial_ctx);
4782 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02004783 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004784 bind_conf->default_ctx = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004785 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02004786}
4787
Willy Tarreau795cdab2016-12-22 17:30:54 +01004788/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
4789void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
4790{
4791 ssl_sock_free_ca(bind_conf);
4792 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004793 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01004794 free(bind_conf->ca_sign_file);
4795 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02004796 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01004797 free(bind_conf->keys_ref->filename);
4798 free(bind_conf->keys_ref->tlskeys);
4799 LIST_DEL(&bind_conf->keys_ref->list);
4800 free(bind_conf->keys_ref);
4801 }
4802 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004803 bind_conf->ca_sign_pass = NULL;
4804 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004805}
4806
Christopher Faulet31af49d2015-06-09 17:29:50 +02004807/* Load CA cert file and private key used to generate certificates */
4808int
Willy Tarreau03209342016-12-22 17:08:28 +01004809ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02004810{
Willy Tarreau03209342016-12-22 17:08:28 +01004811 struct proxy *px = bind_conf->frontend;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004812 FILE *fp;
4813 X509 *cacert = NULL;
4814 EVP_PKEY *capkey = NULL;
4815 int err = 0;
4816
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02004817 if (!bind_conf->generate_certs)
Christopher Faulet31af49d2015-06-09 17:29:50 +02004818 return err;
4819
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01004820#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02004821 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01004822 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004823 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02004824 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004825 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02004826#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02004827
Christopher Faulet31af49d2015-06-09 17:29:50 +02004828 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004829 ha_alert("Proxy '%s': cannot enable certificate generation, "
4830 "no CA certificate File configured at [%s:%d].\n",
4831 px->id, bind_conf->file, bind_conf->line);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004832 goto load_error;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004833 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004834
4835 /* read in the CA certificate */
4836 if (!(fp = fopen(bind_conf->ca_sign_file, "r"))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004837 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
4838 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004839 goto load_error;
4840 }
4841 if (!(cacert = PEM_read_X509(fp, NULL, NULL, NULL))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004842 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
4843 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004844 goto read_error;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004845 }
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004846 rewind(fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004847 if (!(capkey = PEM_read_PrivateKey(fp, NULL, NULL, bind_conf->ca_sign_pass))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004848 ha_alert("Proxy '%s': Failed to read CA private key file '%s' at [%s:%d].\n",
4849 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004850 goto read_error;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004851 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004852
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004853 fclose (fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004854 bind_conf->ca_sign_cert = cacert;
4855 bind_conf->ca_sign_pkey = capkey;
4856 return err;
4857
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004858 read_error:
4859 fclose (fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004860 if (capkey) EVP_PKEY_free(capkey);
4861 if (cacert) X509_free(cacert);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004862 load_error:
4863 bind_conf->generate_certs = 0;
4864 err++;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004865 return err;
4866}
4867
4868/* Release CA cert and private key used to generate certificated */
4869void
4870ssl_sock_free_ca(struct bind_conf *bind_conf)
4871{
Christopher Faulet31af49d2015-06-09 17:29:50 +02004872 if (bind_conf->ca_sign_pkey)
4873 EVP_PKEY_free(bind_conf->ca_sign_pkey);
4874 if (bind_conf->ca_sign_cert)
4875 X509_free(bind_conf->ca_sign_cert);
Willy Tarreau94ff03a2016-12-22 17:57:46 +01004876 bind_conf->ca_sign_pkey = NULL;
4877 bind_conf->ca_sign_cert = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004878}
4879
Emeric Brun46591952012-05-18 15:47:34 +02004880/*
4881 * This function is called if SSL * context is not yet allocated. The function
4882 * is designed to be called before any other data-layer operation and sets the
4883 * handshake flag on the connection. It is safe to call it multiple times.
4884 * It returns 0 on success and -1 in error case.
4885 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004886static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004887{
Olivier Houchard66ab4982019-02-26 18:37:15 +01004888 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02004889 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004890 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004891 return 0;
4892
Willy Tarreau3c728722014-01-23 13:50:42 +01004893 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02004894 return 0;
4895
Olivier Houchard66ab4982019-02-26 18:37:15 +01004896 ctx = pool_alloc(ssl_sock_ctx_pool);
4897 if (!ctx) {
4898 conn->err_code = CO_ER_SSL_NO_MEM;
4899 return -1;
4900 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004901 ctx->wait_event.tasklet = tasklet_new();
4902 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004903 conn->err_code = CO_ER_SSL_NO_MEM;
4904 pool_free(ssl_sock_ctx_pool, ctx);
4905 return -1;
4906 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004907 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
4908 ctx->wait_event.tasklet->context = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004909 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01004910 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01004911 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004912 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01004913 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02004914 ctx->xprt_st = 0;
4915 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004916
4917 /* Only work with sockets for now, this should be adapted when we'll
4918 * add QUIC support.
4919 */
4920 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02004921 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004922 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
4923 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02004924 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01004925
Willy Tarreau20879a02012-12-03 16:32:10 +01004926 if (global.maxsslconn && sslconns >= global.maxsslconn) {
4927 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004928 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004929 }
Willy Tarreau403edff2012-09-06 11:58:37 +02004930
Emeric Brun46591952012-05-18 15:47:34 +02004931 /* If it is in client mode initiate SSL session
4932 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01004933 if (objt_server(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004934 int may_retry = 1;
4935
4936 retry_connect:
Emeric Brun46591952012-05-18 15:47:34 +02004937 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004938 ctx->ssl = SSL_new(__objt_server(conn->target)->ssl_ctx.ctx);
4939 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004940 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004941 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004942 goto retry_connect;
4943 }
Willy Tarreau20879a02012-12-03 16:32:10 +01004944 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004945 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004946 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004947 ctx->bio = BIO_new(ha_meth);
4948 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01004949 SSL_free(ctx->ssl);
4950 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004951 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004952 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004953 goto retry_connect;
4954 }
Emeric Brun55476152014-11-12 17:35:37 +01004955 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004956 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004957 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004958 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02004959 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02004960
Evan Broderbe554312013-06-27 00:05:25 -07004961 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004962 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
4963 SSL_free(ctx->ssl);
4964 ctx->ssl = NULL;
Emeric Brun55476152014-11-12 17:35:37 +01004965 conn->xprt_ctx = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004966 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004967 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004968 goto retry_connect;
4969 }
Emeric Brun55476152014-11-12 17:35:37 +01004970 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004971 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004972 }
4973
Olivier Houchard66ab4982019-02-26 18:37:15 +01004974 SSL_set_connect_state(ctx->ssl);
Willy Tarreau07d94e42018-09-20 10:57:52 +02004975 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
4976 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
4977 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 +01004978 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004979 SSL_SESSION_free(sess);
Willy Tarreau07d94e42018-09-20 10:57:52 +02004980 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
4981 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004982 } else if (sess) {
4983 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01004984 }
4985 }
Evan Broderbe554312013-06-27 00:05:25 -07004986
Emeric Brun46591952012-05-18 15:47:34 +02004987 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02004988 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02004989
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01004990 _HA_ATOMIC_ADD(&sslconns, 1);
4991 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004992 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004993 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004994 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02004995 return 0;
4996 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01004997 else if (objt_listener(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004998 int may_retry = 1;
4999
5000 retry_accept:
Emeric Brun46591952012-05-18 15:47:34 +02005001 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005002 ctx->ssl = SSL_new(__objt_listener(conn->target)->bind_conf->initial_ctx);
5003 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005004 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005005 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005006 goto retry_accept;
5007 }
Willy Tarreau20879a02012-12-03 16:32:10 +01005008 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005009 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005010 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005011 ctx->bio = BIO_new(ha_meth);
5012 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01005013 SSL_free(ctx->ssl);
5014 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005015 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005016 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005017 goto retry_accept;
5018 }
Emeric Brun55476152014-11-12 17:35:37 +01005019 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005020 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005021 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005022 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02005023 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02005024
Emeric Brune1f38db2012-09-03 20:36:47 +02005025 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005026 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
5027 SSL_free(ctx->ssl);
5028 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005029 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005030 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005031 goto retry_accept;
5032 }
Emeric Brun55476152014-11-12 17:35:37 +01005033 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005034 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005035 }
5036
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005037#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5038 if (__objt_listener(conn->target)->bind_conf->ssl_conf.early_data) {
5039 b_alloc(&ctx->early_buf);
5040 SSL_set_max_early_data(ctx->ssl,
5041 /* Only allow early data if we managed to allocate
5042 * a buffer.
5043 */
5044 (!b_is_null(&ctx->early_buf)) ?
5045 global.tune.bufsize - global.tune.maxrewrite : 0);
5046 }
5047#endif
5048
Olivier Houchard66ab4982019-02-26 18:37:15 +01005049 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005050
Emeric Brun46591952012-05-18 15:47:34 +02005051 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005052 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005053#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchardc2aae742017-09-22 18:26:28 +02005054 conn->flags |= CO_FL_EARLY_SSL_HS;
5055#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005056
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005057 _HA_ATOMIC_ADD(&sslconns, 1);
5058 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005059 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005060 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005061 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005062 return 0;
5063 }
5064 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005065 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005066err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005067 if (ctx && ctx->wait_event.tasklet)
5068 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005069 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005070 return -1;
5071}
5072
5073
5074/* This is the callback which is used when an SSL handshake is pending. It
5075 * updates the FD status if it wants some polling before being called again.
5076 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5077 * otherwise it returns non-zero and removes itself from the connection's
5078 * flags (the bit is provided in <flag> by the caller).
5079 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005080static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005081{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005082 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005083 int ret;
5084
Willy Tarreau3c728722014-01-23 13:50:42 +01005085 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005086 return 0;
5087
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005088 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005089 goto out_error;
5090
Willy Tarreau5db847a2019-05-09 14:13:35 +02005091#if HA_OPENSSL_VERSION_NUMBER >= 0x10101000L
Olivier Houchardc2aae742017-09-22 18:26:28 +02005092 /*
5093 * Check if we have early data. If we do, we have to read them
5094 * before SSL_do_handshake() is called, And there's no way to
5095 * detect early data, except to try to read them
5096 */
5097 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005098 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005099
Olivier Houchard54907bb2019-12-19 15:02:39 +01005100 while (1) {
5101 ret = SSL_read_early_data(ctx->ssl,
5102 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5103 &read_data);
5104 if (ret == SSL_READ_EARLY_DATA_ERROR)
5105 goto check_error;
5106 if (read_data > 0) {
5107 conn->flags |= CO_FL_EARLY_DATA;
5108 b_add(&ctx->early_buf, read_data);
5109 }
5110 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5111 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5112 if (!b_data(&ctx->early_buf))
5113 b_free(&ctx->early_buf);
5114 break;
5115 }
5116 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005117 }
5118#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005119 /* If we use SSL_do_handshake to process a reneg initiated by
5120 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5121 * Usually SSL_write and SSL_read are used and process implicitly
5122 * the reneg handshake.
5123 * Here we use SSL_peek as a workaround for reneg.
5124 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005125 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005126 char c;
5127
Olivier Houchard66ab4982019-02-26 18:37:15 +01005128 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005129 if (ret <= 0) {
5130 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005131 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005132
Emeric Brun674b7432012-11-08 19:21:55 +01005133 if (ret == SSL_ERROR_WANT_WRITE) {
5134 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005135 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005136 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005137 return 0;
5138 }
5139 else if (ret == SSL_ERROR_WANT_READ) {
5140 /* handshake may have been completed but we have
5141 * no more data to read.
5142 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005143 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005144 ret = 1;
5145 goto reneg_ok;
5146 }
5147 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005148 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005149 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005150 return 0;
5151 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005152#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005153 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005154 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005155 return 0;
5156 }
5157#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005158 else if (ret == SSL_ERROR_SYSCALL) {
5159 /* if errno is null, then connection was successfully established */
5160 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5161 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005162 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005163#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5164 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005165 conn->err_code = CO_ER_SSL_HANDSHAKE;
5166#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005167 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005168#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005169 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005170 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005171 empty_handshake = state == TLS_ST_BEFORE;
5172#else
Lukas Tribus49799162019-07-08 14:29:15 +02005173 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5174 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005175#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005176 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005177 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005178 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005179 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5180 else
5181 conn->err_code = CO_ER_SSL_EMPTY;
5182 }
5183 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005184 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005185 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5186 else
5187 conn->err_code = CO_ER_SSL_ABORT;
5188 }
5189 }
5190 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005191 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005192 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005193 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005194 conn->err_code = CO_ER_SSL_HANDSHAKE;
5195 }
Lukas Tribus49799162019-07-08 14:29:15 +02005196#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005197 }
Emeric Brun674b7432012-11-08 19:21:55 +01005198 goto out_error;
5199 }
5200 else {
5201 /* Fail on all other handshake errors */
5202 /* Note: OpenSSL may leave unread bytes in the socket's
5203 * buffer, causing an RST to be emitted upon close() on
5204 * TCP sockets. We first try to drain possibly pending
5205 * data to avoid this as much as possible.
5206 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005207 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005208 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005209 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005210 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005211 goto out_error;
5212 }
5213 }
5214 /* read some data: consider handshake completed */
5215 goto reneg_ok;
5216 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005217 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005218check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005219 if (ret != 1) {
5220 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005221 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005222
5223 if (ret == SSL_ERROR_WANT_WRITE) {
5224 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005225 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005226 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005227 return 0;
5228 }
5229 else if (ret == SSL_ERROR_WANT_READ) {
5230 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005231 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005232 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5233 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005234 return 0;
5235 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005236#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005237 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005238 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005239 return 0;
5240 }
5241#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005242 else if (ret == SSL_ERROR_SYSCALL) {
5243 /* if errno is null, then connection was successfully established */
5244 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5245 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005246 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005247#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5248 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005249 conn->err_code = CO_ER_SSL_HANDSHAKE;
5250#else
5251 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005252#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005253 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005254 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005255 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005256#else
Lukas Tribus49799162019-07-08 14:29:15 +02005257 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5258 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005259#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005260 if (empty_handshake) {
5261 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005262 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005263 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5264 else
5265 conn->err_code = CO_ER_SSL_EMPTY;
5266 }
5267 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005268 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005269 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5270 else
5271 conn->err_code = CO_ER_SSL_ABORT;
5272 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005273 }
5274 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005275 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005276 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5277 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005278 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005279 }
Lukas Tribus49799162019-07-08 14:29:15 +02005280#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005281 }
Willy Tarreau89230192012-09-28 20:22:13 +02005282 goto out_error;
5283 }
Emeric Brun46591952012-05-18 15:47:34 +02005284 else {
5285 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005286 /* Note: OpenSSL may leave unread bytes in the socket's
5287 * buffer, causing an RST to be emitted upon close() on
5288 * TCP sockets. We first try to drain possibly pending
5289 * data to avoid this as much as possible.
5290 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005291 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005292 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005293 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005294 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005295 goto out_error;
5296 }
5297 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005298#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchard522eea72017-11-03 16:27:47 +01005299 else {
5300 /*
5301 * If the server refused the early data, we have to send a
5302 * 425 to the client, as we no longer have the data to sent
5303 * them again.
5304 */
5305 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005306 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005307 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5308 goto out_error;
5309 }
5310 }
5311 }
5312#endif
5313
Emeric Brun46591952012-05-18 15:47:34 +02005314
Emeric Brun674b7432012-11-08 19:21:55 +01005315reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005316
Willy Tarreau5db847a2019-05-09 14:13:35 +02005317#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005318 /* ASYNC engine API doesn't support moving read/write
5319 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005320 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005321 */
5322 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005323 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005324#endif
Emeric Brun46591952012-05-18 15:47:34 +02005325 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005326 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005327 if (objt_server(conn->target)) {
5328 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5329 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5330 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005331 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005332 else {
5333 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5334 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5335 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5336 }
Emeric Brun46591952012-05-18 15:47:34 +02005337 }
5338
5339 /* The connection is now established at both layers, it's time to leave */
5340 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5341 return 1;
5342
5343 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005344 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005345 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005346 ERR_clear_error();
5347
Emeric Brun9fa89732012-10-04 17:09:56 +02005348 /* free resumed session if exists */
Willy Tarreau07d94e42018-09-20 10:57:52 +02005349 if (objt_server(conn->target) && __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5350 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
5351 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Emeric Brun9fa89732012-10-04 17:09:56 +02005352 }
5353
Emeric Brun46591952012-05-18 15:47:34 +02005354 /* Fail on all other handshake errors */
5355 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005356 if (!conn->err_code)
5357 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005358 return 0;
5359}
5360
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005361/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5362 * event subscriber <es> is not allowed to change from a previous call as long
5363 * as at least one event is still subscribed. The <event_type> must only be a
5364 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5365 * unless the transport layer was already released.
5366 */
5367static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005368{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005369 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005370
Olivier Houchard0ff28652019-06-24 18:57:39 +02005371 if (!ctx)
5372 return -1;
5373
Willy Tarreau113d52b2020-01-10 09:20:26 +01005374 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005375 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005376
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005377 ctx->subs = es;
5378 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005379
5380 /* we may have to subscribe to lower layers for new events */
5381 event_type &= ~ctx->wait_event.events;
5382 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5383 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005384 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005385}
5386
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005387/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5388 * The <es> pointer is not allowed to differ from the one passed to the
5389 * subscribe() call. It always returns zero.
5390 */
5391static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005392{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005393 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005394
Willy Tarreau113d52b2020-01-10 09:20:26 +01005395 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005396 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005397
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005398 es->events &= ~event_type;
5399 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005400 ctx->subs = NULL;
5401
5402 /* If we subscribed, and we're not doing the handshake,
5403 * then we subscribed because the upper layer asked for it,
5404 * as the upper layer is no longer interested, we can
5405 * unsubscribe too.
5406 */
5407 event_type &= ctx->wait_event.events;
5408 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5409 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005410
5411 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005412}
5413
Olivier Houchard2e055482019-05-27 19:50:12 +02005414/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5415 * Returns 0 on success, and non-zero on failure.
5416 */
5417static 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)
5418{
5419 struct ssl_sock_ctx *ctx = xprt_ctx;
5420
5421 if (oldxprt_ops != NULL)
5422 *oldxprt_ops = ctx->xprt;
5423 if (oldxprt_ctx != NULL)
5424 *oldxprt_ctx = ctx->xprt_ctx;
5425 ctx->xprt = toadd_ops;
5426 ctx->xprt_ctx = toadd_ctx;
5427 return 0;
5428}
5429
Olivier Houchard5149b592019-05-23 17:47:36 +02005430/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5431 * return 0, otherwise just call the remove_xprt method from the underlying
5432 * XPRT.
5433 */
5434static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5435{
5436 struct ssl_sock_ctx *ctx = xprt_ctx;
5437
5438 if (ctx->xprt_ctx == toremove_ctx) {
5439 ctx->xprt_ctx = newctx;
5440 ctx->xprt = newops;
5441 return 0;
5442 }
5443 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5444}
5445
Olivier Houchardea8dd942019-05-20 14:02:16 +02005446static struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned short state)
5447{
5448 struct ssl_sock_ctx *ctx = context;
5449
5450 /* First if we're doing an handshake, try that */
5451 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS)
5452 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
5453 /* If we had an error, or the handshake is done and I/O is available,
5454 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005455 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005456 * we can't be sure conn_fd_handler() will be called again.
5457 */
5458 if ((ctx->conn->flags & CO_FL_ERROR) ||
5459 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5460 int ret = 0;
5461 int woke = 0;
5462
5463 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005464 if (ctx->subs) {
5465 tasklet_wakeup(ctx->subs->tasklet);
5466 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005467 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005468 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005469 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005470
Olivier Houchardea8dd942019-05-20 14:02:16 +02005471 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005472 * upper layers know. If we have no mux, create it,
5473 * and once we have a mux, call its wake method if we didn't
5474 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005475 */
5476 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005477 if (!ctx->conn->mux)
5478 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005479 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
5480 ctx->conn->mux->wake(ctx->conn);
5481 return NULL;
5482 }
5483 }
Olivier Houchard54907bb2019-12-19 15:02:39 +01005484#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5485 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005486 else if (b_data(&ctx->early_buf) && ctx->subs &&
5487 ctx->subs->events & SUB_RETRY_RECV) {
5488 tasklet_wakeup(ctx->subs->tasklet);
5489 ctx->subs->events &= ~SUB_RETRY_RECV;
5490 if (!ctx->subs->events)
5491 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005492 }
5493#endif
Olivier Houchardea8dd942019-05-20 14:02:16 +02005494 return NULL;
5495}
5496
Emeric Brun46591952012-05-18 15:47:34 +02005497/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01005498 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02005499 * buffer wraps, in which case a second call may be performed. The connection's
5500 * flags are updated with whatever special event is detected (error, read0,
5501 * empty). The caller is responsible for taking care of those events and
5502 * avoiding the call if inappropriate. The function does not call the
5503 * connection's polling update function, so the caller is responsible for this.
5504 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005505static 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 +02005506{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005507 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02005508 ssize_t ret;
5509 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02005510
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005511 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005512 goto out_error;
5513
Olivier Houchard54907bb2019-12-19 15:02:39 +01005514#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5515 if (b_data(&ctx->early_buf)) {
5516 try = b_contig_space(buf);
5517 if (try > b_data(&ctx->early_buf))
5518 try = b_data(&ctx->early_buf);
5519 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
5520 b_add(buf, try);
5521 b_del(&ctx->early_buf, try);
5522 if (b_data(&ctx->early_buf) == 0)
5523 b_free(&ctx->early_buf);
5524 return try;
5525 }
5526#endif
5527
Willy Tarreau911db9b2020-01-23 16:27:54 +01005528 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005529 /* a handshake was requested */
5530 return 0;
5531
Emeric Brun46591952012-05-18 15:47:34 +02005532 /* read the largest possible block. For this, we perform only one call
5533 * to recv() unless the buffer wraps and we exactly fill the first hunk,
5534 * in which case we accept to do it once again. A new attempt is made on
5535 * EINTR too.
5536 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01005537 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005538
Willy Tarreau591d4452018-06-15 17:21:00 +02005539 try = b_contig_space(buf);
5540 if (!try)
5541 break;
5542
Willy Tarreauabf08d92014-01-14 11:31:27 +01005543 if (try > count)
5544 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02005545
Olivier Houchard66ab4982019-02-26 18:37:15 +01005546 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005547
Emeric Brune1f38db2012-09-03 20:36:47 +02005548 if (conn->flags & CO_FL_ERROR) {
5549 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005550 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005551 }
Emeric Brun46591952012-05-18 15:47:34 +02005552 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02005553 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005554 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005555 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005556 }
Emeric Brun46591952012-05-18 15:47:34 +02005557 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005558 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005559 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005560 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02005561 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005562 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005563#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005564 /* Async mode can be re-enabled, because we're leaving data state.*/
5565 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005566 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005567#endif
Emeric Brun46591952012-05-18 15:47:34 +02005568 break;
5569 }
5570 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005571 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005572 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5573 SUB_RETRY_RECV,
5574 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01005575 /* handshake is running, and it may need to re-enable read */
5576 conn->flags |= CO_FL_SSL_WAIT_HS;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005577#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005578 /* Async mode can be re-enabled, because we're leaving data state.*/
5579 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005580 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005581#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005582 break;
5583 }
Emeric Brun46591952012-05-18 15:47:34 +02005584 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005585 } else if (ret == SSL_ERROR_ZERO_RETURN)
5586 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005587 /* For SSL_ERROR_SYSCALL, make sure to clear the error
5588 * stack before shutting down the connection for
5589 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005590 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
5591 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02005592 /* otherwise it's a real error */
5593 goto out_error;
5594 }
5595 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005596 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005597 return done;
5598
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005599 clear_ssl_error:
5600 /* Clear openssl global errors stack */
5601 ssl_sock_dump_errors(conn);
5602 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02005603 read0:
5604 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005605 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005606
Emeric Brun46591952012-05-18 15:47:34 +02005607 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005608 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01005609 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005610 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005611 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005612 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005613}
5614
5615
Willy Tarreau787db9a2018-06-14 18:31:46 +02005616/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
5617 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
5618 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02005619 * Only one call to send() is performed, unless the buffer wraps, in which case
5620 * a second call may be performed. The connection's flags are updated with
5621 * whatever special event is detected (error, empty). The caller is responsible
5622 * for taking care of those events and avoiding the call if inappropriate. The
5623 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02005624 * is responsible for this. The buffer's output is not adjusted, it's up to the
5625 * caller to take care of this. It's up to the caller to update the buffer's
5626 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02005627 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005628static 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 +02005629{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005630 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005631 ssize_t ret;
5632 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02005633
5634 done = 0;
5635
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005636 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005637 goto out_error;
5638
Willy Tarreau911db9b2020-01-23 16:27:54 +01005639 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005640 /* a handshake was requested */
5641 return 0;
5642
5643 /* send the largest possible block. For this we perform only one call
5644 * to send() unless the buffer wraps and we exactly fill the first hunk,
5645 * in which case we accept to do it once again.
5646 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02005647 while (count) {
Willy Tarreau5db847a2019-05-09 14:13:35 +02005648#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchardc2aae742017-09-22 18:26:28 +02005649 size_t written_data;
5650#endif
5651
Willy Tarreau787db9a2018-06-14 18:31:46 +02005652 try = b_contig_data(buf, done);
5653 if (try > count)
5654 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01005655
Willy Tarreau7bed9452014-02-02 02:00:24 +01005656 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005657 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01005658 global_ssl.max_record && try > global_ssl.max_record) {
5659 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005660 }
5661 else {
5662 /* we need to keep the information about the fact that
5663 * we're not limiting the upcoming send(), because if it
5664 * fails, we'll have to retry with at least as many data.
5665 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005666 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005667 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01005668
Willy Tarreau5db847a2019-05-09 14:13:35 +02005669#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchard010941f2019-05-03 20:56:19 +02005670 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005671 unsigned int max_early;
5672
Olivier Houchard522eea72017-11-03 16:27:47 +01005673 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01005674 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01005675 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005676 if (SSL_get0_session(ctx->ssl))
5677 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01005678 else
5679 max_early = 0;
5680 }
5681
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005682 if (try + ctx->sent_early_data > max_early) {
5683 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01005684 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02005685 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005686 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005687 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01005688 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005689 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005690 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005691 if (ret == 1) {
5692 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005693 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005694 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005695 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005696 /* Initiate the handshake, now */
5697 tasklet_wakeup(ctx->wait_event.tasklet);
5698 }
Olivier Houchard522eea72017-11-03 16:27:47 +01005699
Olivier Houchardc2aae742017-09-22 18:26:28 +02005700 }
5701
5702 } else
5703#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005704 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01005705
Emeric Brune1f38db2012-09-03 20:36:47 +02005706 if (conn->flags & CO_FL_ERROR) {
5707 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005708 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005709 }
Emeric Brun46591952012-05-18 15:47:34 +02005710 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005711 /* A send succeeded, so we can consider ourself connected */
5712 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005713 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005714 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005715 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005716 }
5717 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005718 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005719
Emeric Brun46591952012-05-18 15:47:34 +02005720 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005721 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01005722 /* handshake is running, and it may need to re-enable write */
5723 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005724 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005725#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005726 /* Async mode can be re-enabled, because we're leaving data state.*/
5727 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005728 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005729#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005730 break;
5731 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005732
Emeric Brun46591952012-05-18 15:47:34 +02005733 break;
5734 }
5735 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005736 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02005737 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005738 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5739 SUB_RETRY_RECV,
5740 &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005741#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005742 /* Async mode can be re-enabled, because we're leaving data state.*/
5743 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005744 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005745#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005746 break;
5747 }
Emeric Brun46591952012-05-18 15:47:34 +02005748 goto out_error;
5749 }
5750 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005751 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005752 return done;
5753
5754 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005755 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005756 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005757 ERR_clear_error();
5758
Emeric Brun46591952012-05-18 15:47:34 +02005759 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005760 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005761}
5762
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005763static void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02005764
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005765 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005766
Olivier Houchardea8dd942019-05-20 14:02:16 +02005767
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005768 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005769 if (ctx->wait_event.events != 0)
5770 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
5771 ctx->wait_event.events,
5772 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01005773 if (ctx->subs) {
5774 ctx->subs->events = 0;
5775 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005776 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005777
Olivier Houchard692c1d02019-05-23 18:41:47 +02005778 if (ctx->xprt->close)
5779 ctx->xprt->close(conn, ctx->xprt_ctx);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005780#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +02005781 if (global_ssl.async) {
5782 OSSL_ASYNC_FD all_fd[32], afd;
5783 size_t num_all_fds = 0;
5784 int i;
5785
Olivier Houchard66ab4982019-02-26 18:37:15 +01005786 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005787 if (num_all_fds > 32) {
5788 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
5789 return;
5790 }
5791
Olivier Houchard66ab4982019-02-26 18:37:15 +01005792 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005793
5794 /* If an async job is pending, we must try to
5795 to catch the end using polling before calling
5796 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005797 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02005798 for (i=0 ; i < num_all_fds ; i++) {
5799 /* switch on an handler designed to
5800 * handle the SSL_free
5801 */
5802 afd = all_fd[i];
5803 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005804 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02005805 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00005806 /* To ensure that the fd cache won't be used
5807 * and we'll catch a real RD event.
5808 */
5809 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02005810 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005811 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005812 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005813 _HA_ATOMIC_ADD(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005814 return;
5815 }
Emeric Brun3854e012017-05-17 20:42:48 +02005816 /* Else we can remove the fds from the fdtab
5817 * and call SSL_free.
5818 * note: we do a fd_remove and not a delete
5819 * because the fd is owned by the engine.
5820 * the engine is responsible to close
5821 */
5822 for (i=0 ; i < num_all_fds ; i++)
5823 fd_remove(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005824 }
5825#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005826 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01005827 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005828 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005829 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005830 _HA_ATOMIC_SUB(&sslconns, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005831 }
Emeric Brun46591952012-05-18 15:47:34 +02005832}
5833
5834/* This function tries to perform a clean shutdown on an SSL connection, and in
5835 * any case, flags the connection as reusable if no handshake was in progress.
5836 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005837static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02005838{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005839 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005840
Willy Tarreau911db9b2020-01-23 16:27:54 +01005841 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005842 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01005843 if (!clean)
5844 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005845 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005846 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005847 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01005848 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005849 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005850 ERR_clear_error();
5851 }
Emeric Brun46591952012-05-18 15:47:34 +02005852}
5853
William Lallemandd4f946c2019-12-05 10:26:40 +01005854/* fill a buffer with the algorithm and size of a public key */
William Lallemandda8584c2020-05-14 10:14:37 +02005855int cert_get_pkey_algo(X509 *crt, struct buffer *out)
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01005856{
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01005857 int bits = 0;
5858 int sig = TLSEXT_signature_anonymous;
5859 int len = -1;
Emmanuel Hocdetc3775d22019-11-04 18:19:32 +01005860 EVP_PKEY *pkey;
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01005861
Emmanuel Hocdetc3775d22019-11-04 18:19:32 +01005862 pkey = X509_get_pubkey(crt);
5863 if (pkey) {
5864 bits = EVP_PKEY_bits(pkey);
5865 switch(EVP_PKEY_base_id(pkey)) {
5866 case EVP_PKEY_RSA:
5867 sig = TLSEXT_signature_rsa;
5868 break;
5869 case EVP_PKEY_EC:
5870 sig = TLSEXT_signature_ecdsa;
5871 break;
5872 case EVP_PKEY_DSA:
5873 sig = TLSEXT_signature_dsa;
5874 break;
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01005875 }
Emmanuel Hocdetc3775d22019-11-04 18:19:32 +01005876 EVP_PKEY_free(pkey);
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01005877 }
5878
5879 switch(sig) {
5880 case TLSEXT_signature_rsa:
5881 len = chunk_printf(out, "RSA%d", bits);
5882 break;
5883 case TLSEXT_signature_ecdsa:
5884 len = chunk_printf(out, "EC%d", bits);
5885 break;
5886 case TLSEXT_signature_dsa:
5887 len = chunk_printf(out, "DSA%d", bits);
5888 break;
5889 default:
5890 return 0;
5891 }
5892 if (len < 0)
5893 return 0;
5894 return 1;
5895}
5896
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005897/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01005898int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
5899{
5900 struct ssl_sock_ctx *ctx;
5901 X509 *crt;
5902
5903 if (!ssl_sock_is_ssl(conn))
5904 return 0;
5905
5906 ctx = conn->xprt_ctx;
5907
5908 crt = SSL_get_certificate(ctx->ssl);
5909 if (!crt)
5910 return 0;
5911
5912 return cert_get_pkey_algo(crt, out);
5913}
5914
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005915/* used for ppv2 cert signature (can be used for logging) */
5916const char *ssl_sock_get_cert_sig(struct connection *conn)
5917{
Christopher Faulet82004142019-09-10 10:12:03 +02005918 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005919
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005920 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
5921 X509 *crt;
5922
5923 if (!ssl_sock_is_ssl(conn))
5924 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005925 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005926 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005927 if (!crt)
5928 return NULL;
5929 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
5930 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
5931}
5932
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005933/* used for ppv2 authority */
5934const char *ssl_sock_get_sni(struct connection *conn)
5935{
5936#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02005937 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005938
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005939 if (!ssl_sock_is_ssl(conn))
5940 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005941 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005942 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005943#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01005944 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005945#endif
5946}
5947
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005948/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005949const char *ssl_sock_get_cipher_name(struct connection *conn)
5950{
Christopher Faulet82004142019-09-10 10:12:03 +02005951 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005952
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005953 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005954 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005955 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005956 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005957}
5958
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005959/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005960const char *ssl_sock_get_proto_version(struct connection *conn)
5961{
Christopher Faulet82004142019-09-10 10:12:03 +02005962 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005963
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005964 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005965 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005966 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005967 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005968}
5969
Willy Tarreau8d598402012-10-22 17:58:39 +02005970/* Extract a serial from a cert, and copy it to a chunk.
5971 * Returns 1 if serial is found and copied, 0 if no serial found and
5972 * -1 if output is not large enough.
5973 */
William Lallemandda8584c2020-05-14 10:14:37 +02005974int ssl_sock_get_serial(X509 *crt, struct buffer *out)
Willy Tarreau8d598402012-10-22 17:58:39 +02005975{
5976 ASN1_INTEGER *serial;
5977
5978 serial = X509_get_serialNumber(crt);
5979 if (!serial)
5980 return 0;
5981
5982 if (out->size < serial->length)
5983 return -1;
5984
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005985 memcpy(out->area, serial->data, serial->length);
5986 out->data = serial->length;
Willy Tarreau8d598402012-10-22 17:58:39 +02005987 return 1;
5988}
5989
Emeric Brun43e79582014-10-29 19:03:26 +01005990/* Extract a cert to der, and copy it to a chunk.
Joseph Herlant017b3da2018-11-15 09:07:59 -08005991 * Returns 1 if the cert is found and copied, 0 on der conversion failure
5992 * and -1 if the output is not large enough.
Emeric Brun43e79582014-10-29 19:03:26 +01005993 */
William Lallemandef761072020-05-15 09:52:16 +02005994int ssl_sock_crt2der(X509 *crt, struct buffer *out)
Emeric Brun43e79582014-10-29 19:03:26 +01005995{
5996 int len;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005997 unsigned char *p = (unsigned char *) out->area;;
Emeric Brun43e79582014-10-29 19:03:26 +01005998
5999 len =i2d_X509(crt, NULL);
6000 if (len <= 0)
6001 return 1;
6002
6003 if (out->size < len)
6004 return -1;
6005
6006 i2d_X509(crt,&p);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006007 out->data = len;
Emeric Brun43e79582014-10-29 19:03:26 +01006008 return 1;
6009}
6010
Emeric Brunce5ad802012-10-22 14:11:22 +02006011
Willy Tarreau83061a82018-07-13 11:56:34 +02006012/* Copy Date in ASN1_UTCTIME format in struct buffer out.
Emeric Brunce5ad802012-10-22 14:11:22 +02006013 * Returns 1 if serial is found and copied, 0 if no valid time found
6014 * and -1 if output is not large enough.
6015 */
William Lallemandef761072020-05-15 09:52:16 +02006016int ssl_sock_get_time(ASN1_TIME *tm, struct buffer *out)
Emeric Brunce5ad802012-10-22 14:11:22 +02006017{
6018 if (tm->type == V_ASN1_GENERALIZEDTIME) {
6019 ASN1_GENERALIZEDTIME *gentm = (ASN1_GENERALIZEDTIME *)tm;
6020
6021 if (gentm->length < 12)
6022 return 0;
6023 if (gentm->data[0] != 0x32 || gentm->data[1] != 0x30)
6024 return 0;
6025 if (out->size < gentm->length-2)
6026 return -1;
6027
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006028 memcpy(out->area, gentm->data+2, gentm->length-2);
6029 out->data = gentm->length-2;
Emeric Brunce5ad802012-10-22 14:11:22 +02006030 return 1;
6031 }
6032 else if (tm->type == V_ASN1_UTCTIME) {
6033 ASN1_UTCTIME *utctm = (ASN1_UTCTIME *)tm;
6034
6035 if (utctm->length < 10)
6036 return 0;
6037 if (utctm->data[0] >= 0x35)
6038 return 0;
6039 if (out->size < utctm->length)
6040 return -1;
6041
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006042 memcpy(out->area, utctm->data, utctm->length);
6043 out->data = utctm->length;
Emeric Brunce5ad802012-10-22 14:11:22 +02006044 return 1;
6045 }
6046
6047 return 0;
6048}
6049
Emeric Brun87855892012-10-17 17:39:35 +02006050/* Extract an entry from a X509_NAME and copy its value to an output chunk.
6051 * Returns 1 if entry found, 0 if entry not found, or -1 if output not large enough.
6052 */
William Lallemandef761072020-05-15 09:52:16 +02006053int ssl_sock_get_dn_entry(X509_NAME *a, const struct buffer *entry, int pos,
6054 struct buffer *out)
Emeric Brun87855892012-10-17 17:39:35 +02006055{
6056 X509_NAME_ENTRY *ne;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006057 ASN1_OBJECT *obj;
6058 ASN1_STRING *data;
6059 const unsigned char *data_ptr;
6060 int data_len;
Emeric Brun87855892012-10-17 17:39:35 +02006061 int i, j, n;
6062 int cur = 0;
6063 const char *s;
6064 char tmp[128];
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006065 int name_count;
6066
6067 name_count = X509_NAME_entry_count(a);
Emeric Brun87855892012-10-17 17:39:35 +02006068
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006069 out->data = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006070 for (i = 0; i < name_count; i++) {
Emeric Brun87855892012-10-17 17:39:35 +02006071 if (pos < 0)
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006072 j = (name_count-1) - i;
Emeric Brun87855892012-10-17 17:39:35 +02006073 else
6074 j = i;
6075
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006076 ne = X509_NAME_get_entry(a, j);
6077 obj = X509_NAME_ENTRY_get_object(ne);
6078 data = X509_NAME_ENTRY_get_data(ne);
6079 data_ptr = ASN1_STRING_get0_data(data);
6080 data_len = ASN1_STRING_length(data);
6081 n = OBJ_obj2nid(obj);
Emeric Brun87855892012-10-17 17:39:35 +02006082 if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006083 i2t_ASN1_OBJECT(tmp, sizeof(tmp), obj);
Emeric Brun87855892012-10-17 17:39:35 +02006084 s = tmp;
6085 }
6086
6087 if (chunk_strcasecmp(entry, s) != 0)
6088 continue;
6089
6090 if (pos < 0)
6091 cur--;
6092 else
6093 cur++;
6094
6095 if (cur != pos)
6096 continue;
6097
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006098 if (data_len > out->size)
Emeric Brun87855892012-10-17 17:39:35 +02006099 return -1;
6100
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006101 memcpy(out->area, data_ptr, data_len);
6102 out->data = data_len;
Emeric Brun87855892012-10-17 17:39:35 +02006103 return 1;
6104 }
6105
6106 return 0;
6107
William Lallemandd4f946c2019-12-05 10:26:40 +01006108}
6109
6110/*
Elliot Otchet71f82972020-01-15 08:12:14 -05006111 * Extract the DN in the specified format from the X509_NAME and copy result to a chunk.
6112 * Currently supports rfc2253 for returning LDAP V3 DNs.
6113 * Returns 1 if dn entries exist, 0 if no dn entry was found.
6114 */
William Lallemandef761072020-05-15 09:52:16 +02006115int ssl_sock_get_dn_formatted(X509_NAME *a, const struct buffer *format, struct buffer *out)
Elliot Otchet71f82972020-01-15 08:12:14 -05006116{
6117 BIO *bio = NULL;
6118 int ret = 0;
6119 int data_len = 0;
6120
6121 if (chunk_strcmp(format, "rfc2253") == 0) {
6122 bio = BIO_new(BIO_s_mem());
6123 if (bio == NULL)
6124 goto out;
6125
6126 if (X509_NAME_print_ex(bio, a, 0, XN_FLAG_RFC2253) < 0)
6127 goto out;
6128
6129 if ((data_len = BIO_read(bio, out->area, out->size)) <= 0)
6130 goto out;
6131
6132 out->data = data_len;
6133
6134 ret = 1;
6135 }
6136out:
6137 if (bio)
6138 BIO_free(bio);
6139 return ret;
6140}
6141
Emeric Brun87855892012-10-17 17:39:35 +02006142/* Extract and format full DN from a X509_NAME and copy result into a chunk
6143 * Returns 1 if dn entries exits, 0 if no dn entry found or -1 if output is not large enough.
6144 */
William Lallemandda8584c2020-05-14 10:14:37 +02006145int ssl_sock_get_dn_oneline(X509_NAME *a, struct buffer *out)
Emeric Brun87855892012-10-17 17:39:35 +02006146{
6147 X509_NAME_ENTRY *ne;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006148 ASN1_OBJECT *obj;
6149 ASN1_STRING *data;
6150 const unsigned char *data_ptr;
6151 int data_len;
Emeric Brun87855892012-10-17 17:39:35 +02006152 int i, n, ln;
6153 int l = 0;
6154 const char *s;
6155 char *p;
6156 char tmp[128];
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006157 int name_count;
6158
6159
6160 name_count = X509_NAME_entry_count(a);
Emeric Brun87855892012-10-17 17:39:35 +02006161
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006162 out->data = 0;
6163 p = out->area;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006164 for (i = 0; i < name_count; i++) {
6165 ne = X509_NAME_get_entry(a, i);
6166 obj = X509_NAME_ENTRY_get_object(ne);
6167 data = X509_NAME_ENTRY_get_data(ne);
6168 data_ptr = ASN1_STRING_get0_data(data);
6169 data_len = ASN1_STRING_length(data);
6170 n = OBJ_obj2nid(obj);
Emeric Brun87855892012-10-17 17:39:35 +02006171 if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006172 i2t_ASN1_OBJECT(tmp, sizeof(tmp), obj);
Emeric Brun87855892012-10-17 17:39:35 +02006173 s = tmp;
6174 }
6175 ln = strlen(s);
6176
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006177 l += 1 + ln + 1 + data_len;
Emeric Brun87855892012-10-17 17:39:35 +02006178 if (l > out->size)
6179 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006180 out->data = l;
Emeric Brun87855892012-10-17 17:39:35 +02006181
6182 *(p++)='/';
6183 memcpy(p, s, ln);
6184 p += ln;
6185 *(p++)='=';
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006186 memcpy(p, data_ptr, data_len);
6187 p += data_len;
Emeric Brun87855892012-10-17 17:39:35 +02006188 }
6189
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006190 if (!out->data)
Emeric Brun87855892012-10-17 17:39:35 +02006191 return 0;
6192
6193 return 1;
6194}
6195
Olivier Houchardab28a322018-12-21 19:45:40 +01006196void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6197{
6198#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02006199 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006200
Olivier Houcharde488ea82019-06-28 14:10:33 +02006201 if (!ssl_sock_is_ssl(conn))
6202 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006203 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006204 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006205#endif
6206}
6207
Willy Tarreau119a4082016-12-22 21:58:38 +01006208/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6209 * to disable SNI.
6210 */
Willy Tarreau63076412015-07-10 11:33:32 +02006211void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6212{
6213#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006214 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006215
Willy Tarreau119a4082016-12-22 21:58:38 +01006216 char *prev_name;
6217
Willy Tarreau63076412015-07-10 11:33:32 +02006218 if (!ssl_sock_is_ssl(conn))
6219 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006220 ctx = conn->xprt_ctx;
Willy Tarreau63076412015-07-10 11:33:32 +02006221
Willy Tarreau119a4082016-12-22 21:58:38 +01006222 /* if the SNI changes, we must destroy the reusable context so that a
6223 * new connection will present a new SNI. As an optimization we could
6224 * later imagine having a small cache of ssl_ctx to hold a few SNI per
6225 * server.
6226 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006227 prev_name = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau119a4082016-12-22 21:58:38 +01006228 if ((!prev_name && hostname) ||
6229 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006230 SSL_set_session(ctx->ssl, NULL);
Willy Tarreau119a4082016-12-22 21:58:38 +01006231
Olivier Houchard66ab4982019-02-26 18:37:15 +01006232 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006233#endif
6234}
6235
Emeric Brun0abf8362014-06-24 18:26:41 +02006236/* Extract peer certificate's common name into the chunk dest
6237 * Returns
6238 * the len of the extracted common name
6239 * or 0 if no CN found in DN
6240 * or -1 on error case (i.e. no peer certificate)
6241 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006242int ssl_sock_get_remote_common_name(struct connection *conn,
6243 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006244{
Christopher Faulet82004142019-09-10 10:12:03 +02006245 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04006246 X509 *crt = NULL;
6247 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006248 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006249 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006250 .area = (char *)&find_cn,
6251 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006252 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006253 int result = -1;
David Safb76832014-05-08 23:42:08 -04006254
6255 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02006256 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02006257 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006258
6259 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006260 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006261 if (!crt)
6262 goto out;
6263
6264 name = X509_get_subject_name(crt);
6265 if (!name)
6266 goto out;
David Safb76832014-05-08 23:42:08 -04006267
Emeric Brun0abf8362014-06-24 18:26:41 +02006268 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6269out:
David Safb76832014-05-08 23:42:08 -04006270 if (crt)
6271 X509_free(crt);
6272
6273 return result;
6274}
6275
Dave McCowan328fb582014-07-30 10:39:13 -04006276/* returns 1 if client passed a certificate for this session, 0 if not */
6277int ssl_sock_get_cert_used_sess(struct connection *conn)
6278{
Christopher Faulet82004142019-09-10 10:12:03 +02006279 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006280 X509 *crt = NULL;
6281
6282 if (!ssl_sock_is_ssl(conn))
6283 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006284 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006285
6286 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006287 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006288 if (!crt)
6289 return 0;
6290
6291 X509_free(crt);
6292 return 1;
6293}
6294
6295/* returns 1 if client passed a certificate for this connection, 0 if not */
6296int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006297{
Christopher Faulet82004142019-09-10 10:12:03 +02006298 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006299
David Safb76832014-05-08 23:42:08 -04006300 if (!ssl_sock_is_ssl(conn))
6301 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006302 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006303 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006304}
6305
6306/* returns result from SSL verify */
6307unsigned int ssl_sock_get_verify_result(struct connection *conn)
6308{
Christopher Faulet82004142019-09-10 10:12:03 +02006309 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006310
David Safb76832014-05-08 23:42:08 -04006311 if (!ssl_sock_is_ssl(conn))
6312 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006313 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006314 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006315}
6316
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006317/* Returns the application layer protocol name in <str> and <len> when known.
6318 * Zero is returned if the protocol name was not found, otherwise non-zero is
6319 * returned. The string is allocated in the SSL context and doesn't have to be
6320 * freed by the caller. NPN is also checked if available since older versions
6321 * of openssl (1.0.1) which are more common in field only support this one.
6322 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006323static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006324{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006325#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6326 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006327 struct ssl_sock_ctx *ctx = xprt_ctx;
6328 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006329 return 0;
6330
6331 *str = NULL;
6332
6333#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006334 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006335 if (*str)
6336 return 1;
6337#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006338#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006339 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006340 if (*str)
6341 return 1;
6342#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006343#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006344 return 0;
6345}
6346
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006347/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006348int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006349{
6350 X509 *ca;
6351 X509_NAME *name = NULL;
6352 ASN1_OCTET_STRING *skid = NULL;
6353 STACK_OF(X509) *chain = NULL;
6354 struct issuer_chain *issuer;
6355 struct eb64_node *node;
6356 char *path;
6357 u64 key;
6358 int ret = 0;
6359
6360 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6361 if (chain == NULL) {
6362 chain = sk_X509_new_null();
6363 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6364 name = X509_get_subject_name(ca);
6365 }
6366 if (!sk_X509_push(chain, ca)) {
6367 X509_free(ca);
6368 goto end;
6369 }
6370 }
6371 if (!chain) {
6372 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6373 goto end;
6374 }
6375 if (!skid) {
6376 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6377 goto end;
6378 }
6379 if (!name) {
6380 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6381 goto end;
6382 }
6383 key = XXH64(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006384 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006385 issuer = container_of(node, typeof(*issuer), node);
6386 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6387 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6388 goto end;
6389 }
6390 }
6391 issuer = calloc(1, sizeof *issuer);
6392 path = strdup(fp);
6393 if (!issuer || !path) {
6394 free(issuer);
6395 free(path);
6396 goto end;
6397 }
6398 issuer->node.key = key;
6399 issuer->path = path;
6400 issuer->chain = chain;
6401 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006402 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006403 ret = 1;
6404 end:
6405 if (skid)
6406 ASN1_OCTET_STRING_free(skid);
6407 if (chain)
6408 sk_X509_pop_free(chain, X509_free);
6409 return ret;
6410}
6411
William Lallemandda8584c2020-05-14 10:14:37 +02006412 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006413{
6414 AUTHORITY_KEYID *akid;
6415 struct issuer_chain *issuer = NULL;
6416
6417 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
6418 if (akid) {
6419 struct eb64_node *node;
6420 u64 hk;
6421 hk = XXH64(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
6422 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6423 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6424 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6425 issuer = ti;
6426 break;
6427 }
6428 }
6429 AUTHORITY_KEYID_free(akid);
6430 }
6431 return issuer;
6432}
6433
William Lallemanddad31052020-05-14 17:47:32 +02006434void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006435{
6436 struct eb64_node *node, *back;
6437 struct issuer_chain *issuer;
6438
William Lallemande0f3fd52020-02-25 14:53:06 +01006439 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006440 while (node) {
6441 issuer = container_of(node, typeof(*issuer), node);
6442 back = eb64_next(node);
6443 eb64_delete(node);
6444 free(issuer->path);
6445 sk_X509_pop_free(issuer->chain, X509_free);
6446 free(issuer);
6447 node = back;
6448 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006449}
6450
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006451#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006452static int ssl_check_async_engine_count(void) {
6453 int err_code = 0;
6454
Emeric Brun3854e012017-05-17 20:42:48 +02006455 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006456 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006457 err_code = ERR_ABORT;
6458 }
6459 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006460}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006461#endif
6462
William Lallemand32af2032016-10-29 18:09:35 +02006463/* This function is used with TLS ticket keys management. It permits to browse
6464 * each reference. The variable <getnext> must contain the current node,
6465 * <end> point to the root node.
6466 */
6467#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6468static inline
6469struct tls_keys_ref *tlskeys_list_get_next(struct tls_keys_ref *getnext, struct list *end)
6470{
6471 struct tls_keys_ref *ref = getnext;
6472
6473 while (1) {
6474
6475 /* Get next list entry. */
6476 ref = LIST_NEXT(&ref->list, struct tls_keys_ref *, list);
6477
6478 /* If the entry is the last of the list, return NULL. */
6479 if (&ref->list == end)
6480 return NULL;
6481
6482 return ref;
6483 }
6484}
6485
6486static inline
6487struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6488{
6489 int id;
6490 char *error;
6491
6492 /* If the reference starts by a '#', this is numeric id. */
6493 if (reference[0] == '#') {
6494 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6495 id = strtol(reference + 1, &error, 10);
6496 if (*error != '\0')
6497 return NULL;
6498
6499 /* Perform the unique id lookup. */
6500 return tlskeys_ref_lookupid(id);
6501 }
6502
6503 /* Perform the string lookup. */
6504 return tlskeys_ref_lookup(reference);
6505}
6506#endif
6507
6508
6509#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6510
6511static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6512
6513static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6514 return cli_io_handler_tlskeys_files(appctx);
6515}
6516
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006517/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6518 * (next index to be dumped), and cli.p0 (next key reference).
6519 */
William Lallemand32af2032016-10-29 18:09:35 +02006520static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6521
6522 struct stream_interface *si = appctx->owner;
6523
6524 switch (appctx->st2) {
6525 case STAT_ST_INIT:
6526 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006527 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006528 * later and restart at the state "STAT_ST_INIT".
6529 */
6530 chunk_reset(&trash);
6531
6532 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6533 chunk_appendf(&trash, "# id secret\n");
6534 else
6535 chunk_appendf(&trash, "# id (file)\n");
6536
Willy Tarreau06d80a92017-10-19 14:32:15 +02006537 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006538 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006539 return 0;
6540 }
6541
William Lallemand32af2032016-10-29 18:09:35 +02006542 /* Now, we start the browsing of the references lists.
6543 * Note that the following call to LIST_ELEM return bad pointer. The only
6544 * available field of this pointer is <list>. It is used with the function
6545 * tlskeys_list_get_next() for retruning the first available entry
6546 */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006547 if (appctx->ctx.cli.p0 == NULL) {
6548 appctx->ctx.cli.p0 = LIST_ELEM(&tlskeys_reference, struct tls_keys_ref *, list);
6549 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006550 }
6551
6552 appctx->st2 = STAT_ST_LIST;
6553 /* fall through */
6554
6555 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006556 while (appctx->ctx.cli.p0) {
6557 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006558
6559 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006560 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006561 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006562
6563 if (appctx->ctx.cli.i1 == 0)
6564 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6565
William Lallemand32af2032016-10-29 18:09:35 +02006566 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006567 int head;
6568
6569 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6570 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006571 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006572 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006573
6574 chunk_reset(t2);
6575 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006576 if (ref->key_size_bits == 128) {
6577 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6578 sizeof(struct tls_sess_key_128),
6579 t2->area, t2->size);
6580 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6581 t2->area);
6582 }
6583 else if (ref->key_size_bits == 256) {
6584 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6585 sizeof(struct tls_sess_key_256),
6586 t2->area, t2->size);
6587 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6588 t2->area);
6589 }
6590 else {
6591 /* This case should never happen */
6592 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6593 }
William Lallemand32af2032016-10-29 18:09:35 +02006594
Willy Tarreau06d80a92017-10-19 14:32:15 +02006595 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006596 /* let's try again later from this stream. We add ourselves into
6597 * this stream's users so that it can remove us upon termination.
6598 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006599 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006600 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006601 return 0;
6602 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006603 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006604 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006605 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006606 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006607 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006608 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006609 /* let's try again later from this stream. We add ourselves into
6610 * this stream's users so that it can remove us upon termination.
6611 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006612 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006613 return 0;
6614 }
6615
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006616 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006617 break;
6618
6619 /* get next list entry and check the end of the list */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006620 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006621 }
6622
6623 appctx->st2 = STAT_ST_FIN;
6624 /* fall through */
6625
6626 default:
6627 appctx->st2 = STAT_ST_FIN;
6628 return 1;
6629 }
6630 return 0;
6631}
6632
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006633/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006634static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006635{
William Lallemand32af2032016-10-29 18:09:35 +02006636 /* no parameter, shows only file list */
6637 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006638 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006639 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006640 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006641 }
6642
6643 if (args[2][0] == '*') {
6644 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006645 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006646 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006647 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006648 if (!appctx->ctx.cli.p0)
6649 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006650 }
William Lallemand32af2032016-10-29 18:09:35 +02006651 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006652 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006653}
6654
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006655static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006656{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006657 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006658 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006659
William Lallemand32af2032016-10-29 18:09:35 +02006660 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006661 if (!*args[3] || !*args[4])
6662 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 +02006663
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006664 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006665 if (!ref)
6666 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006667
Willy Tarreau1c913e42018-08-22 05:26:57 +02006668 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006669 if (ret < 0)
6670 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006671
Willy Tarreau1c913e42018-08-22 05:26:57 +02006672 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006673 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6674 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006675
Willy Tarreau9d008692019-08-09 11:21:01 +02006676 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006677}
William Lallemandd4f946c2019-12-05 10:26:40 +01006678#endif
William Lallemand419e6342020-04-08 12:05:39 +02006679
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006680static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006681{
6682#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6683 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006684 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006685
6686 if (!payload)
6687 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006688
6689 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006690 if (!*payload)
6691 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006692
6693 /* remove \r and \n from the payload */
6694 for (i = 0, j = 0; payload[i]; i++) {
6695 if (payload[i] == '\r' || payload[i] == '\n')
6696 continue;
6697 payload[j++] = payload[i];
6698 }
6699 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006700
Willy Tarreau1c913e42018-08-22 05:26:57 +02006701 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006702 if (ret < 0)
6703 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006704
Willy Tarreau1c913e42018-08-22 05:26:57 +02006705 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02006706 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02006707 if (err)
6708 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
6709 else
6710 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006711 }
Willy Tarreau9d008692019-08-09 11:21:01 +02006712
6713 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006714#else
Willy Tarreau9d008692019-08-09 11:21:01 +02006715 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 +02006716#endif
6717
Elliot Otchet71f82972020-01-15 08:12:14 -05006718}
6719
William Lallemand32af2032016-10-29 18:09:35 +02006720/* register cli keywords */
6721static struct cli_kw_list cli_kws = {{ },{
6722#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6723 { { "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 +02006724 { { "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 +02006725#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006726 { { "set", "ssl", "ocsp-response", NULL }, NULL, cli_parse_set_ocspresponse, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02006727 { { NULL }, NULL, NULL, NULL }
6728}};
6729
Willy Tarreau0108d902018-11-25 19:14:37 +01006730INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02006731
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02006732/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02006733struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02006734 .snd_buf = ssl_sock_from_buf,
6735 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01006736 .subscribe = ssl_subscribe,
6737 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02006738 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02006739 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02006740 .rcv_pipe = NULL,
6741 .snd_pipe = NULL,
6742 .shutr = NULL,
6743 .shutw = ssl_sock_shutw,
6744 .close = ssl_sock_close,
6745 .init = ssl_sock_init,
Willy Tarreau55d37912016-12-21 23:38:39 +01006746 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01006747 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01006748 .prepare_srv = ssl_sock_prepare_srv_ctx,
6749 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006750 .get_alpn = ssl_sock_get_alpn,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01006751 .name = "SSL",
Emeric Brun46591952012-05-18 15:47:34 +02006752};
6753
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006754enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
6755 struct session *sess, struct stream *s, int flags)
6756{
6757 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006758 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006759
6760 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006761 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006762
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006763 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006764 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006765 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006766 s->req.flags |= CF_READ_NULL;
6767 return ACT_RET_YIELD;
6768 }
6769 }
6770 return (ACT_RET_CONT);
6771}
6772
6773static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
6774{
6775 rule->action_ptr = ssl_action_wait_for_hs;
6776
6777 return ACT_RET_PRS_OK;
6778}
6779
6780static struct action_kw_list http_req_actions = {ILH, {
6781 { "wait-for-handshake", ssl_parse_wait_for_hs },
6782 { /* END */ }
6783}};
6784
Willy Tarreau0108d902018-11-25 19:14:37 +01006785INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
6786
Willy Tarreau5db847a2019-05-09 14:13:35 +02006787#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006788
6789static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6790{
6791 if (ptr) {
6792 chunk_destroy(ptr);
6793 free(ptr);
6794 }
6795}
6796
6797#endif
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006798static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6799{
Willy Tarreaubafbe012017-11-24 17:34:44 +01006800 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006801}
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006802
Emeric Brun46591952012-05-18 15:47:34 +02006803__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02006804static void __ssl_sock_init(void)
6805{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006806#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006807 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006808 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006809#endif
Emeric Brun46591952012-05-18 15:47:34 +02006810
Willy Tarreauef934602016-12-22 23:12:01 +01006811 if (global_ssl.listen_default_ciphers)
6812 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
6813 if (global_ssl.connect_default_ciphers)
6814 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Emmanuel Hocdet839af572019-05-14 16:27:35 +02006815#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02006816 if (global_ssl.listen_default_ciphersuites)
6817 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
6818 if (global_ssl.connect_default_ciphersuites)
6819 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
6820#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01006821
Willy Tarreau13e14102016-12-22 20:25:26 +01006822 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006823#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02006824 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08006825#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006826#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006827 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006828 n = sk_SSL_COMP_num(cm);
6829 while (n--) {
6830 (void) sk_SSL_COMP_pop(cm);
6831 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006832#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006833
Willy Tarreau5db847a2019-05-09 14:13:35 +02006834#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006835 ssl_locking_init();
6836#endif
Willy Tarreau5db847a2019-05-09 14:13:35 +02006837#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006838 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
6839#endif
Thierry FOURNIER28962c92018-06-17 21:37:05 +02006840 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02006841 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 +02006842#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006843 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006844 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006845#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01006846#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6847 hap_register_post_check(tlskeys_finalize_config);
6848#endif
Willy Tarreau80713382018-11-26 10:19:54 +01006849
6850 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
6851 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
6852
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006853 hap_register_post_deinit(ssl_free_global_issuers);
6854
Willy Tarreau80713382018-11-26 10:19:54 +01006855#ifndef OPENSSL_NO_DH
6856 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
6857 hap_register_post_deinit(ssl_free_dh);
6858#endif
6859#ifndef OPENSSL_NO_ENGINE
6860 hap_register_post_deinit(ssl_free_engines);
6861#endif
6862 /* Load SSL string for the verbose & debug mode. */
6863 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02006864 ha_meth = BIO_meth_new(0x666, "ha methods");
6865 BIO_meth_set_write(ha_meth, ha_ssl_write);
6866 BIO_meth_set_read(ha_meth, ha_ssl_read);
6867 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
6868 BIO_meth_set_create(ha_meth, ha_ssl_new);
6869 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
6870 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
6871 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02006872
6873 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006874
Dragan Dosen9ac98092020-05-11 15:51:45 +02006875 /* Try to register dedicated SSL/TLS protocol message callbacks for
6876 * heartbleed attack (CVE-2014-0160) and clienthello.
6877 */
6878 hap_register_post_check(ssl_sock_register_msg_callbacks);
6879
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006880 /* Try to free all callbacks that were registered by using
6881 * ssl_sock_register_msg_callback().
6882 */
6883 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01006884}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01006885
Willy Tarreau80713382018-11-26 10:19:54 +01006886/* Compute and register the version string */
6887static void ssl_register_build_options()
6888{
6889 char *ptr = NULL;
6890 int i;
6891
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006892 memprintf(&ptr, "Built with OpenSSL version : "
6893#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006894 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006895#else /* OPENSSL_IS_BORINGSSL */
6896 OPENSSL_VERSION_TEXT
6897 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08006898 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02006899 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006900#endif
6901 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006902#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006903 "no (library version too old)"
6904#elif defined(OPENSSL_NO_TLSEXT)
6905 "no (disabled via OPENSSL_NO_TLSEXT)"
6906#else
6907 "yes"
6908#endif
6909 "", ptr);
6910
6911 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
6912#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
6913 "yes"
6914#else
6915#ifdef OPENSSL_NO_TLSEXT
6916 "no (because of OPENSSL_NO_TLSEXT)"
6917#else
6918 "no (version might be too old, 0.9.8f min needed)"
6919#endif
6920#endif
6921 "", ptr);
6922
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02006923 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
6924 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
6925 if (methodVersions[i].option)
6926 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006927
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006928 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01006929}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006930
Willy Tarreau80713382018-11-26 10:19:54 +01006931INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02006932
Emeric Brun46591952012-05-18 15:47:34 +02006933
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006934#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006935void ssl_free_engines(void) {
6936 struct ssl_engine_list *wl, *wlb;
6937 /* free up engine list */
6938 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
6939 ENGINE_finish(wl->e);
6940 ENGINE_free(wl->e);
6941 LIST_DEL(&wl->list);
6942 free(wl);
6943 }
6944}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006945#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02006946
Remi Gacogned3a23c32015-05-28 16:39:47 +02006947#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00006948void ssl_free_dh(void) {
6949 if (local_dh_1024) {
6950 DH_free(local_dh_1024);
6951 local_dh_1024 = NULL;
6952 }
6953 if (local_dh_2048) {
6954 DH_free(local_dh_2048);
6955 local_dh_2048 = NULL;
6956 }
6957 if (local_dh_4096) {
6958 DH_free(local_dh_4096);
6959 local_dh_4096 = NULL;
6960 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02006961 if (global_dh) {
6962 DH_free(global_dh);
6963 global_dh = NULL;
6964 }
Grant Zhang872f9c22017-01-21 01:10:18 +00006965}
6966#endif
6967
6968__attribute__((destructor))
6969static void __ssl_sock_deinit(void)
6970{
6971#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006972 if (ssl_ctx_lru_tree) {
6973 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01006974 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02006975 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02006976#endif
6977
Willy Tarreau5db847a2019-05-09 14:13:35 +02006978#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006979 ERR_remove_state(0);
6980 ERR_free_strings();
6981
6982 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08006983#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02006984
Willy Tarreau5db847a2019-05-09 14:13:35 +02006985#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006986 CRYPTO_cleanup_all_ex_data();
6987#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02006988 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02006989}
6990
Emeric Brun46591952012-05-18 15:47:34 +02006991/*
6992 * Local variables:
6993 * c-indent-level: 8
6994 * c-basic-offset: 8
6995 * End:
6996 */