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: ac3fb6e2b246cc39096843b104014f663adcaa8b $
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: ac3fb6e2b246cc39096843b104014f663adcaa8b $")
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 request = fr_tls_session_request(tls_session->ssl);
746 tls_cache = tls_session->cache;
747
748 /*
749 * Request was cancelled, just get OpenSSL to
750 * free the session data, and don't do any work.
751 */
752 if (unlang_request_is_cancelled(request)) return 0;
753
754 id = SSL_SESSION_get_id(sess, &id_len);
755 RDEBUG3("Session ID %pV - Requested store", fr_box_octets(id, id_len));
756 /*
757 * Store the session blob and session id for writing
758 * later, once all the authentication phases have completed.
759 */
760 tls_cache->store.sess = sess;
761 tls_cache->store.state = FR_TLS_CACHE_STORE_REQUESTED;
762
763 return 1;
764}
765
766/** Read session data from the cache
767 *
768 * @param[in] ssl session state.
769 * @param[in] key to retrieve session data for.
770 * @param[in] key_len The length of the key.
771 * @param[out] copy Indicates whether OpenSSL should increment the reference
772 * count on SSL_SESSION to prevent it being automatically freed. We always
773 * set this to 0.
774 * @return
775 * - Deserialised session data on success.
776 * - NULL on error.
777 */
778static SSL_SESSION *tls_cache_load_cb(SSL *ssl,
779 unsigned char const *key,
780 int key_len, int *copy)
781{
782 fr_tls_session_t *tls_session;
783 fr_tls_cache_t *tls_cache;
784 request_t *request;
785
786 tls_session = fr_tls_session(ssl);
787 request = fr_tls_session_request(tls_session->ssl);
788 tls_cache = tls_session->cache;
789
790 /*
791 * Request was cancelled, don't return any session and hopefully
792 * OpenSSL will return back to SSL_read() soon.
793 */
794 if (unlang_request_is_cancelled(request)) return NULL;
795
796 /*
797 * Ensure if session resumption is disallowed this callback
798 * will never return session data.
799 */
800 if (!tls_cache || !tls_session->allow_session_resumption) return NULL;
801
802 /*
803 * 1. On the first call we return SSL_magic_pending_session_ptr.
804 * This causes the current SSL_read() call to error out and
805 * for SSL_get_error() to return SSL_ERROR_PENDING_SESSION.
806 * 2. On receiving SSL_ERROR_PENDING_SESSION we asynchronously
807 * load session information from a datastore and associated
808 * it with the SSL session.
809 * 3. We asynchronously validate the certificate information
810 * retrieved during the session session load.
811 * 3. We call SSL_read() again, which in turn calls this callback
812 * again.
813 */
814again:
815 switch (tls_cache->load.state) {
816 case FR_TLS_CACHE_LOAD_INIT:
817 fr_assert(!tls_cache->load.id);
818
819 tls_cache->load.state = FR_TLS_CACHE_LOAD_REQUESTED;
820 MEM(tls_cache->load.id = talloc_typed_memdup(tls_cache, (uint8_t const *)key, key_len));
821
822 RDEBUG3("Requested session load - ID %pV", fr_box_octets_buffer(tls_cache->load.id));
823
824 /*
825 * Cache functions are only allowed during the handshake
826 * FIXME: With TLS 1.3 session tickets can be sent
827 * later... Technically every point where we call
828 * SSL_read() may need to be a yield point.
829 */
830 if (unlikely(!tls_session->can_pause)) {
831 cant_pause:
832 fr_assert_msg("Unexpected call to %s. "
833 "tls_session_async_handshake_cont must be in call stack", __FUNCTION__);
834 return NULL;
835 }
836 /*
837 * Jumps back to SSL_read() in session.c
838 *
839 * Be aware that if the request is cancelled
840 * whatever was meant to be done during the
841 * time we yielded may not have been completed.
842 */
843 ASYNC_pause_job();
844
845 /*
846 * load cache { ... } returned, but the parent
847 * request was cancelled, try and get everything
848 * back into a consistent state and tell OpenSSL
849 * we failed to load the session.
850 */
851 if (unlang_request_is_cancelled(request)) {
852 tls_cache_load_state_reset(request, tls_cache); /* Clears any loaded session data */
853 return NULL;
854
855 }
856 goto again;
857
858 case FR_TLS_CACHE_LOAD_REQUESTED:
859 fr_assert(0); /* Called twice without attempting the load?! */
860 tls_cache->load.state = FR_TLS_CACHE_LOAD_FAILED;
861 break;
862
863 case FR_TLS_CACHE_LOAD_RETRIEVED:
864 {
865 SSL_SESSION *sess;
866
867 TALLOC_FREE(tls_cache->load.id);
868
869 RDEBUG3("Setting session data");
870
871 /*
872 * This restores the contents of &session-state[*]
873 * which hopefully still contains all the certificate
874 * pairs.
875 *
876 * Although the SSL_SESSION does contain a copy of
877 * the peer's certificate, it does not contain the
878 * peer's certificate chain, and so isn't reliable
879 * for performing re-validation.
880 */
881 if (tls_cache_app_data_get(request, tls_cache->load.sess) < 0) {
882 REDEBUG("Denying session resumption via session-id");
883 verify_error:
884 /*
885 * Request the session be deleted the next
886 * time something calls cache action pending.
887 */
888 tls_cache_delete_request(tls_cache->load.sess);
889 tls_cache_load_state_reset(request, tls_session->cache); /* Free the session */
890 return NULL;
891 }
892
893 /*
894 * This sets the validation state of the tls_session
895 * so that when we call ASYNC_pause_job(), and execution
896 * jumps back to tls_session_async_handshake_cont
897 * (just under SSL_read())
898 * the code there knows what job it needs to push onto
899 * the unlang stack.
900 */
901 fr_tls_verify_cert_request(tls_session, true);
902
903 if (unlikely(!tls_session->can_pause)) goto cant_pause;
904 /*
905 * Jumps back to SSL_read() in session.c
906 *
907 * Be aware that if the request is cancelled
908 * whatever was meant to be done during the
909 * time we yielded may not have been completed.
910 */
911 ASYNC_pause_job();
912
913 /*
914 * Certificate validation returned but the request
915 * was cancelled. Free any data we have so far
916 * and reset the states, then let OpenSSL know
917 * we failed to load the session.
918 */
919 if (unlang_request_is_cancelled(request)) {
920 tls_cache_load_state_reset(request, tls_cache); /* Clears any loaded session data */
921 fr_tls_verify_cert_reset(tls_session);
922 return NULL;
923
924 }
925
926 /*
927 * If we couldn't validate the client certificate
928 * then validation overall fails.
929 */
930 if (!fr_tls_verify_cert_result(tls_session)) {
931 RDEBUG2("Certificate re-validation failed, denying session resumption via session-id");
932 goto verify_error;
933 }
934 sess = tls_cache->load.sess;
935
936 /*
937 * After we return it's OpenSSL's responsibility
938 * to free the session data, so set our copy of
939 * the pointer to NULL, to prevent a double free
940 * on cleanup.
941 */
942 {
943 SESSION_ID(sess_id, tls_cache->load.sess);
944
945 RDEBUG3("Session ID %pV - Session ownership transferred to libssl", &sess_id);
946 *copy = 0;
947 tls_cache->load.sess = NULL;
948 }
949 return sess;
950 }
951
952
953 case FR_TLS_CACHE_LOAD_FAILED:
954 RDEBUG3("Session data load failed");
955 break;
956 }
957
958 TALLOC_FREE(tls_cache->load.id);
959 fr_assert(!tls_cache->load.sess);
960
961 return NULL;
962}
963
964/** Delete session data from the cache
965 *
966 * @param[in] ctx Current ssl context.
967 * @param[in] sess to be deleted.
968 */
969static void tls_cache_delete_cb(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
970{
971 /*
972 * Not sure why this happens, but sometimes SSL_SESSION *s
973 * make it here without the correct ex data.
974 *
975 * Maybe it's one OpenSSL created internally?
976 */
977 if (!SSL_SESSION_get_ex_data(sess, FR_TLS_EX_INDEX_TLS_SESSION)) return;
978 tls_cache_delete_request(sess);
979}
980
981/** Prevent a TLS session from being resumed in future
982 *
983 * @note In OpenSSL > 1.1.0 this should not be called directly, but passed as a callback to
984 * SSL_CTX_set_not_resumable_session_callback.
985 *
986 * @param ssl The current OpenSSL session.
987 * @param is_forward_secure Whether the cipher is forward secure, pass -1 if unknown.
988 * @return
989 * - 0 if session-resumption is allowed.
990 * - 1 if enabling session-resumption was disabled for this session.
991 */
992int fr_tls_cache_disable_cb(SSL *ssl, int is_forward_secure)
993{
994 request_t *request;
995
996 fr_tls_session_t *tls_session;
997 fr_pair_t *vp;
998
999 tls_session = fr_tls_session(ssl);
1000 request = fr_tls_session_request(tls_session->ssl);
1001
1002 /*
1003 * Request was cancelled, try and get OpenSSL to
1004 * do as little work as possible.
1005 */
1006 if (unlang_request_is_cancelled(request)) return 1;
1007
1008 {
1009 fr_tls_conf_t *conf;
1010
1011 conf = talloc_get_type_abort(SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF), fr_tls_conf_t);
1012 if (conf->cache.require_extms && (SSL_get_extms_support(tls_session->ssl) == 0)) {
1013 RDEBUG2("Client does not support the Extended Master Secret extension, "
1014 "denying session resumption");
1015 goto disable;
1016 }
1017
1018 if (conf->cache.require_pfs && !is_forward_secure) {
1019 RDEBUG2("Cipher suite is not forward secure, denying session resumption");
1020 goto disable;
1021 }
1022 }
1023
1024 /*
1025 * If there's no session resumption, delete the entry
1026 * from the cache. This means either it's disabled
1027 * globally for this SSL context, OR we were told to
1028 * disable it for this user.
1029 *
1030 * This also means you can't turn it on just for one
1031 * user.
1032 */
1033 if (!tls_session->allow_session_resumption) {
1034 RDEBUG2("Session resumption not enabled for this TLS session, denying session resumption");
1035 goto disable;
1036 }
1037
1038 vp = fr_pair_find_by_da(&request->control_pairs, NULL, attr_allow_session_resumption);
1039 if (vp && (vp->vp_uint32 == 0)) {
1040 RDEBUG2("control.Allow-Session-Resumption == no, denying session resumption");
1041 disable:
1042 SSL_CTX_remove_session(tls_session->ctx, tls_session->session);
1043 tls_session->allow_session_resumption = false;
1044 return 1;
1045 }
1046
1047 RDEBUG2("Allowing future session-resumption");
1048
1049 return 0;
1050}
1051
1052/** Prevent a pending TLS session being persisted, and clear any resumed sessions
1053 *
1054 * Usually called if authentication has failed for some reason.
1055 *
1056 * Will clear any serialized data out of the tls_session structure
1057 * and should result in tls_cache_delete_cb being called.
1058 *
1059 * @note Calling this function will immediately free the memory used
1060 * by the session, but not the external persisted copy of the
1061 * session. To clear the persisted copy #fr_tls_cache_pending_push
1062 * must be called in a place where the caller is prepared to yield.
1063 * In most cases this means whether the handshake is a success or
1064 * failure, the last thing the caller of the TLS code should do
1065 * is set the result, and call #fr_tls_cache_pending_push.
1066 *
1067 * @param[in] request to use for running any async cache actions.
1068 * @param[in] tls_session on which to prevent resumption.
1069 */
1070void fr_tls_cache_deny(request_t *request, fr_tls_session_t *tls_session)
1071{
1072 fr_tls_cache_t *tls_cache = tls_session->cache;
1073 bool tmp_bind = !fr_tls_session_request_bound(tls_session->ssl);
1074
1075 /*
1076 * This is necessary to allow this function to
1077 * be called inside and outside of OpenSSL handshake
1078 * code.
1079 */
1080 if (tmp_bind) {
1081 fr_tls_session_request_bind(tls_session->ssl, request);
1082 /*
1083 * If there's already a request bound, it better be
1084 * the one passed to this function.
1085 */
1086 } else {
1087 fr_assert(fr_tls_session_request(tls_session->ssl) == request);
1088 }
1089
1090 /*
1091 * SSL_CTX_remove_session frees the previously loaded
1092 * session in tls_session. If the reference count reaches zero
1093 * the SSL_CTX_sess_remove_cb is called, which in our code is
1094 * tls_cache_delete_cb.
1095 *
1096 * tls_cache_delete_cb calls tls_cache_delete_request
1097 * to record the ID of tls_session->session
1098 * in our pending cache state structure.
1099 *
1100 * tls_cache_delete_request does NOT immediately call the
1101 * `cache clear {}` section as that must be done in a code area
1102 * which is prepared to yield.
1103 *
1104 * #fr_tls_cache_pending_push MUST be called to actually
1105 * clear external data.
1106 */
1107 if (tls_session->session) SSL_CTX_remove_session(tls_session->ctx, tls_session->session);
1108 tls_session->allow_session_resumption = false;
1109
1110 /*
1111 * Clear any pending store requests.
1112 */
1113 tls_cache_store_state_reset(fr_tls_session_request(tls_session->ssl), tls_cache);
1114
1115 /*
1116 * Unbind the request last...
1117 */
1118 if (tmp_bind) fr_tls_session_request_unbind(tls_session->ssl);
1119}
1120
1121/** Cleanup any memory allocated by OpenSSL
1122 */
1123static int _tls_cache_free(fr_tls_cache_t *tls_cache)
1124{
1125 tls_cache_load_state_reset(NULL, tls_cache);
1126 tls_cache_store_state_reset(NULL, tls_cache);
1127
1128 return 0;
1129}
1130
1131/** Allocate a session cache state structure, and assign it to a tls_session
1132 *
1133 * @note This must be called if session caching is enabled for a tls session.
1134 *
1135 * @param[in] tls_session to assign cache structure to.
1136 */
1137void fr_tls_cache_session_alloc(fr_tls_session_t *tls_session)
1138{
1139 fr_assert(!tls_session->cache);
1140
1141 MEM(tls_session->cache = talloc_zero(tls_session, fr_tls_cache_t));
1142 talloc_set_destructor(tls_session->cache, _tls_cache_free);
1143}
1144
1145/** Disable stateless session tickets for a given TLS ctx
1146 *
1147 * @param[in] ctx to disable session tickets for.
1148 */
1149static inline CC_HINT(always_inline)
1150void tls_cache_disable_stateless_resumption(SSL_CTX *ctx)
1151{
1152 long ctx_options = SSL_CTX_get_options(ctx);
1153
1154 /*
1155 * Disable session tickets for older TLS versions
1156 */
1157 ctx_options |= SSL_OP_NO_TICKET;
1158 SSL_CTX_set_options(ctx, ctx_options);
1159
1160 /*
1161 * This controls the number of stateful or stateless
1162 * tickets generated with TLS 1.3. In OpenSSL 1.1.0
1163 * it's also required to disable sending session tickets,
1164 * SSL_SESS_CACHE_OFF is not good enough.
1165 */
1166 SSL_CTX_set_num_tickets(ctx, 0);
1167}
1168
1169/** Disable stateful session resumption for a given TLS ctx
1170 *
1171 * @param[in] ctx to disable stateful session resumption for.
1172 */
1173static inline CC_HINT(always_inline)
1174void tls_cache_disable_statefull_resumption(SSL_CTX *ctx)
1175{
1176 /*
1177 * Only disables stateful session-resumption.
1178 *
1179 * As per Matt Caswell:
1180 *
1181 * SSL_SESS_CACHE_OFF, when called on the server,
1182 * disables caching of server side sessions.
1183 * It does not switch off resumption. Resumption can
1184 * still occur if a stateless session ticket is used
1185 * (even in TLSv1.2).
1186 */
1187 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1188}
1189
1190/** Called when new tickets are being generated
1191 *
1192 * This adds additional application data to the session ticket to
1193 * allow us to perform validation checks when the session is
1194 * resumed.
1195 */
1196static int tls_cache_session_ticket_app_data_set(SSL *ssl, void *arg)
1197{
1198 fr_tls_session_t *tls_session = fr_tls_session(ssl);
1199 fr_tls_cache_conf_t *tls_cache_conf = arg; /* Not talloced */
1200 SSL_SESSION *sess;
1201 request_t *request;
1202
1203 /*
1204 * Check to see if we have a request bound
1205 * to the session. If we don't have a
1206 * request there's no application data to
1207 * add.
1208 */
1209 if (!fr_tls_session_request_bound(ssl)) return 1;
1210
1211 /*
1212 * Encode the complete session state list
1213 * as app data. Then, when the session is
1214 * resumed, the session-state list is
1215 * repopulated.
1216 */
1217 request = fr_tls_session_request(ssl);
1218
1219 /*
1220 * Request was cancelled, don't do anything.
1221 */
1222 if (unlang_request_is_cancelled(request)) return 0;
1223
1224 /*
1225 * Fatal error - We definitely should be
1226 * attempting to generate session tickets
1227 * if it's not permitted.
1228 */
1229 if (!tls_session->allow_session_resumption ||
1230 (!(tls_cache_conf->mode & FR_TLS_CACHE_STATELESS))) {
1231 REDEBUG("Generating session-tickets is not allowed");
1232 return 0;
1233 }
1234
1235 sess = SSL_get_session(ssl);
1236 if (!sess) {
1237 REDEBUG("Failed retrieving session in session generation callback");
1238 return 0;
1239 }
1240
1241 if (tls_cache_app_data_set(request, sess, enum_tls_session_resumed_stateless->vb_uint32) < 0) return 0;
1242
1243 return 1;
1244}
1245
1246/** Called when new tickets are being decoded
1247 *
1248 * This adds the session-state attributes back to the current request.
1249 */
1250static SSL_TICKET_RETURN tls_cache_session_ticket_app_data_get(SSL *ssl, SSL_SESSION *sess,
1251 UNUSED unsigned char const *keyname,
1252 UNUSED size_t keyname_len,
1253 SSL_TICKET_STATUS status,
1254 void *arg)
1255{
1256 fr_tls_session_t *tls_session = fr_tls_session(ssl);
1257 fr_tls_conf_t *conf = fr_tls_session_conf(tls_session->ssl);
1258 fr_tls_cache_conf_t *tls_cache_conf = arg; /* Not talloced */
1259 request_t *request = NULL;
1260
1261 if (fr_tls_session_request_bound(ssl)) {
1262 request = fr_tls_session_request(ssl);
1263 if (unlang_request_is_cancelled(request)) return SSL_TICKET_RETURN_ABORT;
1264 }
1265
1266 if (!tls_session->allow_session_resumption ||
1267 (!(tls_cache_conf->mode & FR_TLS_CACHE_STATELESS))) {
1268 ROPTIONAL(RDEBUG2, DEBUG2, "Session resumption not enabled for this TLS session, "
1269 "denying session resumption via session-ticket");
1270 return SSL_TICKET_RETURN_IGNORE;
1271 }
1272
1273 switch (status) {
1274 case SSL_TICKET_EMPTY:
1275 case SSL_TICKET_NO_DECRYPT:
1276 case SSL_TICKET_FATAL_ERR_MALLOC:
1277 case SSL_TICKET_FATAL_ERR_OTHER:
1278 case SSL_TICKET_NONE:
1279#ifdef STATIC_ANALYZER
1280 default:
1281#endif
1282 return SSL_TICKET_RETURN_IGNORE_RENEW; /* Send a new ticket */
1283
1284 case SSL_TICKET_SUCCESS:
1285 if (!request) return SSL_TICKET_RETURN_USE;
1286 break;
1287
1288 case SSL_TICKET_SUCCESS_RENEW:
1289 if (!request) return SSL_TICKET_RETURN_USE_RENEW;
1290 break;
1291 }
1292
1293 /*
1294 * This restores the contents of &session-state[*]
1295 * which hopefully still contains all the certificate
1296 * pairs.
1297 *
1298 * Although the SSL_SESSION does contain a copy of
1299 * the peer's certificate, it does not contain the
1300 * peer's certificate chain, and so isn't reliable
1301 * for performing re-validation.
1302 */
1303 if (tls_cache_app_data_get(request, sess) < 0) {
1304 REDEBUG("Denying session resumption via session-ticket");
1305 return SSL_TICKET_RETURN_IGNORE_RENEW;
1306 }
1307
1308 if (conf->virtual_server && tls_session->verify_client_cert) {
1309 RDEBUG2("Requesting certificate re-validation for session-ticket");
1310 /*
1311 * This sets the validation state of the tls_session
1312 * so that when we call ASYNC_pause_job(), and execution
1313 * jumps back to tls_session_async_handshake_cont
1314 * (just under SSL_read())
1315 * the code there knows what job it needs to push onto
1316 * the unlang stack.
1317 */
1318 fr_tls_verify_cert_request(tls_session, true);
1319
1320 /*
1321 * Cache functions are only allowed during the handshake
1322 * FIXME: With TLS 1.3 session tickets can be sent
1323 * later... Technically every point where we call
1324 * SSL_read() may need to be a yield point.
1325 */
1326 if (unlikely(!tls_session->can_pause)) {
1327 fr_assert_msg("Unexpected call to %s. "
1328 "tls_session_async_handshake_cont must be in call stack", __FUNCTION__);
1329 return SSL_TICKET_RETURN_IGNORE_RENEW;
1330 }
1331
1332 /*
1333 * Jumps back to SSL_read() in session.c
1334 *
1335 * Be aware that if the request is cancelled
1336 * whatever was meant to be done during the
1337 * time we yielded may not have been completed.
1338 */
1339 ASYNC_pause_job();
1340
1341 /*
1342 * If the request was cancelled get everything back into
1343 * a known state.
1344 */
1345 if (unlang_request_is_cancelled(request)) {
1346 fr_tls_verify_cert_reset(tls_session);
1347 return SSL_TICKET_RETURN_ABORT;
1348 }
1349
1350 /*
1351 * If we couldn't validate the client certificate
1352 * give the client the opportunity to send a new
1353 * one, but _don't_ allow session resumption.
1354 */
1355 if (!fr_tls_verify_cert_result(tls_session)) {
1356 RDEBUG2("Certificate re-validation failed, denying session resumption via session-ticket");
1357 return SSL_TICKET_RETURN_IGNORE_RENEW;
1358 }
1359 }
1360
1361 return (status == SSL_TICKET_SUCCESS_RENEW) ? SSL_TICKET_RETURN_USE_RENEW : SSL_TICKET_RETURN_USE;
1362}
1363
1364/** Sets callbacks and flags on a SSL_CTX to enable/disable session resumption
1365 *
1366 * @param[in] ctx to modify.
1367 * @param[in] cache_conf Session caching configuration.
1368 * @return
1369 * - 0 on success.
1370 * - -1 on failure.
1371 */
1372int fr_tls_cache_ctx_init(SSL_CTX *ctx, fr_tls_cache_conf_t const *cache_conf)
1373{
1374 switch (cache_conf->mode) {
1375 case FR_TLS_CACHE_DISABLED:
1376 tls_cache_disable_stateless_resumption(ctx);
1377 tls_cache_disable_statefull_resumption(ctx);
1378 return 0;
1379
1380 case FR_TLS_CACHE_AUTO:
1381 case FR_TLS_CACHE_STATEFUL:
1382 /*
1383 * Setup the callbacks for stateful session-resumption
1384 * i.e. where the server stores session information.
1385 */
1386 SSL_CTX_sess_set_new_cb(ctx, tls_cache_store_cb);
1387 SSL_CTX_sess_set_get_cb(ctx, tls_cache_load_cb);
1388 SSL_CTX_sess_set_remove_cb(ctx, tls_cache_delete_cb);
1389
1390 /*
1391 * Controls the stateful cache mode
1392 *
1393 * Here we disable internal lookups, and rely on the
1394 * callbacks above.
1395 */
1396 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_INTERNAL);
1397
1398 /*
1399 * Controls the validity period of the stateful cache.
1400 */
1401 SSL_CTX_set_timeout(ctx, fr_time_delta_to_sec(cache_conf->lifetime));
1402
1403 /*
1404 * Disables stateless session tickets for TLS 1.3.
1405 */
1406 if (!(cache_conf->mode & FR_TLS_CACHE_STATELESS)) {
1407 tls_cache_disable_stateless_resumption(ctx);
1408 break;
1409 }
1411
1412 case FR_TLS_CACHE_STATELESS:
1413 {
1414 size_t key_len;
1415 uint8_t *key_buff;
1416 EVP_PKEY_CTX *pkey_ctx = NULL;
1417
1418 if (!(cache_conf->mode & FR_TLS_CACHE_STATEFUL)) tls_cache_disable_statefull_resumption(ctx);
1419
1420 /*
1421 * If keys is NULL, then OpenSSL returns the expected
1422 * key length, which may be different across different
1423 * flavours/versions of OpenSSL.
1424 *
1425 * We could calculate this in conf.c, but, if in future
1426 * OpenSSL decides to use different key lengths based
1427 * on other parameters in the ctx, that'd break.
1428 */
1429 key_len = SSL_CTX_set_tlsext_ticket_keys(ctx, NULL, 0);
1430
1431 if (unlikely((pkey_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL)) == NULL)) {
1432 fr_tls_strerror_printf(NULL);
1433 PERROR("Failed initialising KDF");
1434 kdf_error:
1435 if (pkey_ctx) EVP_PKEY_CTX_free(pkey_ctx);
1436 return -1;
1437 }
1438 if (unlikely(EVP_PKEY_derive_init(pkey_ctx) != 1)) {
1439 fr_tls_strerror_printf(NULL);
1440 PERROR("Failed initialising KDF derivation ctx");
1441 goto kdf_error;
1442 }
1443 if (unlikely(EVP_PKEY_CTX_set_hkdf_md(pkey_ctx, UNCONST(struct evp_md_st *, EVP_sha256())) != 1)) {
1444 fr_tls_strerror_printf(NULL);
1445 PERROR("Failed setting KDF MD");
1446 goto kdf_error;
1447 }
1448 if (unlikely(EVP_PKEY_CTX_set1_hkdf_key(pkey_ctx,
1449 UNCONST(unsigned char *, cache_conf->session_ticket_key),
1450 talloc_array_length(cache_conf->session_ticket_key)) != 1)) {
1451 fr_tls_strerror_printf(NULL);
1452 PERROR("Failed setting KDF key");
1453 goto kdf_error;
1454 }
1455 if (unlikely(EVP_PKEY_CTX_add1_hkdf_info(pkey_ctx,
1456 UNCONST(unsigned char *, "freeradius-session-ticket"),
1457 sizeof("freeradius-session-ticket") - 1) != 1)) {
1458 fr_tls_strerror_printf(NULL);
1459 PERROR("Failed setting KDF label");
1460 goto kdf_error;
1461 }
1462
1463 /*
1464 * SSL_CTX_set_tlsext_ticket_keys memcpys its
1465 * inputs so this is just a temporary buffer.
1466 */
1467 MEM(key_buff = talloc_array(NULL, uint8_t, key_len));
1468 if (EVP_PKEY_derive(pkey_ctx, key_buff, &key_len) != 1) {
1469 fr_tls_strerror_printf(NULL);
1470 PERROR("Failed deriving session ticket key");
1471
1472 talloc_free(key_buff);
1473 goto kdf_error;
1474 }
1475 EVP_PKEY_CTX_free(pkey_ctx);
1476
1477 fr_assert(talloc_array_length(key_buff) == key_len);
1478 /*
1479 * Ensure the same keys are used across all threads
1480 */
1481 if (SSL_CTX_set_tlsext_ticket_keys(ctx,
1482 key_buff, key_len) != 1) {
1483 fr_tls_strerror_printf(NULL);
1484 PERROR("Failed setting session ticket keys");
1485 return -1;
1486 }
1487
1488 DEBUG3("Derived session-ticket-key:");
1489 HEXDUMP3(key_buff, key_len, NULL);
1490 talloc_free(key_buff);
1491
1492 /*
1493 * These callbacks embed and extract the
1494 * session-state list from the session-ticket.
1495 */
1496 if (unlikely(SSL_CTX_set_session_ticket_cb(ctx,
1497 tls_cache_session_ticket_app_data_set,
1498 tls_cache_session_ticket_app_data_get,
1499 UNCONST(fr_tls_cache_conf_t *, cache_conf)) != 1)) {
1500 fr_tls_strerror_printf(NULL);
1501 PERROR("Failed setting session ticket callbacks");
1502 return -1;
1503 }
1504
1505 /*
1506 * Stateless resumption is enabled by default when
1507 * the TLS ctx is created, but OpenSSL sends too
1508 * many session tickets by default (2), and we only
1509 * need one.
1510 */
1511 SSL_CTX_set_num_tickets(ctx, 1);
1512 }
1513 break;
1514 }
1515
1516 SSL_CTX_set_not_resumable_session_callback(ctx, fr_tls_cache_disable_cb);
1517 SSL_CTX_set_quiet_shutdown(ctx, 1);
1518
1519 return 0;
1520}
1521#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:1579
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