The FreeRADIUS server $Id: 15bac2a4c627c01d1aa2047687b3418955ac7f00 $
Loading...
Searching...
No Matches
cache.c
Go to the documentation of this file.
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17/**
18 * $Id: 565532041f121500b51df88fa3a3393fb1da5b34 $
19 *
20 * @file tls/cache.c
21 * @brief Functions to support TLS session resumption
22 *
23 * @copyright 2015-2016 The FreeRADIUS server project
24 * @copyright 2021 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
25 */
26RCSID("$Id: 565532041f121500b51df88fa3a3393fb1da5b34 $")
27USES_APPLE_DEPRECATED_API /* OpenSSL API has been deprecated by Apple */
28
29#ifdef WITH_TLS
30#define LOG_PREFIX "tls"
31
32#include <freeradius-devel/internal/internal.h>
33#include <freeradius-devel/server/pair.h>
34#include <freeradius-devel/server/module_rlm.h>
35#include <freeradius-devel/unlang/function.h>
36#include <freeradius-devel/unlang/subrequest.h>
37#include <freeradius-devel/unlang/interpret.h>
38#include <freeradius-devel/util/debug.h>
39
40#include "attrs.h"
41#include "base.h"
42#include "cache.h"
43#include "log.h"
44#include "strerror.h"
45#include "verify.h"
46
47#include <openssl/ssl.h>
48#include <openssl/kdf.h>
49
50/** Retrieve session ID (in binary form) from the session
51 *
52 * @param[in] ctx Where to allocate the array to hold the session id.
53 * @param[in] sess to retrieve the ID for.
54 * @return A copy of the session id.
55 */
56uint8_t *fr_tls_cache_id(TALLOC_CTX *ctx, SSL_SESSION *sess)
57{
58 unsigned int len;
59 uint8_t const *id;
60
61 id = SSL_SESSION_get_id(sess, &len);
62 if (unlikely(!id)) return NULL;
63
64 return talloc_typed_memdup(ctx, id, len);
65}
66
67/** Retrieve session ID (in binary form), and assign it to a box
68 *
69 * @note Box will be reinitialised
70 *
71 * @param[out] out Where to write the session ID.
72 * @param[in] sess to retrieve the ID for.
73 */
74static inline CC_HINT(always_inline, nonnull)
75int fr_tls_cache_id_to_box_shallow(fr_value_box_t *out, SSL_SESSION *sess)
76{
77 unsigned int len;
78 uint8_t const *id;
79
80 id = SSL_SESSION_get_id(sess, &len);
81 if (unlikely(!id)) return -1;
82
83 fr_value_box_memdup_shallow(out, NULL, id, len, true);
84
85 return 0;
86}
87
88/** Create a temporary boxed version of the session ID
89 *
90 * @param[out] _box to place on the stack.
91 * @param[in] _sess to write to box.
92 */
93#define SESSION_ID(_box, _sess) \
94fr_value_box_t _box; \
95if (unlikely(fr_tls_cache_id_to_box_shallow(&_box, _sess) < 0)) fr_value_box_init_null(&_box)
96
97
98/** Add an attribute specifying the session id for the operation to be performed with.
99 *
100 * Adds the following attributes to the request:
101 *
102 * - &request.Session-Id
103 *
104 * Session identity will contain the binary session key used to create, retrieve
105 * and delete cache entries related to the SSL session.
106 *
107 * @param[in] request The current request.
108 * @param[in] session_id Identifier for the session.
109 */
110static inline CC_HINT(always_inline, nonnull(2))
111void tls_cache_session_id_to_vp(request_t *request, uint8_t const *session_id)
112{
113 fr_pair_t *vp;
115 fr_pair_value_memdup_buffer(vp, session_id, true);
116}
117
118static inline CC_HINT(always_inline, nonnull(2))
119void _tls_cache_load_state_reset(request_t *request, fr_tls_cache_t *cache, char const *func)
120{
121 if (cache->load.sess) {
123 SESSION_ID(sess_id, cache->load.sess);
124 ROPTIONAL(RDEBUG3, DEBUG3, "Session ID %pV - Freeing loaded session in %s", &sess_id, func);
125 }
126
127 SSL_SESSION_free(cache->load.sess);
128 cache->load.sess = NULL;
129 }
130 cache->load.state = FR_TLS_CACHE_LOAD_INIT;
131}
132#define tls_cache_load_state_reset(_request, _cache) _tls_cache_load_state_reset(_request, _cache, __FUNCTION__)
133
134static inline CC_HINT(always_inline, nonnull(2))
135void _tls_cache_store_state_reset(request_t *request, fr_tls_cache_t *cache, char const *func)
136{
137 if (cache->store.sess) {
139 SESSION_ID(sess_id, cache->store.sess);
140 ROPTIONAL(RDEBUG3, DEBUG3, "Session ID %pV - Freeing session to store in %s", &sess_id, func);
141 }
142 SSL_SESSION_free(cache->store.sess);
143 cache->store.sess = NULL;
144 }
145 cache->store.state = FR_TLS_CACHE_STORE_INIT;
146}
147#define tls_cache_store_state_reset(_request, _cache) _tls_cache_store_state_reset(_request, _cache, __FUNCTION__)
148
149static inline CC_HINT(always_inline)
150void _tls_cache_clear_state_reset(request_t *request, fr_tls_cache_t *cache, char const *func)
151{
152 if (cache->clear.id) {
154 ROPTIONAL(RDEBUG3, DEBUG3, "Session ID %pV - Freeing session ID to clear in %s",
155 fr_box_octets_buffer(cache->clear.id), func);
156 TALLOC_FREE(cache->clear.id);
157 }
158 }
159 cache->clear.state = FR_TLS_CACHE_CLEAR_INIT;
160}
161#define tls_cache_clear_state_reset(_request, _cache) _tls_cache_clear_state_reset(_request, _cache, __FUNCTION__)
162
163/** Serialize the session-state list and store it in the SSL_SESSION *
164 *
165 */
166static int tls_cache_app_data_set(request_t *request, SSL_SESSION *sess, uint32_t resumption_type)
167{
168 fr_dbuff_t dbuff;
169 fr_dbuff_uctx_talloc_t tctx;
170 fr_dcursor_t dcursor;
171 fr_pair_t *vp, *type_vp;
172 ssize_t slen;
173 int ret;
174
175 /*
176 * Add a temporary pair for the type of session resumption
177 */
179 type_vp->vp_uint32 = resumption_type;
180
181 if (RDEBUG_ENABLED2) {
182 SESSION_ID(sess_id, sess);
183
184 RDEBUG2("Session ID %pV - Adding session-state[*] to data", &sess_id);
185 RINDENT();
186 log_request_pair_list(L_DBG_LVL_2, request, NULL, &request->session_state_pairs, NULL);
187 REXDENT();
188 }
189
190 /*
191 * Absolute maximum is `0..2^16-1`.
192 *
193 * We leave OpenSSL 2k to add anything else
194 */
195 MEM(fr_dbuff_init_talloc(NULL, &dbuff, &tctx, 1024, 1024 * 62));
196
197 /*
198 * Encode the session-state contents and
199 * add it to the ticket.
200 */
201 for (vp = fr_pair_dcursor_init(&dcursor, &request->session_state_pairs);
202 vp;
203 vp = fr_dcursor_current(&dcursor)) {
204 slen = fr_internal_encode_pair(&dbuff, &dcursor, NULL);
205 if (slen < 0) {
206 SESSION_ID(sess_id, sess);
207
208 RPERROR("Session ID %pV - Failed serialising session-state list", &sess_id);
209 fr_dbuff_free_talloc(&dbuff);
210 return 0;
211 }
212 }
213
214 fr_pair_remove(&request->session_state_pairs, type_vp);
215
216 RHEXDUMP4(fr_dbuff_start(&dbuff), fr_dbuff_used(&dbuff), "session-ticket application data");
217
218 /*
219 * Pass the serialized session-state list
220 * over to OpenSSL.
221 */
222 ret = SSL_SESSION_set1_ticket_appdata(sess, fr_dbuff_start(&dbuff), fr_dbuff_used(&dbuff));
223 fr_dbuff_free_talloc(&dbuff); /* OpenSSL memdups the data */
224 if (ret != 1) {
225 SESSION_ID(sess_id, sess);
226
227 fr_tls_log(request, "Session ID %pV - Failed setting application data", &sess_id);
228 return -1;
229 }
230
231 return 0;
232}
233
234static int tls_cache_app_data_get(request_t *request, SSL_SESSION *sess)
235{
236 uint8_t *data;
237 size_t data_len;
238 fr_dbuff_t dbuff;
239 fr_pair_list_t tmp;
240
241 /*
242 * Extract the session-state list from the ticket.
243 */
244 if (SSL_SESSION_get0_ticket_appdata(sess, (void **)&data, &data_len) != 1) {
245 SESSION_ID(sess_id, sess);
246
247 fr_tls_log(request, "Session ID %pV - Failed retrieving application data", &sess_id);
248 return -1;
249 }
250
251 fr_pair_list_init(&tmp);
252 fr_dbuff_init(&dbuff, data, data_len);
253
254 RHEXDUMP4(fr_dbuff_start(&dbuff), fr_dbuff_len(&dbuff), "session application data");
255
256 /*
257 * Decode the session-state data into a temporary list.
258 *
259 * It's very important that we decode _all_ attributes,
260 * or disallow session resumption.
261 */
262 while (fr_dbuff_remaining(&dbuff) > 0) {
263 if (fr_internal_decode_pair_dbuff(request->session_state_ctx, &tmp,
264 fr_dict_root(request->dict), &dbuff, NULL) < 0) {
265 SESSION_ID(sess_id, sess);
266
267 fr_pair_list_free(&tmp);
268 RPEDEBUG("Session-ID %pV - Failed decoding session-state", &sess_id);
269 return -1;
270 }
271 }
272
273 if (RDEBUG_ENABLED2) {
274 SESSION_ID(sess_id, sess);
275
276 RDEBUG2("Session-ID %pV - Restoring session-state[*]", &sess_id);
277 RINDENT();
278 log_request_pair_list(L_DBG_LVL_2, request, NULL, &tmp, "&session-state.");
279 REXDENT();
280 }
281
282 fr_pair_list_append(&request->session_state_pairs, &tmp);
283
284 return 0;
285}
286
287/** Delete session data be deleted from the cache
288 *
289 * @param[in] sess to be deleted.
290 */
291static void tls_cache_delete_request(SSL_SESSION *sess)
292{
293 fr_tls_session_t *tls_session;
294 fr_tls_cache_t *tls_cache;
295 request_t *request;
296
297 tls_session = talloc_get_type_abort(SSL_SESSION_get_ex_data(sess, FR_TLS_EX_INDEX_TLS_SESSION), fr_tls_session_t);
298
299 if (!tls_session->cache) return;
300
301 request = fr_tls_session_request(tls_session->ssl);
302 tls_cache = tls_session->cache;
303
304 /*
305 * Request was cancelled just return without doing any work.
306 */
307 if (unlang_request_is_cancelled(request)) return;
308
309 fr_assert(tls_cache->clear.state == FR_TLS_CACHE_CLEAR_INIT);
310
311 /*
312 * Record the session to delete
313 */
314 tls_cache->clear.id = fr_tls_cache_id(tls_cache, sess);
315 if (!tls_cache->clear.id) {
316 RWDEBUG("Error retrieving Session ID");
317 return;
318 }
319
320 RDEBUG3("Session ID %pV - Requested session clear", fr_box_octets_buffer(tls_cache->clear.id));
321
322 tls_cache->clear.state = FR_TLS_CACHE_CLEAR_REQUESTED;
323
324 /*
325 * We store a copy of the pointer for the session
326 * in tls_session->session. If the session is
327 * being freed then this pointer must be invalid
328 * so clear it to prevent crashes in other areas
329 * of the code.
330 */
331 if (tls_session->session == sess) tls_session->session = NULL;
332
333 /*
334 * Previously the code called ASYNC_pause_job();
335 * assuming this callback would always be called
336 * from SSL_read() or another SSL function.
337 *
338 * Unfortunately it appears that the call path
339 * can also be triggered with SSL_CTX_remove_session
340 * if the reference count on the SSL_SESSION
341 * drops to zero.
342 *
343 * We now check the 'can_pause' flag to determine
344 * if we're inside a yieldable SSL_read call.
345 */
346 if (tls_session->can_pause) ASYNC_pause_job();
347}
348
349/** Process the result of `load session { ... }`
350 */
351static unlang_action_t tls_cache_load_result(UNUSED rlm_rcode_t *p_result, UNUSED int *priority,
352 request_t *request, void *uctx)
353{
354 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
355 fr_tls_cache_t *tls_cache = tls_session->cache;
356 fr_pair_t *vp;
357 uint8_t const *q, **p;
358 SSL_SESSION *sess;
359
360 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_packet_type);
361 if (!vp || (vp->vp_uint32 != enum_tls_packet_type_success->vb_uint32)) {
362 RWDEBUG("Failed acquiring session data");
363 error:
364 tls_cache->load.state = FR_TLS_CACHE_LOAD_FAILED;
366 }
367
368 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_session_data);
369 if (!vp) {
370 RWDEBUG("No cached session found");
371 goto error;
372 }
373
374 q = vp->vp_octets; /* openssl will mutate q, so we can't use vp_octets directly */
375 p = (unsigned char const **)&q;
376
377 sess = d2i_SSL_SESSION(NULL, p, vp->vp_length);
378 if (!sess) {
379 fr_tls_log(request, "Failed loading persisted session");
380 goto error;
381 }
382
383 if (RDEBUG_ENABLED3) {
384 SESSION_ID(sess_id, sess);
385
386 RDEBUG3("Session ID %pV - Read %zu bytes of data. "
387 "Session de-serialized successfully", &sess_id, vp->vp_length);
388 SSL_SESSION_print(fr_tls_request_log_bio(request, L_DBG, L_DBG_LVL_3), sess);
389 }
390
391 /*
392 * OpenSSL's API is very inconsistent.
393 *
394 * We need to set external data here, so it can be
395 * retrieved in fr_tls_cache_delete.
396 *
397 * ex_data is not serialised in i2d_SSL_SESSION
398 * so we don't have to bother unsetting it.
399 */
400 SSL_SESSION_set_ex_data(sess, FR_TLS_EX_INDEX_TLS_SESSION, fr_tls_session(tls_session->ssl));
401
402 tls_cache->load.state = FR_TLS_CACHE_LOAD_RETRIEVED;
403 tls_cache->load.sess = sess; /* This is consumed in tls_cache_load_cb */
404
406}
407
408/** Push a `load session { ... }` call into the current request, using a subrequest
409 *
410 * @param[in] request The current request.
411 * @param[in] tls_session The current TLS session.
412 * @return
413 * - UNLANG_ACTION_CALCULATE_RESULT on noop.
414 * - UNLANG_ACTION_PUSHED_CHILD on success.
415 * - UNLANG_ACTION_FAIL on failure.
416 */
417static unlang_action_t tls_cache_load_push(request_t *request, fr_tls_session_t *tls_session)
418{
419 fr_tls_cache_t *tls_cache = tls_session->cache;
420 fr_tls_conf_t *conf = fr_tls_session_conf(tls_session->ssl);
421 request_t *child;
422 fr_pair_t *vp;
424
425 if (tls_cache->load.state != FR_TLS_CACHE_LOAD_REQUESTED) return UNLANG_ACTION_CALCULATE_RESULT;
426
427 fr_assert(tls_cache->load.id);
428
429 MEM(child = unlang_subrequest_alloc(request, dict_tls));
430 request = child;
431
432 /*
433 * Setup the child request for loading
434 * session resumption data.
435 */
437 vp->vp_uint32 = enum_tls_packet_type_load_session->vb_uint32;
438
439 /*
440 * Add the session identifier we're
441 * trying to load.
442 */
443 tls_cache_session_id_to_vp(child, tls_cache->load.id);
444
445 /*
446 * Allocate a child, and set it up to call
447 * the TLS virtual server.
448 */
449 ua = fr_tls_call_push(child, tls_cache_load_result, conf, tls_session);
450 if (ua < 0) {
451 talloc_free(child);
452 tls_cache_load_state_reset(request, tls_cache);
453 return UNLANG_ACTION_FAIL;
454 }
455
456 return ua;
457}
458
459/** Process the result of `store session { ... }`
460 */
461static unlang_action_t tls_cache_store_result(UNUSED rlm_rcode_t *p_result, UNUSED int *priority,
462 request_t *request, void *uctx)
463{
464 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
465 fr_tls_cache_t *tls_cache = tls_session->cache;
466 fr_pair_t *vp;
467
468 tls_cache_store_state_reset(request, tls_cache);
469
470 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_packet_type);
471 if (vp && (vp->vp_uint32 == enum_tls_packet_type_success->vb_uint32)) {
472 tls_cache->store.state = FR_TLS_CACHE_STORE_PERSISTED; /* Avoid spurious clear calls */
473 } else {
474 RWDEBUG("Failed storing session data");
475 tls_cache->store.state = FR_TLS_CACHE_STORE_INIT;
476 }
477
479}
480
481/** Push a `store session { ... }` call into the current request, using a subrequest
482 *
483 * @param[in] request The current request.
484 * @param[in] conf TLS configuration.
485 * @param[in] tls_session The current TLS session.
486 * @return
487 * - UNLANG_ACTION_CALCULATE_RESULT on noop.
488 * - UNLANG_ACTION_PUSHED_CHILD on success.
489 * - UNLANG_ACTION_FAIL on failure.
490 */
491static inline CC_HINT(always_inline)
492unlang_action_t tls_cache_store_push(request_t *request, fr_tls_conf_t *conf, fr_tls_session_t *tls_session)
493{
494 fr_tls_cache_t *tls_cache = tls_session->cache;
495 size_t len, ret;
496
497 uint8_t *p, *data = NULL;
498
499 request_t *child;
500 fr_pair_t *vp;
501 SSL_SESSION *sess = tls_session->cache->store.sess;
503#if OPENSSL_VERSION_NUMBER >= 0x30400000L
504 fr_time_t expires = fr_time_from_sec((time_t)(SSL_SESSION_get_time_ex(sess) + SSL_get_timeout(sess)));
505#else
506 fr_time_t expires = fr_time_from_sec((time_t)(SSL_SESSION_get_time(sess) + SSL_get_timeout(sess)));
507#endif
508 fr_time_t now = fr_time();
509
510 fr_assert(tls_cache->store.sess);
511 fr_assert(tls_cache->store.state == FR_TLS_CACHE_STORE_REQUESTED);
512
513 if (fr_time_lteq(expires, now)) {
515 fr_tls_cache_id_to_box_shallow(&id, sess);
516
517 RWDEBUG("Session ID %pV - Session has already expired, not storing", &id);
519 }
520
521 /*
522 * Add the current session-state list
523 * contents to the ssl-data
524 */
525 if (tls_cache_app_data_set(request, sess, enum_tls_session_resumed_stateful->vb_uint32) < 0) return UNLANG_ACTION_FAIL;
526
527 MEM(child = unlang_subrequest_alloc(request, dict_tls));
528 request = child;
529
530 /*
531 * Setup the child request for storing
532 * session resumption data.
533 */
535 vp->vp_uint32 = enum_tls_packet_type_store_session->vb_uint32;
536
537 /*
538 * Add the session identifier we're trying
539 * to store.
540 */
542 fr_pair_value_memdup_buffer_shallow(vp, fr_tls_cache_id(vp, sess), true);
543
544 /*
545 * How long the session has to live
546 */
548 vp->vp_time_delta = fr_time_sub(expires, now);
549
550 /*
551 * Serialize the session
552 */
553 len = i2d_SSL_SESSION(sess, NULL); /* find out what length data we need */
554 if (len < 1) {
556 fr_tls_cache_id_to_box_shallow(&id, sess);
557
558 /* something went wrong */
559 fr_tls_strerror_printf(NULL); /* Drain the OpenSSL error stack */
560 RPWDEBUG("Session ID %pV - Serialisation failed, couldn't determine "
561 "required buffer length", &id);
562 error:
563 tls_cache_store_state_reset(request, tls_cache);
564 talloc_free(child);
565 return UNLANG_ACTION_FAIL;
566 }
567
569 MEM(data = talloc_array(vp, uint8_t, len));
570
571 /* openssl mutates &p */
572 p = data;
573 ret = i2d_SSL_SESSION(sess, &p); /* Serialize as ASN.1 */
574 if (ret != len) {
576 fr_tls_cache_id_to_box_shallow(&id, sess);
577
578 fr_tls_strerror_printf(NULL); /* Drain the OpenSSL error stack */
579 RPWDEBUG("Session ID %pV - Serialisation failed", &id);
581 goto error;
582 }
584
585 /*
586 * Allocate a child, and set it up to call
587 * the TLS virtual server.
588 */
589 ua = fr_tls_call_push(child, tls_cache_store_result, conf, tls_session);
590 if (ua < 0) goto error;
591
592 return ua;
593}
594
595/** Process the result of `clear session { ... }`
596 */
597static unlang_action_t tls_cache_clear_result(UNUSED rlm_rcode_t *p_result, UNUSED int *priority,
598 request_t *request, void *uctx)
599{
600 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
601 fr_tls_cache_t *tls_cache = tls_session->cache;
602 fr_pair_t *vp;
603
604 tls_cache_clear_state_reset(request, tls_cache);
605
606 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_packet_type);
607 if (vp &&
608 ((vp->vp_uint32 == enum_tls_packet_type_success->vb_uint32) ||
609 (vp->vp_uint32 == enum_tls_packet_type_notfound->vb_uint32))) {
611 }
612
613 RWDEBUG("Failed deleting session data - security may be compromised");
615}
616
617/** Push a `clear session { ... }` call into the current request, using a subrequest
618 *
619 * @param[in] request The current request.
620 * @param[in] conf TLS configuration.
621 * @param[in] tls_session The current TLS session.
622 * @return
623 * - UNLANG_ACTION_CALCULATE_RESULT on noop.
624 * - UNLANG_ACTION_PUSHED_CHILD on success.
625 * - UNLANG_ACTION_FAIL on failure.
626 */
627static inline CC_HINT(always_inline)
628unlang_action_t tls_cache_clear_push(request_t *request, fr_tls_conf_t *conf, fr_tls_session_t *tls_session)
629{
630 request_t *child;
631 fr_pair_t *vp;
632 fr_tls_cache_t *tls_cache = tls_session->cache;
634
635 fr_assert(tls_cache->clear.state == FR_TLS_CACHE_CLEAR_REQUESTED);
636 fr_assert(tls_cache->clear.id);
637
638 MEM(child = unlang_subrequest_alloc(request, dict_tls));
639 request = child;
640
641 /*
642 * Setup the child request for loading
643 * session resumption data.
644 */
646 vp->vp_uint32 = enum_tls_packet_type_clear_session->vb_uint32;
647
648 /*
649 * Add the session identifier we're
650 * trying to load.
651 */
652 tls_cache_session_id_to_vp(child, tls_cache->clear.id);
653
654 /*
655 * Allocate a child, and set it up to call
656 * the TLS virtual server.
657 */
658 ua = fr_tls_call_push(child, tls_cache_clear_result, conf, tls_session);
659 if (ua < 0) {
660 talloc_free(child);
661 tls_cache_clear_state_reset(request, tls_cache);
662 return UNLANG_ACTION_FAIL;
663 }
664
665 return ua;
666}
667
668/** Push a `store session { ... }` or `clear session { ... }` or `load session { ... }` depending on what operations are pending
669 *
670 * @param[in] request The current request.
671 * @param[in] tls_session The current TLS session.
672 * @return
673 * - UNLANG_ACTION_CALCULATE_RESULT - No pending actions
674 * - UNLANG_ACTION_PUSHED_CHILD - Pending operations to evaluate.
675 */
676unlang_action_t fr_tls_cache_pending_push(request_t *request, fr_tls_session_t *tls_session)
677{
678 fr_tls_cache_t *tls_cache = tls_session->cache;
679 fr_tls_conf_t *conf = fr_tls_session_conf(tls_session->ssl);
680
681 if (!tls_cache) return UNLANG_ACTION_CALCULATE_RESULT; /* No caching allowed */
682
683 /*
684 * Load stateful session data
685 */
686 if (tls_cache->load.state == FR_TLS_CACHE_LOAD_REQUESTED) {
687 return tls_cache_load_push(request, tls_session);
688 }
689
690 /*
691 * We only support a single session
692 * ticket currently...
693 */
694 if (tls_cache->clear.state == FR_TLS_CACHE_CLEAR_REQUESTED) {
695 /*
696 * Abort any pending store operations
697 * if they were for the same ID as
698 * we're now trying to clear.
699 */
700 if (tls_cache->store.state == FR_TLS_CACHE_STORE_REQUESTED) {
701 unsigned int len;
702 uint8_t const *id;
703
704 id = SSL_SESSION_get_id(tls_cache->store.sess, &len);
705 if ((len == talloc_array_length(tls_cache->clear.id)) &&
706 (memcmp(tls_cache->clear.id, id, len) == 0)) {
707 tls_cache_store_state_reset(request, tls_cache);
708 }
709 }
710
711 return tls_cache_clear_push(request, conf, tls_session);
712 }
713
714 if (tls_cache->store.state == FR_TLS_CACHE_STORE_REQUESTED) {
715 return tls_cache_store_push(request, conf, tls_session);
716 }
717
719}
720
721/** Write a newly created session data to the tls_session->cache structure
722 *
723 * @note If you hit an assert in this function, it was likely called twice, which shouldn't happen
724 * so blame OpenSSL.
725 *
726 * @param[in] ssl session state.
727 * @param[in] sess to serialise and write to the cache.
728 * @return
729 * - 1. What we return is not used by OpenSSL to indicate success
730 * or failure, but to indicate whether it should free its copy of
731 * the session data.
732 * In this case we tell it not to free the session data, as we
733 */
734static int tls_cache_store_cb(SSL *ssl, SSL_SESSION *sess)
735{
736 request_t *request;
737 fr_tls_session_t *tls_session;
738 fr_tls_cache_t *tls_cache;
739 unsigned int id_len;
740 uint8_t const *id;
741
742 /*
743 * This functions should only be called once during the lifetime
744 * of the tls_session, as the fields aren't re-populated on
745 * resumption.
746 */
747 tls_session = fr_tls_session(ssl);
748 request = fr_tls_session_request(tls_session->ssl);
749 tls_cache = tls_session->cache;
750
751 /*
752 * Request was cancelled, just get OpenSSL to
753 * free the session data, and don't do any work.
754 */
755 if (unlang_request_is_cancelled(request)) return 0;
756
757 id = SSL_SESSION_get_id(sess, &id_len);
758 RDEBUG3("Session ID %pV - Requested store", fr_box_octets(id, id_len));
759 /*
760 * Store the session blob and session id for writing
761 * later, once all the authentication phases have completed.
762 */
763 tls_cache->store.sess = sess;
764 tls_cache->store.state = FR_TLS_CACHE_STORE_REQUESTED;
765
766 return 1;
767}
768
769/** Read session data from the cache
770 *
771 * @param[in] ssl session state.
772 * @param[in] key to retrieve session data for.
773 * @param[in] key_len The length of the key.
774 * @param[out] copy Indicates whether OpenSSL should increment the reference
775 * count on SSL_SESSION to prevent it being automatically freed. We always
776 * set this to 0.
777 * @return
778 * - Deserialised session data on success.
779 * - NULL on error.
780 */
781static SSL_SESSION *tls_cache_load_cb(SSL *ssl,
782 unsigned char const *key,
783 int key_len, int *copy)
784{
785 fr_tls_session_t *tls_session;
786 fr_tls_cache_t *tls_cache;
787 request_t *request;
788
789 tls_session = fr_tls_session(ssl);
790 request = fr_tls_session_request(tls_session->ssl);
791 tls_cache = tls_session->cache;
792
793 /*
794 * Request was cancelled, don't return any session and hopefully
795 * OpenSSL will return back to SSL_read() soon.
796 */
797 if (unlang_request_is_cancelled(request)) return NULL;
798
799 /*
800 * Ensure if session resumption is disallowed this callback
801 * will never return session data.
802 */
803 if (!tls_cache || !tls_session->allow_session_resumption) return NULL;
804
805 /*
806 * 1. On the first call we return SSL_magic_pending_session_ptr.
807 * This causes the current SSL_read() call to error out and
808 * for SSL_get_error() to return SSL_ERROR_PENDING_SESSION.
809 * 2. On receiving SSL_ERROR_PENDING_SESSION we asynchronously
810 * load session information from a datastore and associated
811 * it with the SSL session.
812 * 3. We asynchronously validate the certificate information
813 * retrieved during the session session load.
814 * 3. We call SSL_read() again, which in turn calls this callback
815 * again.
816 */
817again:
818 switch (tls_cache->load.state) {
819 case FR_TLS_CACHE_LOAD_INIT:
820 fr_assert(!tls_cache->load.id);
821
822 tls_cache->load.state = FR_TLS_CACHE_LOAD_REQUESTED;
823 MEM(tls_cache->load.id = talloc_typed_memdup(tls_cache, (uint8_t const *)key, key_len));
824
825 RDEBUG3("Requested session load - ID %pV", fr_box_octets_buffer(tls_cache->load.id));
826
827 /*
828 * Cache functions are only allowed during the handshake
829 * FIXME: With TLS 1.3 session tickets can be sent
830 * later... Technically every point where we call
831 * SSL_read() may need to be a yield point.
832 */
833 if (unlikely(!tls_session->can_pause)) {
834 cant_pause:
835 fr_assert_msg("Unexpected call to %s. "
836 "tls_session_async_handshake_cont must be in call stack", __FUNCTION__);
837 return NULL;
838 }
839 /*
840 * Jumps back to SSL_read() in session.c
841 *
842 * Be aware that if the request is cancelled
843 * whatever was meant to be done during the
844 * time we yielded may not have been completed.
845 */
846 ASYNC_pause_job();
847
848 /*
849 * load cache { ... } returned, but the parent
850 * request was cancelled, try and get everything
851 * back into a consistent state and tell OpenSSL
852 * we failed to load the session.
853 */
854 if (unlang_request_is_cancelled(request)) {
855 tls_cache_load_state_reset(request, tls_cache); /* Clears any loaded session data */
856 return NULL;
857
858 }
859 goto again;
860
861 case FR_TLS_CACHE_LOAD_REQUESTED:
862 fr_assert(0); /* Called twice without attempting the load?! */
863 tls_cache->load.state = FR_TLS_CACHE_LOAD_FAILED;
864 break;
865
866 case FR_TLS_CACHE_LOAD_RETRIEVED:
867 {
868 SSL_SESSION *sess;
869
870 TALLOC_FREE(tls_cache->load.id);
871
872 RDEBUG3("Setting session data");
873
874 /*
875 * This restores the contents of &session-state[*]
876 * which hopefully still contains all the certificate
877 * pairs.
878 *
879 * Although the SSL_SESSION does contain a copy of
880 * the peer's certificate, it does not contain the
881 * peer's certificate chain, and so isn't reliable
882 * for performing re-validation.
883 */
884 if (tls_cache_app_data_get(request, tls_cache->load.sess) < 0) {
885 REDEBUG("Denying session resumption via session-id");
886 verify_error:
887 /*
888 * Request the session be deleted the next
889 * time something calls cache action pending.
890 */
891 tls_cache_delete_request(tls_cache->load.sess);
892 tls_cache_load_state_reset(request, tls_session->cache); /* Free the session */
893 return NULL;
894 }
895
896 /*
897 * This sets the validation state of the tls_session
898 * so that when we call ASYNC_pause_job(), and execution
899 * jumps back to tls_session_async_handshake_cont
900 * (just under SSL_read())
901 * the code there knows what job it needs to push onto
902 * the unlang stack.
903 */
904 fr_tls_verify_cert_request(tls_session, true);
905
906 if (unlikely(!tls_session->can_pause)) goto cant_pause;
907 /*
908 * Jumps back to SSL_read() in session.c
909 *
910 * Be aware that if the request is cancelled
911 * whatever was meant to be done during the
912 * time we yielded may not have been completed.
913 */
914 ASYNC_pause_job();
915
916 /*
917 * Certificate validation returned but the request
918 * was cancelled. Free any data we have so far
919 * and reset the states, then let OpenSSL know
920 * we failed to load the session.
921 */
922 if (unlang_request_is_cancelled(request)) {
923 tls_cache_load_state_reset(request, tls_cache); /* Clears any loaded session data */
924 fr_tls_verify_cert_reset(tls_session);
925 return NULL;
926
927 }
928
929 /*
930 * If we couldn't validate the client certificate
931 * then validation overall fails.
932 */
933 if (!fr_tls_verify_cert_result(tls_session)) {
934 RDEBUG2("Certificate re-validation failed, denying session resumption via session-id");
935 goto verify_error;
936 }
937 sess = tls_cache->load.sess;
938
939 /*
940 * After we return it's OpenSSL's responsibility
941 * to free the session data, so set our copy of
942 * the pointer to NULL, to prevent a double free
943 * on cleanup.
944 */
945 {
946 SESSION_ID(sess_id, tls_cache->load.sess);
947
948 RDEBUG3("Session ID %pV - Session ownership transferred to libssl", &sess_id);
949 *copy = 0;
950 tls_cache->load.sess = NULL;
951 }
952 return sess;
953 }
954
955
956 case FR_TLS_CACHE_LOAD_FAILED:
957 RDEBUG3("Session data load failed");
958 break;
959 }
960
961 TALLOC_FREE(tls_cache->load.id);
962 fr_assert(!tls_cache->load.sess);
963
964 return NULL;
965}
966
967/** Delete session data from the cache
968 *
969 * @param[in] ctx Current ssl context.
970 * @param[in] sess to be deleted.
971 */
972static void tls_cache_delete_cb(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
973{
974 /*
975 * Not sure why this happens, but sometimes SSL_SESSION *s
976 * make it here without the correct ex data.
977 *
978 * Maybe it's one OpenSSL created internally?
979 */
980 if (!SSL_SESSION_get_ex_data(sess, FR_TLS_EX_INDEX_TLS_SESSION)) return;
981 tls_cache_delete_request(sess);
982}
983
984/** Prevent a TLS session from being resumed in future
985 *
986 * @note In OpenSSL > 1.1.0 this should not be called directly, but passed as a callback to
987 * SSL_CTX_set_not_resumable_session_callback.
988 *
989 * @param ssl The current OpenSSL session.
990 * @param is_forward_secure Whether the cipher is forward secure, pass -1 if unknown.
991 * @return
992 * - 0 if session-resumption is allowed.
993 * - 1 if enabling session-resumption was disabled for this session.
994 */
995int fr_tls_cache_disable_cb(SSL *ssl, int is_forward_secure)
996{
997 request_t *request;
998
999 fr_tls_session_t *tls_session;
1000 fr_pair_t *vp;
1001
1002 tls_session = fr_tls_session(ssl);
1003 request = fr_tls_session_request(tls_session->ssl);
1004
1005 /*
1006 * Request was cancelled, try and get OpenSSL to
1007 * do as little work as possible.
1008 */
1009 if (unlang_request_is_cancelled(request)) return 1;
1010
1011 {
1012 fr_tls_conf_t *conf;
1013
1014 conf = talloc_get_type_abort(SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF), fr_tls_conf_t);
1015 if (conf->cache.require_extms && (SSL_get_extms_support(tls_session->ssl) == 0)) {
1016 RDEBUG2("Client does not support the Extended Master Secret extension, "
1017 "denying session resumption");
1018 goto disable;
1019 }
1020
1021 if (conf->cache.require_pfs && !is_forward_secure) {
1022 RDEBUG2("Cipher suite is not forward secure, denying session resumption");
1023 goto disable;
1024 }
1025 }
1026
1027 /*
1028 * If there's no session resumption, delete the entry
1029 * from the cache. This means either it's disabled
1030 * globally for this SSL context, OR we were told to
1031 * disable it for this user.
1032 *
1033 * This also means you can't turn it on just for one
1034 * user.
1035 */
1036 if (!tls_session->allow_session_resumption) {
1037 RDEBUG2("Session resumption not enabled for this TLS session, denying session resumption");
1038 goto disable;
1039 }
1040
1041 vp = fr_pair_find_by_da(&request->control_pairs, NULL, attr_allow_session_resumption);
1042 if (vp && (vp->vp_uint32 == 0)) {
1043 RDEBUG2("control.Allow-Session-Resumption == no, denying session resumption");
1044 disable:
1045 SSL_CTX_remove_session(tls_session->ctx, tls_session->session);
1046 tls_session->allow_session_resumption = false;
1047 return 1;
1048 }
1049
1050 RDEBUG2("Allowing future session-resumption");
1051
1052 return 0;
1053}
1054
1055/** Prevent a pending TLS session being persisted, and clear any resumed sessions
1056 *
1057 * Usually called if authentication has failed for some reason.
1058 *
1059 * Will clear any serialized data out of the tls_session structure
1060 * and should result in tls_cache_delete_cb being called.
1061 *
1062 * @note Calling this function will immediately free the memory used
1063 * by the session, but not the external persisted copy of the
1064 * session. To clear the persisted copy #fr_tls_cache_pending_push
1065 * must be called in a place where the caller is prepared to yield.
1066 * In most cases this means whether the handshake is a success or
1067 * failure, the last thing the caller of the TLS code should do
1068 * is set the result, and call #fr_tls_cache_pending_push.
1069 *
1070 * @param[in] request to use for running any async cache actions.
1071 * @param[in] tls_session on which to prevent resumption.
1072 */
1073void fr_tls_cache_deny(request_t *request, fr_tls_session_t *tls_session)
1074{
1075 fr_tls_cache_t *tls_cache = tls_session->cache;
1076 bool tmp_bind = !fr_tls_session_request_bound(tls_session->ssl);
1077
1078 /*
1079 * This is necessary to allow this function to
1080 * be called inside and outside of OpenSSL handshake
1081 * code.
1082 */
1083 if (tmp_bind) {
1084 fr_tls_session_request_bind(tls_session->ssl, request);
1085 /*
1086 * If there's already a request bound, it better be
1087 * the one passed to this function.
1088 */
1089 } else {
1090 fr_assert(fr_tls_session_request(tls_session->ssl) == request);
1091 }
1092
1093 /*
1094 * SSL_CTX_remove_session frees the previously loaded
1095 * session in tls_session. If the reference count reaches zero
1096 * the SSL_CTX_sess_remove_cb is called, which in our code is
1097 * tls_cache_delete_cb.
1098 *
1099 * tls_cache_delete_cb calls tls_cache_delete_request
1100 * to record the ID of tls_session->session
1101 * in our pending cache state structure.
1102 *
1103 * tls_cache_delete_request does NOT immediately call the
1104 * `cache clear {}` section as that must be done in a code area
1105 * which is prepared to yield.
1106 *
1107 * #fr_tls_cache_pending_push MUST be called to actually
1108 * clear external data.
1109 */
1110 if (tls_session->session) SSL_CTX_remove_session(tls_session->ctx, tls_session->session);
1111 tls_session->allow_session_resumption = false;
1112
1113 /*
1114 * Clear any pending store requests.
1115 */
1116 tls_cache_store_state_reset(fr_tls_session_request(tls_session->ssl), tls_cache);
1117
1118 /*
1119 * Unbind the request last...
1120 */
1121 if (tmp_bind) fr_tls_session_request_unbind(tls_session->ssl);
1122}
1123
1124/** Cleanup any memory allocated by OpenSSL
1125 */
1126static int _tls_cache_free(fr_tls_cache_t *tls_cache)
1127{
1128 tls_cache_load_state_reset(NULL, tls_cache);
1129 tls_cache_store_state_reset(NULL, tls_cache);
1130
1131 return 0;
1132}
1133
1134/** Allocate a session cache state structure, and assign it to a tls_session
1135 *
1136 * @note This must be called if session caching is enabled for a tls session.
1137 *
1138 * @param[in] tls_session to assign cache structure to.
1139 */
1140void fr_tls_cache_session_alloc(fr_tls_session_t *tls_session)
1141{
1142 fr_assert(!tls_session->cache);
1143
1144 MEM(tls_session->cache = talloc_zero(tls_session, fr_tls_cache_t));
1145 talloc_set_destructor(tls_session->cache, _tls_cache_free);
1146}
1147
1148/** Disable stateless session tickets for a given TLS ctx
1149 *
1150 * @param[in] ctx to disable session tickets for.
1151 */
1152static inline CC_HINT(always_inline)
1153void tls_cache_disable_stateless_resumption(SSL_CTX *ctx)
1154{
1155 long ctx_options = SSL_CTX_get_options(ctx);
1156
1157 /*
1158 * Disable session tickets for older TLS versions
1159 */
1160 ctx_options |= SSL_OP_NO_TICKET;
1161 SSL_CTX_set_options(ctx, ctx_options);
1162
1163 /*
1164 * This controls the number of stateful or stateless
1165 * tickets generated with TLS 1.3. In OpenSSL 1.1.0
1166 * it's also required to disable sending session tickets,
1167 * SSL_SESS_CACHE_OFF is not good enough.
1168 */
1169 SSL_CTX_set_num_tickets(ctx, 0);
1170}
1171
1172/** Disable stateful session resumption for a given TLS ctx
1173 *
1174 * @param[in] ctx to disable stateful session resumption for.
1175 */
1176static inline CC_HINT(always_inline)
1177void tls_cache_disable_statefull_resumption(SSL_CTX *ctx)
1178{
1179 /*
1180 * Only disables stateful session-resumption.
1181 *
1182 * As per Matt Caswell:
1183 *
1184 * SSL_SESS_CACHE_OFF, when called on the server,
1185 * disables caching of server side sessions.
1186 * It does not switch off resumption. Resumption can
1187 * still occur if a stateless session ticket is used
1188 * (even in TLSv1.2).
1189 */
1190 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1191}
1192
1193/** Called when new tickets are being generated
1194 *
1195 * This adds additional application data to the session ticket to
1196 * allow us to perform validation checks when the session is
1197 * resumed.
1198 */
1199static int tls_cache_session_ticket_app_data_set(SSL *ssl, void *arg)
1200{
1201 fr_tls_session_t *tls_session = fr_tls_session(ssl);
1202 fr_tls_cache_conf_t *tls_cache_conf = arg; /* Not talloced */
1203 SSL_SESSION *sess;
1204 request_t *request;
1205
1206 /*
1207 * Check to see if we have a request bound
1208 * to the session. If we don't have a
1209 * request there's no application data to
1210 * add.
1211 */
1212 if (!fr_tls_session_request_bound(ssl)) return 1;
1213
1214 /*
1215 * Encode the complete session state list
1216 * as app data. Then, when the session is
1217 * resumed, the session-state list is
1218 * repopulated.
1219 */
1220 request = fr_tls_session_request(ssl);
1221
1222 /*
1223 * Request was cancelled, don't do anything.
1224 */
1225 if (unlang_request_is_cancelled(request)) return 0;
1226
1227 /*
1228 * Fatal error - We definitely should be
1229 * attempting to generate session tickets
1230 * if it's not permitted.
1231 */
1232 if (!tls_session->allow_session_resumption ||
1233 (!(tls_cache_conf->mode & FR_TLS_CACHE_STATELESS))) {
1234 REDEBUG("Generating session-tickets is not allowed");
1235 return 0;
1236 }
1237
1238 sess = SSL_get_session(ssl);
1239 if (!sess) {
1240 REDEBUG("Failed retrieving session in session generation callback");
1241 return 0;
1242 }
1243
1244 if (tls_cache_app_data_set(request, sess, enum_tls_session_resumed_stateless->vb_uint32) < 0) return 0;
1245
1246 return 1;
1247}
1248
1249/** Called when new tickets are being decoded
1250 *
1251 * This adds the session-state attributes back to the current request.
1252 */
1253static SSL_TICKET_RETURN tls_cache_session_ticket_app_data_get(SSL *ssl, SSL_SESSION *sess,
1254 UNUSED unsigned char const *keyname,
1255 UNUSED size_t keyname_len,
1256 SSL_TICKET_STATUS status,
1257 void *arg)
1258{
1259 fr_tls_session_t *tls_session = fr_tls_session(ssl);
1260 fr_tls_conf_t *conf = fr_tls_session_conf(tls_session->ssl);
1261 fr_tls_cache_conf_t *tls_cache_conf = arg; /* Not talloced */
1262 request_t *request = NULL;
1263
1264 if (fr_tls_session_request_bound(ssl)) {
1265 request = fr_tls_session_request(ssl);
1266 if (unlang_request_is_cancelled(request)) return SSL_TICKET_RETURN_ABORT;
1267 }
1268
1269 if (!tls_session->allow_session_resumption ||
1270 (!(tls_cache_conf->mode & FR_TLS_CACHE_STATELESS))) {
1271 ROPTIONAL(RDEBUG2, DEBUG2, "Session resumption not enabled for this TLS session, "
1272 "denying session resumption via session-ticket");
1273 return SSL_TICKET_RETURN_IGNORE;
1274 }
1275
1276 switch (status) {
1277 case SSL_TICKET_EMPTY:
1278 case SSL_TICKET_NO_DECRYPT:
1279 case SSL_TICKET_FATAL_ERR_MALLOC:
1280 case SSL_TICKET_FATAL_ERR_OTHER:
1281 case SSL_TICKET_NONE:
1282#ifdef STATIC_ANALYZER
1283 default:
1284#endif
1285 return SSL_TICKET_RETURN_IGNORE_RENEW; /* Send a new ticket */
1286
1287 case SSL_TICKET_SUCCESS:
1288 if (!request) return SSL_TICKET_RETURN_USE;
1289 break;
1290
1291 case SSL_TICKET_SUCCESS_RENEW:
1292 if (!request) return SSL_TICKET_RETURN_USE_RENEW;
1293 break;
1294 }
1295
1296 /*
1297 * This restores the contents of &session-state[*]
1298 * which hopefully still contains all the certificate
1299 * pairs.
1300 *
1301 * Although the SSL_SESSION does contain a copy of
1302 * the peer's certificate, it does not contain the
1303 * peer's certificate chain, and so isn't reliable
1304 * for performing re-validation.
1305 */
1306 if (tls_cache_app_data_get(request, sess) < 0) {
1307 REDEBUG("Denying session resumption via session-ticket");
1308 return SSL_TICKET_RETURN_IGNORE_RENEW;
1309 }
1310
1311 if (conf->virtual_server && tls_session->verify_client_cert) {
1312 RDEBUG2("Requesting certificate re-validation for session-ticket");
1313 /*
1314 * This sets the validation state of the tls_session
1315 * so that when we call ASYNC_pause_job(), and execution
1316 * jumps back to tls_session_async_handshake_cont
1317 * (just under SSL_read())
1318 * the code there knows what job it needs to push onto
1319 * the unlang stack.
1320 */
1321 fr_tls_verify_cert_request(tls_session, true);
1322
1323 /*
1324 * Cache functions are only allowed during the handshake
1325 * FIXME: With TLS 1.3 session tickets can be sent
1326 * later... Technically every point where we call
1327 * SSL_read() may need to be a yield point.
1328 */
1329 if (unlikely(!tls_session->can_pause)) {
1330 fr_assert_msg("Unexpected call to %s. "
1331 "tls_session_async_handshake_cont must be in call stack", __FUNCTION__);
1332 return SSL_TICKET_RETURN_IGNORE_RENEW;
1333 }
1334
1335 /*
1336 * Jumps back to SSL_read() in session.c
1337 *
1338 * Be aware that if the request is cancelled
1339 * whatever was meant to be done during the
1340 * time we yielded may not have been completed.
1341 */
1342 ASYNC_pause_job();
1343
1344 /*
1345 * If the request was cancelled get everything back into
1346 * a known state.
1347 */
1348 if (unlang_request_is_cancelled(request)) {
1349 fr_tls_verify_cert_reset(tls_session);
1350 return SSL_TICKET_RETURN_ABORT;
1351 }
1352
1353 /*
1354 * If we couldn't validate the client certificate
1355 * give the client the opportunity to send a new
1356 * one, but _don't_ allow session resumption.
1357 */
1358 if (!fr_tls_verify_cert_result(tls_session)) {
1359 RDEBUG2("Certificate re-validation failed, denying session resumption via session-ticket");
1360 return SSL_TICKET_RETURN_IGNORE_RENEW;
1361 }
1362 }
1363
1364 return (status == SSL_TICKET_SUCCESS_RENEW) ? SSL_TICKET_RETURN_USE_RENEW : SSL_TICKET_RETURN_USE;
1365}
1366
1367/** Sets callbacks and flags on a SSL_CTX to enable/disable session resumption
1368 *
1369 * @param[in] ctx to modify.
1370 * @param[in] cache_conf Session caching configuration.
1371 * @return
1372 * - 0 on success.
1373 * - -1 on failure.
1374 */
1375int fr_tls_cache_ctx_init(SSL_CTX *ctx, fr_tls_cache_conf_t const *cache_conf)
1376{
1377 switch (cache_conf->mode) {
1378 case FR_TLS_CACHE_DISABLED:
1379 tls_cache_disable_stateless_resumption(ctx);
1380 tls_cache_disable_statefull_resumption(ctx);
1381 return 0;
1382
1383 case FR_TLS_CACHE_AUTO:
1384 case FR_TLS_CACHE_STATEFUL:
1385 /*
1386 * Setup the callbacks for stateful session-resumption
1387 * i.e. where the server stores session information.
1388 */
1389 SSL_CTX_sess_set_new_cb(ctx, tls_cache_store_cb);
1390 SSL_CTX_sess_set_get_cb(ctx, tls_cache_load_cb);
1391 SSL_CTX_sess_set_remove_cb(ctx, tls_cache_delete_cb);
1392
1393 /*
1394 * Controls the stateful cache mode
1395 *
1396 * Here we disable internal lookups, and rely on the
1397 * callbacks above.
1398 */
1399 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_INTERNAL);
1400
1401 /*
1402 * Controls the validity period of the stateful cache.
1403 */
1404 SSL_CTX_set_timeout(ctx, fr_time_delta_to_sec(cache_conf->lifetime));
1405
1406 /*
1407 * Disables stateless session tickets for TLS 1.3.
1408 */
1409 if (!(cache_conf->mode & FR_TLS_CACHE_STATELESS)) {
1410 tls_cache_disable_stateless_resumption(ctx);
1411 break;
1412 }
1414
1415 case FR_TLS_CACHE_STATELESS:
1416 {
1417 size_t key_len;
1418 uint8_t *key_buff;
1419 EVP_PKEY_CTX *pkey_ctx = NULL;
1420
1421 if (!(cache_conf->mode & FR_TLS_CACHE_STATEFUL)) tls_cache_disable_statefull_resumption(ctx);
1422
1423 /*
1424 * If keys is NULL, then OpenSSL returns the expected
1425 * key length, which may be different across different
1426 * flavours/versions of OpenSSL.
1427 *
1428 * We could calculate this in conf.c, but, if in future
1429 * OpenSSL decides to use different key lengths based
1430 * on other parameters in the ctx, that'd break.
1431 */
1432 key_len = SSL_CTX_set_tlsext_ticket_keys(ctx, NULL, 0);
1433
1434 if (unlikely((pkey_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL)) == NULL)) {
1435 fr_tls_strerror_printf(NULL);
1436 PERROR("Failed initialising KDF");
1437 kdf_error:
1438 if (pkey_ctx) EVP_PKEY_CTX_free(pkey_ctx);
1439 return -1;
1440 }
1441 if (unlikely(EVP_PKEY_derive_init(pkey_ctx) != 1)) {
1442 fr_tls_strerror_printf(NULL);
1443 PERROR("Failed initialising KDF derivation ctx");
1444 goto kdf_error;
1445 }
1446 if (unlikely(EVP_PKEY_CTX_set_hkdf_md(pkey_ctx, UNCONST(struct evp_md_st *, EVP_sha256())) != 1)) {
1447 fr_tls_strerror_printf(NULL);
1448 PERROR("Failed setting KDF MD");
1449 goto kdf_error;
1450 }
1451 if (unlikely(EVP_PKEY_CTX_set1_hkdf_key(pkey_ctx,
1452 UNCONST(unsigned char *, cache_conf->session_ticket_key),
1453 talloc_array_length(cache_conf->session_ticket_key)) != 1)) {
1454 fr_tls_strerror_printf(NULL);
1455 PERROR("Failed setting KDF key");
1456 goto kdf_error;
1457 }
1458 if (unlikely(EVP_PKEY_CTX_add1_hkdf_info(pkey_ctx,
1459 UNCONST(unsigned char *, "freeradius-session-ticket"),
1460 sizeof("freeradius-session-ticket") - 1) != 1)) {
1461 fr_tls_strerror_printf(NULL);
1462 PERROR("Failed setting KDF label");
1463 goto kdf_error;
1464 }
1465
1466 /*
1467 * SSL_CTX_set_tlsext_ticket_keys memcpys its
1468 * inputs so this is just a temporary buffer.
1469 */
1470 MEM(key_buff = talloc_array(NULL, uint8_t, key_len));
1471 if (EVP_PKEY_derive(pkey_ctx, key_buff, &key_len) != 1) {
1472 fr_tls_strerror_printf(NULL);
1473 PERROR("Failed deriving session ticket key");
1474
1475 talloc_free(key_buff);
1476 goto kdf_error;
1477 }
1478 EVP_PKEY_CTX_free(pkey_ctx);
1479
1480 fr_assert(talloc_array_length(key_buff) == key_len);
1481 /*
1482 * Ensure the same keys are used across all threads
1483 */
1484 if (SSL_CTX_set_tlsext_ticket_keys(ctx,
1485 key_buff, key_len) != 1) {
1486 fr_tls_strerror_printf(NULL);
1487 PERROR("Failed setting session ticket keys");
1488 return -1;
1489 }
1490
1491 DEBUG3("Derived session-ticket-key:");
1492 HEXDUMP3(key_buff, key_len, NULL);
1493 talloc_free(key_buff);
1494
1495 /*
1496 * These callbacks embed and extract the
1497 * session-state list from the session-ticket.
1498 */
1499 if (unlikely(SSL_CTX_set_session_ticket_cb(ctx,
1500 tls_cache_session_ticket_app_data_set,
1501 tls_cache_session_ticket_app_data_get,
1502 UNCONST(fr_tls_cache_conf_t *, cache_conf)) != 1)) {
1503 fr_tls_strerror_printf(NULL);
1504 PERROR("Failed setting session ticket callbacks");
1505 return -1;
1506 }
1507
1508 /*
1509 * Stateless resumption is enabled by default when
1510 * the TLS ctx is created, but OpenSSL sends too
1511 * many session tickets by default (2), and we only
1512 * need one.
1513 */
1514 SSL_CTX_set_num_tickets(ctx, 1);
1515 }
1516 break;
1517 }
1518
1519 SSL_CTX_set_not_resumable_session_callback(ctx, fr_tls_cache_disable_cb);
1520 SSL_CTX_set_quiet_shutdown(ctx, 1);
1521
1522 return 0;
1523}
1524#endif /* WITH_TLS */
unlang_action_t
Returned by unlang_op_t calls, determine the next action of the interpreter.
Definition action.h:35
@ UNLANG_ACTION_FAIL
Encountered an unexpected error.
Definition action.h:36
@ UNLANG_ACTION_CALCULATE_RESULT
Calculate a new section rlm_rcode_t value.
Definition action.h:37
#define UNCONST(_type, _ptr)
Remove const qualification from a pointer.
Definition build.h:167
#define USES_APPLE_DEPRECATED_API
Definition build.h:470
#define RCSID(id)
Definition build.h:483
#define FALL_THROUGH
clang 10 doesn't recognised the FALL-THROUGH comment anymore
Definition build.h:322
#define unlikely(_x)
Definition build.h:381
#define UNUSED
Definition build.h:315
#define fr_dbuff_used(_dbuff_or_marker)
Return the number of bytes remaining between the start of the dbuff or marker and the current positio...
Definition dbuff.h:767
static void fr_dbuff_free_talloc(fr_dbuff_t *dbuff)
Free the talloc buffer associated with a dbuff.
Definition dbuff.h:453
#define fr_dbuff_len(_dbuff_or_marker)
The length of the underlying buffer.
Definition dbuff.h:776
#define fr_dbuff_init(_out, _start, _len_or_end)
Initialise an dbuff for encoding or decoding.
Definition dbuff.h:354
#define fr_dbuff_start(_dbuff_or_marker)
Return the 'start' position of a dbuff or marker.
Definition dbuff.h:898
#define fr_dbuff_remaining(_dbuff_or_marker)
Return the number of bytes remaining between the dbuff or marker and the end of the buffer.
Definition dbuff.h:743
static fr_dbuff_t * fr_dbuff_init_talloc(TALLOC_CTX *ctx, fr_dbuff_t *dbuff, fr_dbuff_uctx_talloc_t *tctx, size_t init, size_t max)
Initialise a special dbuff which automatically extends as additional data is written.
Definition dbuff.h:411
static void * fr_dcursor_current(fr_dcursor_t *cursor)
Return the item the cursor current points to.
Definition dcursor.h:337
#define fr_assert_msg(_x, _msg,...)
Calls panic_action ifndef NDEBUG, else logs error and causes the server to exit immediately with code...
Definition debug.h:210
#define MEM(x)
Definition debug.h:36
fr_dict_attr_t const * fr_dict_root(fr_dict_t const *dict)
Return the root attribute of a dictionary.
Definition dict_util.c:2404
bool unlang_request_is_cancelled(request_t const *request)
Return whether a request has been cancelled.
Definition interpret.c:1326
fr_dict_t const * dict_tls
Definition base.c:79
void log_request_pair_list(fr_log_lvl_t lvl, request_t *request, fr_pair_t const *parent, fr_pair_list_t const *vps, char const *prefix)
Print a fr_pair_list_t.
Definition log.c:830
#define PERROR(_fmt,...)
Definition log.h:228
#define REXDENT()
Exdent (unindent) R* messages by one level.
Definition log.h:443
#define DEBUG3(_fmt,...)
Definition log.h:266
#define ROPTIONAL(_l_request, _l_global, _fmt,...)
Use different logging functions depending on whether request is NULL or not.
Definition log.h:528
#define RWDEBUG(fmt,...)
Definition log.h:361
#define RDEBUG_ENABLED3
True if request debug level 1-3 messages are enabled.
Definition log.h:335
#define RDEBUG3(fmt,...)
Definition log.h:343
#define RHEXDUMP4(_data, _len, _fmt,...)
Definition log.h:706
#define ROPTIONAL_ENABLED(_e_request, _e_global)
Check if a debug level is set by the request (if !NULL) or by the global log.
Definition log.h:542
#define RPERROR(fmt,...)
Definition log.h:302
#define RPEDEBUG(fmt,...)
Definition log.h:376
#define HEXDUMP3(_data, _len, _fmt,...)
Definition log.h:723
#define RPWDEBUG(fmt,...)
Definition log.h:366
#define DEBUG_ENABLED3
True if global debug level 1-3 messages are enabled.
Definition log.h:259
#define RINDENT()
Indent R* messages by one level.
Definition log.h:430
fr_value_box_t const * enum_tls_packet_type_store_session
HIDDEN fr_dict_attr_t const * attr_tls_packet_type
fr_value_box_t const * enum_tls_packet_type_success
HIDDEN fr_dict_attr_t const * attr_tls_session_ttl
fr_value_box_t const * enum_tls_session_resumed_stateful
HIDDEN fr_dict_attr_t const * attr_tls_session_data
fr_value_box_t const * enum_tls_packet_type_load_session
HIDDEN fr_dict_attr_t const * attr_tls_session_id
fr_value_box_t const * enum_tls_packet_type_clear_session
fr_value_box_t const * enum_tls_session_resumed_stateless
fr_value_box_t const * enum_tls_packet_type_notfound
HIDDEN fr_dict_attr_t const * attr_tls_session_resume_type
HIDDEN fr_dict_attr_t const * attr_allow_session_resumption
talloc_free(reap)
@ L_DBG_LVL_3
3rd highest priority debug messages (-xxx | -Xx).
Definition log.h:72
@ L_DBG_LVL_2
2nd highest priority debug messages (-xx | -X).
Definition log.h:71
@ L_DBG
Only displayed when debugging is enabled.
Definition log.h:59
unsigned int uint32_t
long int ssize_t
unsigned char uint8_t
int fr_pair_value_memdup_buffer(fr_pair_t *vp, uint8_t const *src, bool tainted)
Copy data from a talloced buffer into an "octets" data type.
Definition pair.c:3011
fr_pair_t * fr_pair_find_by_da(fr_pair_list_t const *list, fr_pair_t const *prev, fr_dict_attr_t const *da)
Find the first pair with a matching da.
Definition pair.c:693
void fr_pair_list_init(fr_pair_list_t *list)
Initialise a pair list header.
Definition pair.c:46
int fr_pair_value_memdup_buffer_shallow(fr_pair_t *vp, uint8_t const *src, bool tainted)
Assign a talloced buffer to a "octets" type value pair.
Definition pair.c:3056
ssize_t fr_internal_decode_pair_dbuff(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent, fr_dbuff_t *dbuff, void *decode_ctx)
Definition decode.c:279
ssize_t fr_internal_encode_pair(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, void *encode_ctx)
Encode a data structure into an internal attribute.
Definition encode.c:281
#define fr_assert(_expr)
Definition rad_assert.h:38
#define pair_update_request(_attr, _da)
#define REDEBUG(fmt,...)
Definition radclient.h:52
#define RDEBUG_ENABLED2()
Definition radclient.h:50
#define RDEBUG2(fmt,...)
Definition radclient.h:54
#define DEBUG2(fmt,...)
Definition radclient.h:43
static rs_t * conf
Definition radsniff.c:53
rlm_rcode_t
Return codes indicating the result of the module call.
Definition rcode.h:40
#define pair_append_session_state(_attr, _da)
Allocate and append a fr_pair_t to session-state list.
Definition pair.h:67
#define pair_prepend_request(_attr, _da)
Allocate and prepend a fr_pair_t to the request list.
Definition pair.h:77
fr_pair_t * vp
#define fr_time()
Allow us to arbitrarily manipulate time.
Definition state_test.c:8
Stores an attribute, a value and various bits of other data.
Definition pair.h:68
request_t * unlang_subrequest_alloc(request_t *parent, fr_dict_t const *namespace)
Allocate a subrequest to run through a virtual server at some point in the future.
Definition subrequest.c:287
uint8_t * talloc_typed_memdup(TALLOC_CTX *ctx, uint8_t const *in, size_t inlen)
Call talloc_memdup, setting the type on the new chunk correctly.
Definition talloc.c:420
#define fr_time_lteq(_a, _b)
Definition time.h:240
static int64_t fr_time_delta_to_sec(fr_time_delta_t delta)
Definition time.h:647
static fr_time_t fr_time_from_sec(time_t when)
Convert a time_t (wallclock time) to a fr_time_t (internal time)
Definition time.h:858
#define fr_time_sub(_a, _b)
Subtract one time from another.
Definition time.h:229
"server local" time.
Definition time.h:69
fr_pair_t * fr_pair_remove(fr_pair_list_t *list, fr_pair_t *vp)
Remove fr_pair_t from a list without freeing.
Definition pair_inline.c:94
void fr_pair_list_free(fr_pair_list_t *list)
Free memory used by a valuepair list.
void fr_pair_list_append(fr_pair_list_t *dst, fr_pair_list_t *src)
Appends a list of fr_pair_t from a temporary list to a destination list.
#define fr_pair_dcursor_init(_cursor, _list)
Initialises a special dcursor with callbacks that will maintain the attr sublists correctly.
Definition pair.h:591
void fr_value_box_memdup_shallow(fr_value_box_t *dst, fr_dict_attr_t const *enumv, uint8_t const *src, size_t len, bool tainted)
Assign a buffer to a box, but don't copy it.
Definition value.c:4548
static fr_slen_t data
Definition value.h:1265
#define fr_box_octets_buffer(_val)
Definition value.h:290
int nonnull(2, 5))
static size_t char ** out
Definition value.h:997
#define fr_box_octets(_val, _len)
Definition value.h:288