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: bab31a58700123c927d79668e1af8b1bece995f9 $
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: bab31a58700123c927d79668e1af8b1bece995f9 $")
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->proto_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(request_t *request, void *uctx)
352{
353 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
354 fr_tls_cache_t *tls_cache = tls_session->cache;
355 fr_pair_t *vp;
356 uint8_t const *q, **p;
357 SSL_SESSION *sess;
358
359 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_packet_type);
360 if (!vp || (vp->vp_uint32 != enum_tls_packet_type_success->vb_uint32)) {
361 RWDEBUG("Failed acquiring session data");
362 error:
363 tls_cache->load.state = FR_TLS_CACHE_LOAD_FAILED;
365 }
366
367 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_session_data);
368 if (!vp) {
369 RWDEBUG("No cached session found");
370 goto error;
371 }
372
373 q = vp->vp_octets; /* openssl will mutate q, so we can't use vp_octets directly */
374 p = (unsigned char const **)&q;
375
376 sess = d2i_SSL_SESSION(NULL, p, vp->vp_length);
377 if (!sess) {
378 fr_tls_log(request, "Failed loading persisted session");
379 goto error;
380 }
381
382 if (RDEBUG_ENABLED3) {
383 SESSION_ID(sess_id, sess);
384
385 RDEBUG3("Session ID %pV - Read %zu bytes of data. "
386 "Session de-serialized successfully", &sess_id, vp->vp_length);
387 SSL_SESSION_print(fr_tls_request_log_bio(request, L_DBG, L_DBG_LVL_3), sess);
388 }
389
390 /*
391 * OpenSSL's API is very inconsistent.
392 *
393 * We need to set external data here, so it can be
394 * retrieved in fr_tls_cache_delete.
395 *
396 * ex_data is not serialised in i2d_SSL_SESSION
397 * so we don't have to bother unsetting it.
398 */
399 SSL_SESSION_set_ex_data(sess, FR_TLS_EX_INDEX_TLS_SESSION, fr_tls_session(tls_session->ssl));
400
401 tls_cache->load.state = FR_TLS_CACHE_LOAD_RETRIEVED;
402 tls_cache->load.sess = sess; /* This is consumed in tls_cache_load_cb */
403
405}
406
407/** Push a `load session { ... }` call into the current request, using a subrequest
408 *
409 * @param[in] request The current request.
410 * @param[in] tls_session The current TLS session.
411 * @return
412 * - UNLANG_ACTION_CALCULATE_RESULT on noop.
413 * - UNLANG_ACTION_PUSHED_CHILD on success.
414 * - UNLANG_ACTION_FAIL on failure.
415 */
416static unlang_action_t tls_cache_load_push(request_t *request, fr_tls_session_t *tls_session)
417{
418 fr_tls_cache_t *tls_cache = tls_session->cache;
419 fr_tls_conf_t *conf = fr_tls_session_conf(tls_session->ssl);
420 request_t *child;
421 fr_pair_t *vp;
423
424 if (tls_cache->load.state != FR_TLS_CACHE_LOAD_REQUESTED) return UNLANG_ACTION_CALCULATE_RESULT;
425
426 fr_assert(tls_cache->load.id);
427
428 MEM(child = unlang_subrequest_alloc(request, dict_tls));
429 request = child;
430
431 /*
432 * Setup the child request for loading
433 * session resumption data.
434 */
436 vp->vp_uint32 = enum_tls_packet_type_load_session->vb_uint32;
437
438 /*
439 * Add the session identifier we're
440 * trying to load.
441 */
442 tls_cache_session_id_to_vp(child, tls_cache->load.id);
443
444 /*
445 * Allocate a child, and set it up to call
446 * the TLS virtual server.
447 */
448 ua = fr_tls_call_push(child, tls_cache_load_result, conf, tls_session, true);
449 if (ua < 0) {
450 talloc_free(child);
451 tls_cache_load_state_reset(request, tls_cache);
452 return UNLANG_ACTION_FAIL;
453 }
454
455 return ua;
456}
457
458/** Process the result of `store session { ... }`
459 */
460static unlang_action_t tls_cache_store_result(request_t *request, void *uctx)
461{
462 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
463 fr_tls_cache_t *tls_cache = tls_session->cache;
464 fr_pair_t *vp;
465
466 tls_cache_store_state_reset(request, tls_cache);
467
468 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_packet_type);
469 if (vp && (vp->vp_uint32 == enum_tls_packet_type_success->vb_uint32)) {
470 tls_cache->store.state = FR_TLS_CACHE_STORE_PERSISTED; /* Avoid spurious clear calls */
471 } else {
472 RWDEBUG("Failed storing session data");
473 tls_cache->store.state = FR_TLS_CACHE_STORE_INIT;
474 }
475
477}
478
479/** Push a `store session { ... }` call into the current request, using a subrequest
480 *
481 * @param[in] request The current request.
482 * @param[in] conf TLS configuration.
483 * @param[in] tls_session The current TLS session.
484 * @return
485 * - UNLANG_ACTION_CALCULATE_RESULT on noop.
486 * - UNLANG_ACTION_PUSHED_CHILD on success.
487 * - UNLANG_ACTION_FAIL on failure.
488 */
489static inline CC_HINT(always_inline)
490unlang_action_t tls_cache_store_push(request_t *request, fr_tls_conf_t *conf, fr_tls_session_t *tls_session)
491{
492 fr_tls_cache_t *tls_cache = tls_session->cache;
493 size_t len, ret;
494
495 uint8_t *p, *data = NULL;
496
497 request_t *child;
498 fr_pair_t *vp;
499 SSL_SESSION *sess = tls_session->cache->store.sess;
501#if OPENSSL_VERSION_NUMBER >= 0x30400000L
502 fr_time_t expires = fr_time_from_sec((time_t)(SSL_SESSION_get_time_ex(sess) + SSL_get_timeout(sess)));
503#else
504 fr_time_t expires = fr_time_from_sec((time_t)(SSL_SESSION_get_time(sess) + SSL_get_timeout(sess)));
505#endif
506 fr_time_t now = fr_time();
507
508 fr_assert(tls_cache->store.sess);
509 fr_assert(tls_cache->store.state == FR_TLS_CACHE_STORE_REQUESTED);
510
511 if (fr_time_lteq(expires, now)) {
513 fr_tls_cache_id_to_box_shallow(&id, sess);
514
515 RWDEBUG("Session ID %pV - Session has already expired, not storing", &id);
517 }
518
519 /*
520 * Add the current session-state list
521 * contents to the ssl-data
522 */
523 if (tls_cache_app_data_set(request, sess, enum_tls_session_resumed_stateful->vb_uint32) < 0) return UNLANG_ACTION_FAIL;
524
525 MEM(child = unlang_subrequest_alloc(request, dict_tls));
526 request = child;
527
528 /*
529 * Setup the child request for storing
530 * session resumption data.
531 */
533 vp->vp_uint32 = enum_tls_packet_type_store_session->vb_uint32;
534
535 /*
536 * Add the session identifier we're trying
537 * to store.
538 */
540 fr_pair_value_memdup_buffer_shallow(vp, fr_tls_cache_id(vp, sess), true);
541
542 /*
543 * How long the session has to live
544 */
546 vp->vp_time_delta = fr_time_sub(expires, now);
547
548 /*
549 * Serialize the session
550 */
551 len = i2d_SSL_SESSION(sess, NULL); /* find out what length data we need */
552 if (len < 1) {
554 fr_tls_cache_id_to_box_shallow(&id, sess);
555
556 /* something went wrong */
557 fr_tls_strerror_printf(NULL); /* Drain the OpenSSL error stack */
558 RPWDEBUG("Session ID %pV - Serialisation failed, couldn't determine "
559 "required buffer length", &id);
560 error:
561 tls_cache_store_state_reset(request, tls_cache);
562 talloc_free(child);
563 return UNLANG_ACTION_FAIL;
564 }
565
567 MEM(data = talloc_array(vp, uint8_t, len));
568
569 /* openssl mutates &p */
570 p = data;
571 ret = i2d_SSL_SESSION(sess, &p); /* Serialize as ASN.1 */
572 if (ret != len) {
574 fr_tls_cache_id_to_box_shallow(&id, sess);
575
576 fr_tls_strerror_printf(NULL); /* Drain the OpenSSL error stack */
577 RPWDEBUG("Session ID %pV - Serialisation failed", &id);
579 goto error;
580 }
582
583 /*
584 * Allocate a child, and set it up to call
585 * the TLS virtual server.
586 */
587 ua = fr_tls_call_push(child, tls_cache_store_result, conf, tls_session, true);
588 if (ua < 0) goto error;
589
590 return ua;
591}
592
593/** Process the result of `clear session { ... }`
594 */
595static unlang_action_t tls_cache_clear_result(request_t *request, void *uctx)
596{
597 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
598 fr_tls_cache_t *tls_cache = tls_session->cache;
599 fr_pair_t *vp;
600
601 tls_cache_clear_state_reset(request, tls_cache);
602
603 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_packet_type);
604 if (vp &&
605 ((vp->vp_uint32 == enum_tls_packet_type_success->vb_uint32) ||
606 (vp->vp_uint32 == enum_tls_packet_type_notfound->vb_uint32))) {
608 }
609
610 RWDEBUG("Failed deleting session data - security may be compromised");
612}
613
614/** Push a `clear session { ... }` call into the current request, using a subrequest
615 *
616 * @param[in] request The current request.
617 * @param[in] conf TLS configuration.
618 * @param[in] tls_session The current TLS session.
619 * @return
620 * - UNLANG_ACTION_CALCULATE_RESULT on noop.
621 * - UNLANG_ACTION_PUSHED_CHILD on success.
622 * - UNLANG_ACTION_FAIL on failure.
623 */
624static inline CC_HINT(always_inline)
625unlang_action_t tls_cache_clear_push(request_t *request, fr_tls_conf_t *conf, fr_tls_session_t *tls_session)
626{
627 request_t *child;
628 fr_pair_t *vp;
629 fr_tls_cache_t *tls_cache = tls_session->cache;
631
632 fr_assert(tls_cache->clear.state == FR_TLS_CACHE_CLEAR_REQUESTED);
633 fr_assert(tls_cache->clear.id);
634
635 MEM(child = unlang_subrequest_alloc(request, dict_tls));
636 request = child;
637
638 /*
639 * Setup the child request for loading
640 * session resumption data.
641 */
643 vp->vp_uint32 = enum_tls_packet_type_clear_session->vb_uint32;
644
645 /*
646 * Add the session identifier we're
647 * trying to load.
648 */
649 tls_cache_session_id_to_vp(child, tls_cache->clear.id);
650
651 /*
652 * Allocate a child, and set it up to call
653 * the TLS virtual server.
654 */
655 ua = fr_tls_call_push(child, tls_cache_clear_result, conf, tls_session, true);
656 if (ua < 0) {
657 talloc_free(child);
658 tls_cache_clear_state_reset(request, tls_cache);
659 return UNLANG_ACTION_FAIL;
660 }
661
662 return ua;
663}
664
665/** Push a `store session { ... }` or `clear session { ... }` or `load session { ... }` depending on what operations are pending
666 *
667 * @param[in] request The current request.
668 * @param[in] tls_session The current TLS session.
669 * @return
670 * - UNLANG_ACTION_CALCULATE_RESULT - No pending actions
671 * - UNLANG_ACTION_PUSHED_CHILD - Pending operations to evaluate.
672 */
673unlang_action_t fr_tls_cache_pending_push(request_t *request, fr_tls_session_t *tls_session)
674{
675 fr_tls_cache_t *tls_cache = tls_session->cache;
676 fr_tls_conf_t *conf = fr_tls_session_conf(tls_session->ssl);
677
678 if (!tls_cache) return UNLANG_ACTION_CALCULATE_RESULT; /* No caching allowed */
679
680 /*
681 * Load stateful session data
682 */
683 if (tls_cache->load.state == FR_TLS_CACHE_LOAD_REQUESTED) {
684 return tls_cache_load_push(request, tls_session);
685 }
686
687 /*
688 * We only support a single session
689 * ticket currently...
690 */
691 if (tls_cache->clear.state == FR_TLS_CACHE_CLEAR_REQUESTED) {
692 /*
693 * Abort any pending store operations
694 * if they were for the same ID as
695 * we're now trying to clear.
696 */
697 if (tls_cache->store.state == FR_TLS_CACHE_STORE_REQUESTED) {
698 unsigned int len;
699 uint8_t const *id;
700
701 id = SSL_SESSION_get_id(tls_cache->store.sess, &len);
702 if ((len == talloc_array_length(tls_cache->clear.id)) &&
703 (memcmp(tls_cache->clear.id, id, len) == 0)) {
704 tls_cache_store_state_reset(request, tls_cache);
705 }
706 }
707
708 return tls_cache_clear_push(request, conf, tls_session);
709 }
710
711 if (tls_cache->store.state == FR_TLS_CACHE_STORE_REQUESTED) {
712 return tls_cache_store_push(request, conf, tls_session);
713 }
714
716}
717
718/** Write a newly created session data to the tls_session->cache structure
719 *
720 * @note If you hit an assert in this function, it was likely called twice, which shouldn't happen
721 * so blame OpenSSL.
722 *
723 * @param[in] ssl session state.
724 * @param[in] sess to serialise and write to the cache.
725 * @return
726 * - 1. What we return is not used by OpenSSL to indicate success
727 * or failure, but to indicate whether it should free its copy of
728 * the session data.
729 * In this case we tell it not to free the session data, as we
730 */
731static int tls_cache_store_cb(SSL *ssl, SSL_SESSION *sess)
732{
733 request_t *request;
734 fr_tls_session_t *tls_session;
735 fr_tls_cache_t *tls_cache;
736 unsigned int id_len;
737 uint8_t const *id;
738
739 /*
740 * This functions should only be called once during the lifetime
741 * of the tls_session, as the fields aren't re-populated on
742 * resumption.
743 */
744 tls_session = fr_tls_session(ssl);
745
746 /*
747 * If the session is TLS 1.3, then resumption will be handled by a
748 * session ticket. However, if this callback is defined, it still
749 * gets called.
750 * To avoid unnecessary entries in the stateful cache just return.
751 */
752 if (tls_session->info.version == TLS1_3_VERSION) return 0;
753
754 request = fr_tls_session_request(tls_session->ssl);
755 tls_cache = tls_session->cache;
756
757 /*
758 * Request was cancelled, just get OpenSSL to
759 * free the session data, and don't do any work.
760 */
761 if (unlang_request_is_cancelled(request)) return 0;
762
763 id = SSL_SESSION_get_id(sess, &id_len);
764 RDEBUG3("Session ID %pV - Requested store", fr_box_octets(id, id_len));
765 /*
766 * Store the session blob and session id for writing
767 * later, once all the authentication phases have completed.
768 */
769 tls_cache->store.sess = sess;
770 tls_cache->store.state = FR_TLS_CACHE_STORE_REQUESTED;
771
772 return 1;
773}
774
775/** Read session data from the cache
776 *
777 * @param[in] ssl session state.
778 * @param[in] key to retrieve session data for.
779 * @param[in] key_len The length of the key.
780 * @param[out] copy Indicates whether OpenSSL should increment the reference
781 * count on SSL_SESSION to prevent it being automatically freed. We always
782 * set this to 0.
783 * @return
784 * - Deserialised session data on success.
785 * - NULL on error.
786 */
787static SSL_SESSION *tls_cache_load_cb(SSL *ssl,
788 unsigned char const *key,
789 int key_len, int *copy)
790{
791 fr_tls_session_t *tls_session;
792 fr_tls_cache_t *tls_cache;
793 request_t *request;
794
795 tls_session = fr_tls_session(ssl);
796 request = fr_tls_session_request(tls_session->ssl);
797 tls_cache = tls_session->cache;
798
799 /*
800 * Request was cancelled, don't return any session and hopefully
801 * OpenSSL will return back to SSL_read() soon.
802 */
803 if (unlang_request_is_cancelled(request)) return NULL;
804
805 /*
806 * Ensure if session resumption is disallowed this callback
807 * will never return session data.
808 */
809 if (!tls_cache || !tls_session->allow_session_resumption) return NULL;
810
811 /*
812 * 1. On the first call we return SSL_magic_pending_session_ptr.
813 * This causes the current SSL_read() call to error out and
814 * for SSL_get_error() to return SSL_ERROR_PENDING_SESSION.
815 * 2. On receiving SSL_ERROR_PENDING_SESSION we asynchronously
816 * load session information from a datastore and associated
817 * it with the SSL session.
818 * 3. We asynchronously validate the certificate information
819 * retrieved during the session session load.
820 * 3. We call SSL_read() again, which in turn calls this callback
821 * again.
822 */
823again:
824 switch (tls_cache->load.state) {
825 case FR_TLS_CACHE_LOAD_INIT:
826 fr_assert(!tls_cache->load.id);
827
828 tls_cache->load.state = FR_TLS_CACHE_LOAD_REQUESTED;
829 MEM(tls_cache->load.id = talloc_typed_memdup(tls_cache, (uint8_t const *)key, key_len));
830
831 RDEBUG3("Requested session load - ID %pV", fr_box_octets_buffer(tls_cache->load.id));
832
833 /*
834 * Cache functions are only allowed during the handshake
835 * FIXME: With TLS 1.3 session tickets can be sent
836 * later... Technically every point where we call
837 * SSL_read() may need to be a yield point.
838 */
839 if (unlikely(!tls_session->can_pause)) {
840 cant_pause:
841 fr_assert_msg("Unexpected call to %s. "
842 "tls_session_async_handshake_cont must be in call stack", __FUNCTION__);
843 return NULL;
844 }
845 /*
846 * Jumps back to SSL_read() in session.c
847 *
848 * Be aware that if the request is cancelled
849 * whatever was meant to be done during the
850 * time we yielded may not have been completed.
851 */
852 ASYNC_pause_job();
853
854 /*
855 * load cache { ... } returned, but the parent
856 * request was cancelled, try and get everything
857 * back into a consistent state and tell OpenSSL
858 * we failed to load the session.
859 */
860 if (unlang_request_is_cancelled(request)) {
861 tls_cache_load_state_reset(request, tls_cache); /* Clears any loaded session data */
862 return NULL;
863
864 }
865 goto again;
866
867 case FR_TLS_CACHE_LOAD_REQUESTED:
868 fr_assert(0); /* Called twice without attempting the load?! */
869 tls_cache->load.state = FR_TLS_CACHE_LOAD_FAILED;
870 break;
871
872 case FR_TLS_CACHE_LOAD_RETRIEVED:
873 {
874 SSL_SESSION *sess;
875
876 TALLOC_FREE(tls_cache->load.id);
877
878 RDEBUG3("Setting session data");
879
880 /*
881 * This restores the contents of &session-state[*]
882 * which hopefully still contains all the certificate
883 * pairs.
884 *
885 * Although the SSL_SESSION does contain a copy of
886 * the peer's certificate, it does not contain the
887 * peer's certificate chain, and so isn't reliable
888 * for performing re-validation.
889 */
890 if (tls_cache_app_data_get(request, tls_cache->load.sess) < 0) {
891 REDEBUG("Denying session resumption via session-id");
892 verify_error:
893 /*
894 * Request the session be deleted the next
895 * time something calls cache action pending.
896 */
897 tls_cache_delete_request(tls_cache->load.sess);
898 tls_cache_load_state_reset(request, tls_session->cache); /* Free the session */
899 return NULL;
900 }
901
902 /*
903 * This sets the validation state of the tls_session
904 * so that when we call ASYNC_pause_job(), and execution
905 * jumps back to tls_session_async_handshake_cont
906 * (just under SSL_read())
907 * the code there knows what job it needs to push onto
908 * the unlang stack.
909 */
910 fr_tls_verify_cert_request(tls_session, true);
911
912 if (unlikely(!tls_session->can_pause)) goto cant_pause;
913 /*
914 * Jumps back to SSL_read() in session.c
915 *
916 * Be aware that if the request is cancelled
917 * whatever was meant to be done during the
918 * time we yielded may not have been completed.
919 */
920 ASYNC_pause_job();
921
922 /*
923 * Certificate validation returned but the request
924 * was cancelled. Free any data we have so far
925 * and reset the states, then let OpenSSL know
926 * we failed to load the session.
927 */
928 if (unlang_request_is_cancelled(request)) {
929 tls_cache_load_state_reset(request, tls_cache); /* Clears any loaded session data */
930 fr_tls_verify_cert_reset(tls_session);
931 return NULL;
932
933 }
934
935 /*
936 * If we couldn't validate the client certificate
937 * then validation overall fails.
938 */
939 if (!fr_tls_verify_cert_result(tls_session)) {
940 RDEBUG2("Certificate re-validation failed, denying session resumption via session-id");
941 goto verify_error;
942 }
943 sess = tls_cache->load.sess;
944
945 /*
946 * After we return it's OpenSSL's responsibility
947 * to free the session data, so set our copy of
948 * the pointer to NULL, to prevent a double free
949 * on cleanup.
950 */
951 {
952 SESSION_ID(sess_id, tls_cache->load.sess);
953
954 RDEBUG3("Session ID %pV - Session ownership transferred to libssl", &sess_id);
955 *copy = 0;
956 tls_cache->load.sess = NULL;
957 }
958 return sess;
959 }
960
961
962 case FR_TLS_CACHE_LOAD_FAILED:
963 RDEBUG3("Session data load failed");
964 break;
965 }
966
967 TALLOC_FREE(tls_cache->load.id);
968 fr_assert(!tls_cache->load.sess);
969
970 return NULL;
971}
972
973/** Delete session data from the cache
974 *
975 * @param[in] ctx Current ssl context.
976 * @param[in] sess to be deleted.
977 */
978static void tls_cache_delete_cb(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
979{
980 /*
981 * Not sure why this happens, but sometimes SSL_SESSION *s
982 * make it here without the correct ex data.
983 *
984 * Maybe it's one OpenSSL created internally?
985 */
986 if (!SSL_SESSION_get_ex_data(sess, FR_TLS_EX_INDEX_TLS_SESSION)) return;
987 tls_cache_delete_request(sess);
988}
989
990/** Prevent a TLS session from being resumed in future
991 *
992 * @note In OpenSSL > 1.1.0 this should not be called directly, but passed as a callback to
993 * SSL_CTX_set_not_resumable_session_callback.
994 *
995 * @param ssl The current OpenSSL session.
996 * @param is_forward_secure Whether the cipher is forward secure, pass -1 if unknown.
997 * @return
998 * - 0 if session-resumption is allowed.
999 * - 1 if enabling session-resumption was disabled for this session.
1000 */
1001int fr_tls_cache_disable_cb(SSL *ssl, int is_forward_secure)
1002{
1003 request_t *request;
1004
1005 fr_tls_session_t *tls_session;
1006 fr_pair_t *vp;
1007
1008 tls_session = fr_tls_session(ssl);
1009 request = fr_tls_session_request(tls_session->ssl);
1010
1011 /*
1012 * Request was cancelled, try and get OpenSSL to
1013 * do as little work as possible.
1014 */
1015 if (unlang_request_is_cancelled(request)) return 1;
1016
1017 {
1018 fr_tls_conf_t *conf;
1019
1020 conf = talloc_get_type_abort(SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF), fr_tls_conf_t);
1021 if (conf->cache.require_extms && (SSL_get_extms_support(tls_session->ssl) == 0)) {
1022 RDEBUG2("Client does not support the Extended Master Secret extension, "
1023 "denying session resumption");
1024 goto disable;
1025 }
1026
1027 if (conf->cache.require_pfs && !is_forward_secure) {
1028 RDEBUG2("Cipher suite is not forward secure, denying session resumption");
1029 goto disable;
1030 }
1031 }
1032
1033 /*
1034 * If there's no session resumption, delete the entry
1035 * from the cache. This means either it's disabled
1036 * globally for this SSL context, OR we were told to
1037 * disable it for this user.
1038 *
1039 * This also means you can't turn it on just for one
1040 * user.
1041 */
1042 if (!tls_session->allow_session_resumption) {
1043 RDEBUG2("Session resumption not enabled for this TLS session, denying session resumption");
1044 goto disable;
1045 }
1046
1047 vp = fr_pair_find_by_da(&request->control_pairs, NULL, attr_allow_session_resumption);
1048 if (vp && (vp->vp_uint32 == 0)) {
1049 RDEBUG2("control.Allow-Session-Resumption == no, denying session resumption");
1050 disable:
1051 SSL_CTX_remove_session(tls_session->ctx, tls_session->session);
1052 tls_session->allow_session_resumption = false;
1053 return 1;
1054 }
1055
1056 RDEBUG2("Allowing future session-resumption");
1057
1058 return 0;
1059}
1060
1061/** Prevent a pending TLS session being persisted, and clear any resumed sessions
1062 *
1063 * Usually called if authentication has failed for some reason.
1064 *
1065 * Will clear any serialized data out of the tls_session structure
1066 * and should result in tls_cache_delete_cb being called.
1067 *
1068 * @note Calling this function will immediately free the memory used
1069 * by the session, but not the external persisted copy of the
1070 * session. To clear the persisted copy #fr_tls_cache_pending_push
1071 * must be called in a place where the caller is prepared to yield.
1072 * In most cases this means whether the handshake is a success or
1073 * failure, the last thing the caller of the TLS code should do
1074 * is set the result, and call #fr_tls_cache_pending_push.
1075 *
1076 * @param[in] request to use for running any async cache actions.
1077 * @param[in] tls_session on which to prevent resumption.
1078 */
1079void fr_tls_cache_deny(request_t *request, fr_tls_session_t *tls_session)
1080{
1081 fr_tls_cache_t *tls_cache = tls_session->cache;
1082 bool tmp_bind = !fr_tls_session_request_bound(tls_session->ssl);
1083
1084 /*
1085 * This is necessary to allow this function to
1086 * be called inside and outside of OpenSSL handshake
1087 * code.
1088 */
1089 if (tmp_bind) {
1090 fr_tls_session_request_bind(tls_session->ssl, request);
1091 /*
1092 * If there's already a request bound, it better be
1093 * the one passed to this function.
1094 */
1095 } else {
1096 fr_assert(fr_tls_session_request(tls_session->ssl) == request);
1097 }
1098
1099 /*
1100 * SSL_CTX_remove_session frees the previously loaded
1101 * session in tls_session. If the reference count reaches zero
1102 * the SSL_CTX_sess_remove_cb is called, which in our code is
1103 * tls_cache_delete_cb.
1104 *
1105 * tls_cache_delete_cb calls tls_cache_delete_request
1106 * to record the ID of tls_session->session
1107 * in our pending cache state structure.
1108 *
1109 * tls_cache_delete_request does NOT immediately call the
1110 * `cache clear {}` section as that must be done in a code area
1111 * which is prepared to yield.
1112 *
1113 * #fr_tls_cache_pending_push MUST be called to actually
1114 * clear external data.
1115 */
1116 if (tls_session->session) SSL_CTX_remove_session(tls_session->ctx, tls_session->session);
1117 tls_session->allow_session_resumption = false;
1118
1119 /*
1120 * Clear any pending store requests.
1121 */
1122 tls_cache_store_state_reset(fr_tls_session_request(tls_session->ssl), tls_cache);
1123
1124 /*
1125 * Unbind the request last...
1126 */
1127 if (tmp_bind) fr_tls_session_request_unbind(tls_session->ssl);
1128}
1129
1130/** Cleanup any memory allocated by OpenSSL
1131 */
1132static int _tls_cache_free(fr_tls_cache_t *tls_cache)
1133{
1134 tls_cache_load_state_reset(NULL, tls_cache);
1135 tls_cache_store_state_reset(NULL, tls_cache);
1136
1137 return 0;
1138}
1139
1140/** Allocate a session cache state structure, and assign it to a tls_session
1141 *
1142 * @note This must be called if session caching is enabled for a tls session.
1143 *
1144 * @param[in] tls_session to assign cache structure to.
1145 */
1146void fr_tls_cache_session_alloc(fr_tls_session_t *tls_session)
1147{
1148 fr_assert(!tls_session->cache);
1149
1150 MEM(tls_session->cache = talloc_zero(tls_session, fr_tls_cache_t));
1151 talloc_set_destructor(tls_session->cache, _tls_cache_free);
1152}
1153
1154/** Disable stateless session tickets for a given TLS ctx
1155 *
1156 * @param[in] ctx to disable session tickets for.
1157 */
1158static inline CC_HINT(always_inline)
1159void tls_cache_disable_stateless_resumption(SSL_CTX *ctx)
1160{
1161 long ctx_options = SSL_CTX_get_options(ctx);
1162
1163 /*
1164 * Disable session tickets for older TLS versions
1165 */
1166 ctx_options |= SSL_OP_NO_TICKET;
1167 SSL_CTX_set_options(ctx, ctx_options);
1168
1169 /*
1170 * This controls the number of stateful or stateless
1171 * tickets generated with TLS 1.3. In OpenSSL 1.1.0
1172 * it's also required to disable sending session tickets,
1173 * SSL_SESS_CACHE_OFF is not good enough.
1174 */
1175 SSL_CTX_set_num_tickets(ctx, 0);
1176}
1177
1178/** Disable stateful session resumption for a given TLS ctx
1179 *
1180 * @param[in] ctx to disable stateful session resumption for.
1181 */
1182static inline CC_HINT(always_inline)
1183void tls_cache_disable_statefull_resumption(SSL_CTX *ctx)
1184{
1185 /*
1186 * Only disables stateful session-resumption.
1187 *
1188 * As per Matt Caswell:
1189 *
1190 * SSL_SESS_CACHE_OFF, when called on the server,
1191 * disables caching of server side sessions.
1192 * It does not switch off resumption. Resumption can
1193 * still occur if a stateless session ticket is used
1194 * (even in TLSv1.2).
1195 */
1196 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1197}
1198
1199/** Called when new tickets are being generated
1200 *
1201 * This adds additional application data to the session ticket to
1202 * allow us to perform validation checks when the session is
1203 * resumed.
1204 */
1205static int tls_cache_session_ticket_app_data_set(SSL *ssl, void *arg)
1206{
1207 fr_tls_session_t *tls_session = fr_tls_session(ssl);
1208 fr_tls_cache_conf_t *tls_cache_conf = arg; /* Not talloced */
1209 SSL_SESSION *sess;
1210 request_t *request;
1211
1212 /*
1213 * Check to see if we have a request bound
1214 * to the session. If we don't have a
1215 * request there's no application data to
1216 * add.
1217 */
1218 if (!fr_tls_session_request_bound(ssl)) return 1;
1219
1220 /*
1221 * Encode the complete session state list
1222 * as app data. Then, when the session is
1223 * resumed, the session-state list is
1224 * repopulated.
1225 */
1226 request = fr_tls_session_request(ssl);
1227
1228 /*
1229 * Request was cancelled, don't do anything.
1230 */
1231 if (unlang_request_is_cancelled(request)) return 0;
1232
1233 /*
1234 * Fatal error - We definitely should be
1235 * attempting to generate session tickets
1236 * if it's not permitted.
1237 */
1238 if (!tls_session->allow_session_resumption ||
1239 (!(tls_cache_conf->mode & FR_TLS_CACHE_STATELESS))) {
1240 REDEBUG("Generating session-tickets is not allowed");
1241 return 0;
1242 }
1243
1244 sess = SSL_get_session(ssl);
1245 if (!sess) {
1246 REDEBUG("Failed retrieving session in session generation callback");
1247 return 0;
1248 }
1249
1250 if (tls_cache_app_data_set(request, sess, enum_tls_session_resumed_stateless->vb_uint32) < 0) return 0;
1251
1252 return 1;
1253}
1254
1255/** Called when new tickets are being decoded
1256 *
1257 * This adds the session-state attributes back to the current request.
1258 */
1259static SSL_TICKET_RETURN tls_cache_session_ticket_app_data_get(SSL *ssl, SSL_SESSION *sess,
1260 UNUSED unsigned char const *keyname,
1261 UNUSED size_t keyname_len,
1262 SSL_TICKET_STATUS status,
1263 void *arg)
1264{
1265 fr_tls_session_t *tls_session = fr_tls_session(ssl);
1266 fr_tls_conf_t *conf = fr_tls_session_conf(tls_session->ssl);
1267 fr_tls_cache_conf_t *tls_cache_conf = arg; /* Not talloced */
1268 request_t *request = NULL;
1269
1270 if (fr_tls_session_request_bound(ssl)) {
1271 request = fr_tls_session_request(ssl);
1272 if (unlang_request_is_cancelled(request)) return SSL_TICKET_RETURN_ABORT;
1273 }
1274
1275 if (!tls_session->allow_session_resumption ||
1276 (!(tls_cache_conf->mode & FR_TLS_CACHE_STATELESS))) {
1277 ROPTIONAL(RDEBUG2, DEBUG2, "Session resumption not enabled for this TLS session, "
1278 "denying session resumption via session-ticket");
1279 return SSL_TICKET_RETURN_IGNORE;
1280 }
1281
1282 switch (status) {
1283 case SSL_TICKET_EMPTY:
1284 case SSL_TICKET_NO_DECRYPT:
1285 case SSL_TICKET_FATAL_ERR_MALLOC:
1286 case SSL_TICKET_FATAL_ERR_OTHER:
1287 case SSL_TICKET_NONE:
1288#ifdef STATIC_ANALYZER
1289 default:
1290#endif
1291 return SSL_TICKET_RETURN_IGNORE_RENEW; /* Send a new ticket */
1292
1293 case SSL_TICKET_SUCCESS:
1294 if (!request) return SSL_TICKET_RETURN_USE;
1295 break;
1296
1297 case SSL_TICKET_SUCCESS_RENEW:
1298 if (!request) return SSL_TICKET_RETURN_USE_RENEW;
1299 break;
1300 }
1301
1302 /*
1303 * This restores the contents of &session-state[*]
1304 * which hopefully still contains all the certificate
1305 * pairs.
1306 *
1307 * Although the SSL_SESSION does contain a copy of
1308 * the peer's certificate, it does not contain the
1309 * peer's certificate chain, and so isn't reliable
1310 * for performing re-validation.
1311 */
1312 if (tls_cache_app_data_get(request, sess) < 0) {
1313 REDEBUG("Denying session resumption via session-ticket");
1314 return SSL_TICKET_RETURN_IGNORE_RENEW;
1315 }
1316
1317 if (conf->virtual_server && tls_session->verify_client_cert) {
1318 RDEBUG2("Requesting certificate re-validation for session-ticket");
1319 /*
1320 * This sets the validation state of the tls_session
1321 * so that when we call ASYNC_pause_job(), and execution
1322 * jumps back to tls_session_async_handshake_cont
1323 * (just under SSL_read())
1324 * the code there knows what job it needs to push onto
1325 * the unlang stack.
1326 */
1327 fr_tls_verify_cert_request(tls_session, true);
1328
1329 /*
1330 * Cache functions are only allowed during the handshake
1331 * FIXME: With TLS 1.3 session tickets can be sent
1332 * later... Technically every point where we call
1333 * SSL_read() may need to be a yield point.
1334 */
1335 if (unlikely(!tls_session->can_pause)) {
1336 fr_assert_msg("Unexpected call to %s. "
1337 "tls_session_async_handshake_cont must be in call stack", __FUNCTION__);
1338 return SSL_TICKET_RETURN_IGNORE_RENEW;
1339 }
1340
1341 /*
1342 * Jumps back to SSL_read() in session.c
1343 *
1344 * Be aware that if the request is cancelled
1345 * whatever was meant to be done during the
1346 * time we yielded may not have been completed.
1347 */
1348 ASYNC_pause_job();
1349
1350 /*
1351 * If the request was cancelled get everything back into
1352 * a known state.
1353 */
1354 if (unlang_request_is_cancelled(request)) {
1355 fr_tls_verify_cert_reset(tls_session);
1356 return SSL_TICKET_RETURN_ABORT;
1357 }
1358
1359 /*
1360 * If we couldn't validate the client certificate
1361 * give the client the opportunity to send a new
1362 * one, but _don't_ allow session resumption.
1363 */
1364 if (!fr_tls_verify_cert_result(tls_session)) {
1365 RDEBUG2("Certificate re-validation failed, denying session resumption via session-ticket");
1366 return SSL_TICKET_RETURN_IGNORE_RENEW;
1367 }
1368 }
1369
1370 return (status == SSL_TICKET_SUCCESS_RENEW) ? SSL_TICKET_RETURN_USE_RENEW : SSL_TICKET_RETURN_USE;
1371}
1372
1373/** Sets callbacks and flags on a SSL_CTX to enable/disable session resumption
1374 *
1375 * @param[in] ctx to modify.
1376 * @param[in] cache_conf Session caching configuration.
1377 * @return
1378 * - 0 on success.
1379 * - -1 on failure.
1380 */
1381int fr_tls_cache_ctx_init(SSL_CTX *ctx, fr_tls_cache_conf_t const *cache_conf)
1382{
1383 switch (cache_conf->mode) {
1384 case FR_TLS_CACHE_DISABLED:
1385 tls_cache_disable_stateless_resumption(ctx);
1386 tls_cache_disable_statefull_resumption(ctx);
1387 return 0;
1388
1389 case FR_TLS_CACHE_AUTO:
1390 case FR_TLS_CACHE_STATEFUL:
1391 /*
1392 * Setup the callbacks for stateful session-resumption
1393 * i.e. where the server stores session information.
1394 */
1395 SSL_CTX_sess_set_new_cb(ctx, tls_cache_store_cb);
1396 SSL_CTX_sess_set_get_cb(ctx, tls_cache_load_cb);
1397 SSL_CTX_sess_set_remove_cb(ctx, tls_cache_delete_cb);
1398
1399 /*
1400 * Controls the stateful cache mode
1401 *
1402 * Here we disable internal lookups, and rely on the
1403 * callbacks above.
1404 */
1405 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_INTERNAL);
1406
1407 /*
1408 * Controls the validity period of the stateful cache.
1409 */
1410 SSL_CTX_set_timeout(ctx, fr_time_delta_to_sec(cache_conf->lifetime));
1411
1412 /*
1413 * Disables stateless session tickets for TLS 1.3.
1414 */
1415 if (!(cache_conf->mode & FR_TLS_CACHE_STATELESS)) {
1416 tls_cache_disable_stateless_resumption(ctx);
1417 break;
1418 }
1420
1421 case FR_TLS_CACHE_STATELESS:
1422 {
1423 size_t key_len;
1424 uint8_t *key_buff;
1425 EVP_PKEY_CTX *pkey_ctx = NULL;
1426
1427 if (!(cache_conf->mode & FR_TLS_CACHE_STATEFUL)) tls_cache_disable_statefull_resumption(ctx);
1428
1429 /*
1430 * If keys is NULL, then OpenSSL returns the expected
1431 * key length, which may be different across different
1432 * flavours/versions of OpenSSL.
1433 *
1434 * We could calculate this in conf.c, but, if in future
1435 * OpenSSL decides to use different key lengths based
1436 * on other parameters in the ctx, that'd break.
1437 */
1438 key_len = SSL_CTX_set_tlsext_ticket_keys(ctx, NULL, 0);
1439
1440 if (unlikely((pkey_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL)) == NULL)) {
1441 fr_tls_strerror_printf(NULL);
1442 PERROR("Failed initialising KDF");
1443 kdf_error:
1444 if (pkey_ctx) EVP_PKEY_CTX_free(pkey_ctx);
1445 return -1;
1446 }
1447 if (unlikely(EVP_PKEY_derive_init(pkey_ctx) != 1)) {
1448 fr_tls_strerror_printf(NULL);
1449 PERROR("Failed initialising KDF derivation ctx");
1450 goto kdf_error;
1451 }
1452 if (unlikely(EVP_PKEY_CTX_set_hkdf_md(pkey_ctx, UNCONST(struct evp_md_st *, EVP_sha256())) != 1)) {
1453 fr_tls_strerror_printf(NULL);
1454 PERROR("Failed setting KDF MD");
1455 goto kdf_error;
1456 }
1457 if (unlikely(EVP_PKEY_CTX_set1_hkdf_key(pkey_ctx,
1458 UNCONST(unsigned char *, cache_conf->session_ticket_key),
1459 talloc_array_length(cache_conf->session_ticket_key)) != 1)) {
1460 fr_tls_strerror_printf(NULL);
1461 PERROR("Failed setting KDF key");
1462 goto kdf_error;
1463 }
1464 if (unlikely(EVP_PKEY_CTX_add1_hkdf_info(pkey_ctx,
1465 UNCONST(unsigned char *, "freeradius-session-ticket"),
1466 sizeof("freeradius-session-ticket") - 1) != 1)) {
1467 fr_tls_strerror_printf(NULL);
1468 PERROR("Failed setting KDF label");
1469 goto kdf_error;
1470 }
1471
1472 /*
1473 * SSL_CTX_set_tlsext_ticket_keys memcpys its
1474 * inputs so this is just a temporary buffer.
1475 */
1476 MEM(key_buff = talloc_array(NULL, uint8_t, key_len));
1477 if (EVP_PKEY_derive(pkey_ctx, key_buff, &key_len) != 1) {
1478 fr_tls_strerror_printf(NULL);
1479 PERROR("Failed deriving session ticket key");
1480
1481 talloc_free(key_buff);
1482 goto kdf_error;
1483 }
1484 EVP_PKEY_CTX_free(pkey_ctx);
1485
1486 fr_assert(talloc_array_length(key_buff) == key_len);
1487 /*
1488 * Ensure the same keys are used across all threads
1489 */
1490 if (SSL_CTX_set_tlsext_ticket_keys(ctx,
1491 key_buff, key_len) != 1) {
1492 fr_tls_strerror_printf(NULL);
1493 PERROR("Failed setting session ticket keys");
1494 return -1;
1495 }
1496
1497 DEBUG3("Derived session-ticket-key:");
1498 HEXDUMP3(key_buff, key_len, NULL);
1499 talloc_free(key_buff);
1500
1501 /*
1502 * These callbacks embed and extract the
1503 * session-state list from the session-ticket.
1504 */
1505 if (unlikely(SSL_CTX_set_session_ticket_cb(ctx,
1506 tls_cache_session_ticket_app_data_set,
1507 tls_cache_session_ticket_app_data_get,
1508 UNCONST(fr_tls_cache_conf_t *, cache_conf)) != 1)) {
1509 fr_tls_strerror_printf(NULL);
1510 PERROR("Failed setting session ticket callbacks");
1511 return -1;
1512 }
1513
1514 /*
1515 * Stateless resumption is enabled by default when
1516 * the TLS ctx is created, but OpenSSL sends too
1517 * many session tickets by default (2), and we only
1518 * need one.
1519 */
1520 SSL_CTX_set_num_tickets(ctx, 1);
1521 }
1522 break;
1523 }
1524
1525 SSL_CTX_set_not_resumable_session_callback(ctx, fr_tls_cache_disable_cb);
1526 SSL_CTX_set_quiet_shutdown(ctx, 1);
1527
1528 return 0;
1529}
1530#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:472
#define RCSID(id)
Definition build.h:485
#define FALL_THROUGH
clang 10 doesn't recognised the FALL-THROUGH comment anymore
Definition build.h:324
#define unlikely(_x)
Definition build.h:383
#define UNUSED
Definition build.h:317
#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:339
#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:2403
bool unlang_request_is_cancelled(request_t const *request)
Return whether a request has been cancelled.
Definition interpret.c:1583
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:828
#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:2966
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:697
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:3011
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
#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:304
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:442
#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:93
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:587
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:4700
static fr_slen_t data
Definition value.h:1288
#define fr_box_octets_buffer(_val)
Definition value.h:309
int nonnull(2, 5))
static size_t char ** out
Definition value.h:1020
#define fr_box_octets(_val, _len)
Definition value.h:307