The FreeRADIUS server $Id: a4e7f8c94e8038b7627bcf52356b7ed15955c1d7 $
Loading...
Searching...
No Matches
ticket_stateful.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: b215bb64b953402621445fe4736d14375a1f6cac $
19 *
20 * @file tls/ticket_stateful.c
21 * @brief Stateful TLS session resumption, the session cache and its `load session`, `store session` and `clear session` sections
22 *
23 * @copyright 2021 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
24 * @copyright 2026 Network RADIUS SAS (legal@networkradius.com)
25 */
26RCSID("$Id: b215bb64b953402621445fe4736d14375a1f6cac $")
27USES_APPLE_DEPRECATED_API /* OpenSSL API has been deprecated by Apple */
28
29#ifdef WITH_TLS
30#define LOG_PREFIX "tls"
31#define _TLS_PRIVATE 1
32
33#include <freeradius-devel/internal/internal.h>
34#include <freeradius-devel/server/pair.h>
35#include <freeradius-devel/unlang/function.h>
36#include <freeradius-devel/unlang/subrequest.h>
37#include <freeradius-devel/util/debug.h>
38
39#include <freeradius-devel/protocol/tls/freeradius.h>
40
41#include "attrs.h"
42#include "base.h"
43#include "log.h"
44#include "strerror.h"
45#include "ticket.h"
46#include "verify.h"
47
48#include <openssl/rand.h>
49#include <openssl/ssl.h>
50
51#define TLS_TICKET_STATEFUL_DISABLED (!tls_cache || !conf->virtual_server)
52
53static inline CC_HINT(always_inline, nonnull(2))
54void _tls_ticket_stateful_load_state_reset(request_t *request, fr_tls_ticket_stateful_t *cache, char const *func)
55{
56 if (cache->load.sess) {
58 if (cache->session_id) {
59 ROPTIONAL(RDEBUG3, DEBUG3, "(TLS) Session ID %pV - Freeing loaded session in %s",
60 cache->session_id, func);
61 } else {
62 ROPTIONAL(RDEBUG3, DEBUG3, "(TLS) Freeing loaded session in %s", func);
63 }
64 }
65
66 SSL_SESSION_free(cache->load.sess);
67 cache->load.sess = NULL;
68 }
69 cache->load.returned = false;
70 cache->load.state = FR_TLS_TICKET_STATEFUL_INIT;
71}
72#define tls_ticket_stateful_load_state_reset(_request, _cache) _tls_ticket_stateful_load_state_reset(_request, _cache, __FUNCTION__)
73
74static inline CC_HINT(always_inline, nonnull(2))
75void _tls_ticket_stateful_store_state_reset(request_t *request, fr_tls_ticket_stateful_t *cache, char const *func)
76{
77 if (cache->store.sess) {
79 ROPTIONAL(RDEBUG3, DEBUG3, "(TLS) Session ID %pV - Freeing session to store in %s", &cache->store.id, func);
80 }
81 SSL_SESSION_free(cache->store.sess);
82 cache->store.sess = NULL;
83 fr_value_box_clear(&cache->store.id);
84 }
85 cache->store.state = FR_TLS_TICKET_STATEFUL_INIT;
86}
87#define tls_ticket_stateful_store_state_reset(_request, _cache) _tls_ticket_stateful_store_state_reset(_request, _cache, __FUNCTION__)
88
89static inline CC_HINT(always_inline)
90void _tls_ticket_stateful_clear_state_reset(request_t *request, fr_tls_ticket_stateful_t *cache, char const *func)
91{
92 if (!fr_type_is_null(cache->clear.id.type)) {
94 ROPTIONAL(RDEBUG3, DEBUG3, "(TLS) Session ID %pV - Freeing session ID to clear in %s",
95 &cache->clear.id, func);
96 }
97 fr_value_box_clear(&cache->clear.id);
98 }
99 cache->clear.state = FR_TLS_TICKET_STATEFUL_INIT;
100}
101#define tls_ticket_stateful_clear_state_reset(_request, _cache) _tls_ticket_stateful_clear_state_reset(_request, _cache, __FUNCTION__)
102
103/** Request `load session { ... }`, and tell the handshake a cache section is pending
104 */
105static inline CC_HINT(always_inline) void tls_ticket_stateful_load_state_request(fr_tls_session_t *tls_session)
106{
107 tls_session->cache->load.state = FR_TLS_TICKET_STATEFUL_REQUESTED;
108 TLS_PENDING_SET(tls_session, FR_TLS_PENDING_STATEFUL_TICKET);
109}
110
111/** Request `store session { ... }`, and tell the handshake a cache section is pending
112 */
113static inline CC_HINT(always_inline) void tls_ticket_stateful_store_state_request(fr_tls_session_t *tls_session)
114{
115 tls_session->cache->store.state = FR_TLS_TICKET_STATEFUL_REQUESTED;
116 TLS_PENDING_SET(tls_session, FR_TLS_PENDING_STATEFUL_TICKET);
117}
118
119/** Request `clear session { ... }`, and tell the handshake a cache section is pending
120 */
121static inline CC_HINT(always_inline) void tls_ticket_stateful_clear_state_request(fr_tls_session_t *tls_session)
122{
123 tls_session->cache->clear.state = FR_TLS_TICKET_STATEFUL_REQUESTED;
124 TLS_PENDING_SET(tls_session, FR_TLS_PENDING_STATEFUL_TICKET);
125}
126
127/** Has `load session { ... }` returned a session which the handshake is still using?
128 *
129 * `load.id` is set when the load is requested, and stays set after a successful load. Every failed
130 * load clears `load.id`. Because every failed load clears `load.id`, a set `load.id` with no load
131 * pending means that the session cache holds an entry for the session.
132 *
133 * @param[in] tls_cache to check.
134 * @return
135 * - true if a loaded session exists, and `load.id` names the cache entry.
136 * - false otherwise.
137 */
138static inline CC_HINT(always_inline) bool tls_ticket_stateful_loaded(fr_tls_ticket_stateful_t const *tls_cache)
139{
140 return !fr_type_is_null(tls_cache->load.id.type) && (tls_cache->load.state != FR_TLS_TICKET_STATEFUL_REQUESTED);
141}
142
143/** Delete session data be deleted from the cache
144 *
145 * @param[in] sess to be deleted.
146 */
147static void tls_ticket_stateful_delete_request(fr_tls_session_t *tls_session, SSL_SESSION *sess)
148{
149 fr_tls_ticket_stateful_t *tls_cache;
151
152 if (!tls_session->cache) return;
153
154 request = fr_tls_session_request(tls_session->ssl);
155 tls_cache = tls_session->cache;
156
157 /*
158 * Request was cancelled just return without doing any work.
159 */
161
162 fr_assert(tls_cache->clear.state == FR_TLS_TICKET_STATEFUL_INIT);
163
164 /*
165 * Record the session to delete
166 */
167 if (tls_ticket_id_to_box(tls_cache, &tls_cache->clear.id, sess) < 0) {
168 RWDEBUG("(TLS) Error retrieving Session ID");
169 return;
170 }
171
172 RDEBUG3("(TLS) Session ID %pV - Requested session clear", &tls_cache->clear.id);
173
174 tls_ticket_stateful_clear_state_request(tls_session);
175
176 /*
177 * Reset any pending `store session`, so that we skip
178 * unnecessary work.
179 */
180 tls_ticket_stateful_store_state_reset(request, tls_cache);
181
182 /*
183 * We _usually_ store a copy of the SSL_SESSION in tls_session->session. If the
184 * session is being freed, then we invalidate the cached SSL_SESSION. Note that
185 * tls_session->session can be NULL sometimes, see tls_ticket_stateful_delete_cb().
186 *
187 * In any case, if the SSL_SESSION pointer exists, we clear it here to avoid leaving a dangling
188 * pointer.
189 */
190 if (tls_session->session) {
191 fr_assert(tls_session->session == sess);
192 tls_session->session = NULL;
193 }
194
195 /*
196 * Previously the code called ASYNC_pause_job();
197 * assuming this callback would always be called
198 * from SSL_read() or another SSL function.
199 *
200 * Unfortunately it appears that the call path
201 * can also be triggered with SSL_CTX_remove_session
202 * if the reference count on the SSL_SESSION
203 * drops to zero.
204 *
205 * We now check the 'can_pause' flag to determine
206 * if we're inside a yieldable SSL_read call.
207 */
208 if (tls_session->can_pause) ASYNC_pause_job();
209}
210
211/** Process the result of `load session { ... }`
212 */
213static unlang_action_t tls_ticket_stateful_load_resume(request_t *request, void *uctx)
214{
215 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
216 fr_tls_ticket_stateful_t *tls_cache = tls_session->cache;
217 fr_pair_t *vp;
218 uint8_t const *q, **p;
219 SSL_SESSION *sess;
220
221 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_packet_type);
222 if (!vp || (vp->vp_uint32 != enum_tls_packet_type_success->vb_uint32)) {
223 RWDEBUG("(TLS) Failed acquiring session data");
224
225 /*
226 * A cache miss answers `notfound`, and a miss is the
227 * normal answer on a first connection. Recording it as
228 * a failure would put an `Error` in the session-state
229 * list of every healthy handshake.
230 */
231 fr_tls_session_error_add(request->parent,
232 (vp && (vp->vp_uint32 == enum_tls_packet_type_notfound->vb_uint32)) ?
233 FR_ERROR_VALUE_LOAD_SESSION_NOT_FOUND :
234 FR_ERROR_VALUE_LOAD_SESSION_FAILED);
235 error:
236 tls_cache->load.state = FR_TLS_TICKET_STATEFUL_FAILED;
238 }
239
240 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_session_data);
241 if (!vp) {
242 RWDEBUG("(TLS) No cached session found");
243 fr_tls_session_error_add(request->parent, FR_ERROR_VALUE_LOAD_SESSION_NOT_FOUND);
244 goto error;
245 }
246
247 q = vp->vp_octets; /* openssl will mutate q, so we can't use vp_octets directly */
248 p = (unsigned char const **)&q;
249
250 sess = d2i_SSL_SESSION(NULL, p, vp->vp_length);
251 if (!sess) {
252 fr_tls_log_perror(request, "Failed loading persisted session");
253 fr_tls_session_error_add(request->parent, FR_ERROR_VALUE_LOAD_SESSION_MALFORMED);
254 goto error;
255 }
256
257 tls_session_id_cache(tls_session, sess); /* the client path has no ID until now */
258
259 if (RDEBUG_ENABLED3) {
260 RDEBUG3("(TLS) Session ID %pV - Read %zu bytes of data. "
261 "Session de-serialized successfully", &tls_session->session_id, vp->vp_length);
262 SSL_SESSION_print(fr_tls_request_log_bio(request, L_DBG, L_DBG_LVL_3), sess);
263 }
264
265 /*
266 * Enforce session timeouts. We don't resume sessions which have exceeded their lifetime.
267 *
268 * The lifetime is already enforced for `store session`. The session may exist on disk (or in a
269 * DB) for long enough that it expires.
270 *
271 * tls_ticket_session_lifetime() clamps to the lowest of the session's own lifetime, the
272 * configured `lifetime`, and the RFC maximum. Clamping to the configured value is what lets
273 * a policy update reach sessions which were stored before it.
274 */
275 {
276 fr_tls_conf_t *conf = tls_session->conf;
277
278 if (!tls_ticket_session_resumable(request, &tls_session->session_id, conf, sess)) {
279 RWDEBUG("(TLS) Session ID %pV - Cached session has too little life left, not resuming",
280 &tls_session->session_id);
281 fr_tls_session_error_add(request, FR_ERROR_VALUE_LOAD_SESSION_EXPIRED);
282
283 /*
284 * The session was allocated by d2i_SSL_SESSION(), and it is not yet saved in
285 * tls_cache->load.sess. We're the only one who knows about it, so we have to
286 * free it.
287 */
288 SSL_SESSION_free(sess);
289 goto error;
290 }
291 }
292
293 /*
294 * OpenSSL's API is very inconsistent.
295 *
296 * We need to set external data here, so it can be
297 * retrieved in tls_ticket_stateful_delete_cb().
298 *
299 * ex_data is not serialised in i2d_SSL_SESSION
300 * so we don't have to bother unsetting it.
301 */
302 SSL_SESSION_set_ex_data(sess, fr_tls_session_ex_index, fr_tls_session(tls_session->ssl));
303
304 tls_cache->load.state = FR_TLS_TICKET_STATEFUL_SUCCESS;
305 tls_cache->load.sess = sess; /* This is consumed in tls_ticket_stateful_load_cb */
306
308}
309
310/** Push a `load session { ... }` call into the current request, using a subrequest
311 *
312 * @param[in] request The current request.
313 * @param[in] tls_session The current TLS session.
314 * @return
315 * - UNLANG_ACTION_CALCULATE_RESULT on noop.
316 * - UNLANG_ACTION_PUSHED_CHILD on success.
317 * - UNLANG_ACTION_FAIL on failure.
318 */
319static unlang_action_t tls_ticket_stateful_load_push(request_t *request, fr_tls_session_t *tls_session)
320{
321 fr_tls_ticket_stateful_t *tls_cache = tls_session->cache;
322 fr_tls_conf_t *conf = tls_session->conf;
323 request_t *child;
325
326 if (TLS_TICKET_STATEFUL_DISABLED) return UNLANG_ACTION_CALCULATE_RESULT;
327
328 if (tls_cache->load.state != FR_TLS_TICKET_STATEFUL_REQUESTED) return UNLANG_ACTION_CALCULATE_RESULT;
329
330 /*
331 * Reset any pending `load session` if there is also a
332 * pending `clear session`, and mark up the load as failed.
333 *
334 * The load is stuck in an async callback via
335 * ASYNC_pause_job(), so we can't reset the load state
336 * here. When it runs, the callback sees that the load
337 * failed, tells OpenSSL that there is no session, and the
338 * peer does a full handshake instead.
339 */
340 if (tls_cache->clear.state == FR_TLS_TICKET_STATEFUL_REQUESTED) {
341 RDEBUG3("(TLS) Session ID %pV - Clear is pending, skipping `load session { ... }`",
342 &tls_cache->load.id);
343 tls_cache->load.state = FR_TLS_TICKET_STATEFUL_FAILED;
345 }
346
347 fr_assert(!fr_type_is_null(tls_cache->load.id.type));
348
349 MEM(child = tls_subrequest_alloc(request, enum_tls_packet_type_load_session->vb_uint32,
350 &tls_cache->load.id));
351
352 /*
353 * Allocate a child, and set it up to call
354 * the TLS virtual server.
355 */
356 ua = fr_tls_call_push(child, tls_ticket_stateful_load_resume, conf, tls_session, true);
357 if (ua == UNLANG_ACTION_FAIL) {
358 talloc_free(child);
359 tls_ticket_stateful_load_state_reset(request, tls_cache);
360 return UNLANG_ACTION_FAIL;
361 }
362
363 return ua;
364}
365
366/** Process the result of `store session { ... }`
367 */
368static unlang_action_t tls_ticket_stateful_store_resume(request_t *request, void *uctx)
369{
370 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
371 fr_tls_ticket_stateful_t *tls_cache = tls_session->cache;
372 fr_pair_t *vp;
373
374 tls_ticket_stateful_store_state_reset(request, tls_cache);
375
376 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_packet_type);
377 if (vp && (vp->vp_uint32 == enum_tls_packet_type_success->vb_uint32)) {
378 tls_cache->store.state = FR_TLS_TICKET_STATEFUL_SUCCESS; /* Avoid spurious clear calls */
379 } else {
380 RWDEBUG("(TLS) Failed storing session data");
381 fr_tls_session_error_add(request->parent, FR_ERROR_VALUE_STORE_SESSION_FAILED);
382 tls_cache->store.state = FR_TLS_TICKET_STATEFUL_INIT;
383 }
384
386}
387
388/** Push a `store session { ... }` call into the current request, using a subrequest
389 *
390 * @param[in] request The current request.
391 * @param[in] conf TLS configuration.
392 * @param[in] tls_session The current TLS session.
393 * @return
394 * - UNLANG_ACTION_CALCULATE_RESULT on noop.
395 * - UNLANG_ACTION_PUSHED_CHILD on success.
396 * - UNLANG_ACTION_FAIL on failure.
397 */
398static inline CC_HINT(always_inline)
399unlang_action_t tls_ticket_stateful_store_push(request_t *request, fr_tls_conf_t *conf, fr_tls_session_t *tls_session)
400{
401 fr_tls_ticket_stateful_t *tls_cache = tls_session->cache;
402 size_t len, ret;
403 int rcode;
404
405 uint8_t *p, *data = NULL;
406
407 request_t *child;
408 fr_pair_t *vp;
409 SSL_SESSION *sess = tls_session->cache->store.sess;
411 fr_time_delta_t ttl;
412
413 if (TLS_TICKET_STATEFUL_DISABLED) return UNLANG_ACTION_CALCULATE_RESULT;
414
415 fr_assert(tls_cache->store.sess);
416 fr_assert(tls_cache->store.state == FR_TLS_TICKET_STATEFUL_REQUESTED);
417
418 /*
419 * If there's a pending clear, then don't push any load /
420 * save / etc. This isn't strictly necessary, but is
421 * good "defense in depth" for any future code changes.
422 * It also documents / enforces our expectations.
423 */
424 if (tls_cache->clear.state == FR_TLS_TICKET_STATEFUL_REQUESTED) {
425 RWDEBUG("(TLS) Session ID %pV - Clear is pending, not storing", &tls_cache->store.id);
426 fr_tls_session_error_add(request, FR_ERROR_VALUE_STORE_CANCELLED_BY_CLEAR);
427 tls_ticket_stateful_store_state_reset(request, tls_cache);
429 }
430
431 ttl = tls_ticket_session_lifetime(request, &tls_cache->store.id, conf, sess);
432 if (!fr_time_delta_ispos(ttl)) {
433 RWDEBUG("(TLS) Session ID %pV - Session has already expired, not storing", &tls_cache->store.id);
434 fr_tls_session_error_add(request, FR_ERROR_VALUE_STORE_SESSION_EXPIRED);
436 }
437
438 /*
439 * Add the current session-state list
440 * contents to the ssl-data
441 */
442 rcode = tls_ticket_app_data_set(request, sess, &tls_cache->store.id);
443 if (rcode < 0) {
444 tls_ticket_stateful_store_state_reset(request, tls_cache);
445 return UNLANG_ACTION_FAIL;
446 }
447
448 if (rcode == 0) return UNLANG_ACTION_CALCULATE_RESULT;
449
450 MEM(child = tls_subrequest_alloc(request, enum_tls_packet_type_store_session->vb_uint32,
451 &tls_cache->store.id));
452 request = child;
453
454 /*
455 * How long the session has to live. Already clamped, the RFC
456 * maximum included, by tls_ticket_session_lifetime() above.
457 */
459 vp->vp_time_delta = ttl;
460
461 /*
462 * Serialize the session
463 */
464 ret = i2d_SSL_SESSION(sess, NULL); /* find out what length data we need */
465 if (ret < 1) {
466 /* something went wrong */
467 fr_tls_strerror_printf(NULL); /* Drain the OpenSSL error stack */
468 RPWDEBUG("(TLS) Session ID %pV - Serialisation failed, couldn't determine "
469 "required buffer length", &tls_cache->store.id);
470 error:
471 tls_ticket_stateful_store_state_reset(request, tls_cache);
472 talloc_free(child);
473 return UNLANG_ACTION_FAIL;
474 }
475 len = ret;
476
478 MEM(data = talloc_array(vp, uint8_t, len));
479
480 /* openssl mutates &p */
481 p = data;
482 ret = i2d_SSL_SESSION(sess, &p); /* Serialize as ASN.1 */
483 if (ret != len) {
484 fr_tls_strerror_printf(NULL); /* Drain the OpenSSL error stack */
485 RPWDEBUG("(TLS) Session ID %pV - Serialisation failed", &tls_cache->store.id);
487 goto error;
488 }
490
491 /*
492 * Allocate a child, and set it up to call
493 * the TLS virtual server.
494 */
495 ua = fr_tls_call_push(child, tls_ticket_stateful_store_resume, conf, tls_session, true);
496 if (ua == UNLANG_ACTION_FAIL) goto error;
497
498 return ua;
499}
500
501/** Process the result of `clear session { ... }`
502 */
503static unlang_action_t tls_ticket_stateful_clear_resume(request_t *request, void *uctx)
504{
505 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
506 fr_tls_ticket_stateful_t *tls_cache = tls_session->cache;
507 fr_pair_t *vp;
508
509 tls_ticket_stateful_clear_state_reset(request, tls_cache);
510
511 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_packet_type);
512 if (vp &&
513 ((vp->vp_uint32 == enum_tls_packet_type_success->vb_uint32) ||
514 (vp->vp_uint32 == enum_tls_packet_type_notfound->vb_uint32))) {
516 }
517
518 RWDEBUG("(TLS) Failed deleting session data - security may be compromised");
519 fr_tls_session_error_add(request->parent, FR_ERROR_VALUE_CLEAR_SESSION_FAILED);
521}
522
523/** Push a `clear session { ... }` call into the current request, using a subrequest
524 *
525 * @param[in] request The current request.
526 * @param[in] conf TLS configuration.
527 * @param[in] tls_session The current TLS session.
528 * @return
529 * - UNLANG_ACTION_CALCULATE_RESULT on noop.
530 * - UNLANG_ACTION_PUSHED_CHILD on success.
531 * - UNLANG_ACTION_FAIL on failure.
532 */
533static inline CC_HINT(always_inline)
534unlang_action_t tls_ticket_stateful_clear_push(request_t *request, fr_tls_conf_t *conf, fr_tls_session_t *tls_session)
535{
536 request_t *child;
537 fr_tls_ticket_stateful_t *tls_cache = tls_session->cache;
539
540 if (TLS_TICKET_STATEFUL_DISABLED) return UNLANG_ACTION_CALCULATE_RESULT;
541
542 fr_assert(tls_cache->clear.state == FR_TLS_TICKET_STATEFUL_REQUESTED);
543 fr_assert(!fr_type_is_null(tls_cache->clear.id.type));
544
545 MEM(child = tls_subrequest_alloc(request, enum_tls_packet_type_clear_session->vb_uint32,
546 &tls_cache->clear.id));
547
548 /*
549 * Allocate a child, and set it up to call
550 * the TLS virtual server.
551 */
552 ua = fr_tls_call_push(child, tls_ticket_stateful_clear_resume, conf, tls_session, true);
553 if (ua == UNLANG_ACTION_FAIL) {
554 talloc_free(child);
555 tls_ticket_stateful_clear_state_reset(request, tls_cache);
556 return UNLANG_ACTION_FAIL;
557 }
558
559 return ua;
560}
561
562/** Process the result of a client's `load session { ... }` call
563 *
564 * A client hands the session to OpenSSL before the handshake starts. The
565 * server path differs: OpenSSL hands a server the session ID part way through
566 * a handshake, and the server returns the matching session.
567 */
568static unlang_action_t tls_ticket_stateful_load_client_resume(request_t *request, void *uctx)
569{
570 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
571 fr_tls_ticket_stateful_t *tls_cache = tls_session->cache;
572
573 (void) tls_ticket_stateful_load_resume(request, uctx);
574
575 if (tls_cache->load.state != FR_TLS_TICKET_STATEFUL_SUCCESS) {
576 RDEBUG2("(TLS) No session to resume");
577 fr_value_box_clear(&tls_cache->load.id);
579 }
580
581 if (SSL_set_session(tls_session->ssl, tls_cache->load.sess) != 1) {
582 fr_tls_log_perror(request, "Failed setting the session to resume");
583 tls_ticket_stateful_load_state_reset(request, tls_cache);
584 fr_value_box_clear(&tls_cache->load.id);
586 }
587
588 RDEBUG2("(TLS) Offering the cached session for resumption");
589
590 fr_tls_alpn_client_resume(request, tls_session->ssl, tls_cache->load.sess, tls_session->conf);
591
592 /*
593 * SSL_set_session() takes its own reference, and nothing else
594 * consumes this one, unlike the server path where the session is
595 * handed back to OpenSSL from tls_ticket_stateful_load_cb.
596 */
597 tls_ticket_stateful_load_state_reset(request, tls_cache);
598
600}
601
602/** Ask the virtual server for a session to resume, as a client
603 *
604 * Call this before the handshake starts. A client chooses which session to
605 * offer, so the client looks a session up under a key the client already
606 * knows, the expansion of `session { name = ... }`. A server makes no such
607 * choice. OpenSSL hands the server the session ID the peer asked for, so the
608 * server path lives in tls_ticket_stateful_load_cb().
609 *
610 * The policy decides what the key means. `TLS-Session-Id` holds the expanded
611 * name, and the `load session { ... }` section may look the session up by
612 * `TLS-Session-Id`, or by any other attribute in the request.
613 *
614 * @param[in] request The current request.
615 * @param[in] tls_session The current TLS session.
616 * @return
617 * - UNLANG_ACTION_CALCULATE_RESULT if there is nothing to do.
618 * - UNLANG_ACTION_PUSHED_CHILD on success.
619 * - UNLANG_ACTION_FAIL on failure.
620 */
621unlang_action_t fr_tls_ticket_stateful_load_client_push(request_t *request, fr_tls_session_t *tls_session)
622{
623 fr_tls_ticket_stateful_t *tls_cache = tls_session->cache;
624 fr_tls_conf_t *conf = tls_session->conf;
625 char *name;
626 request_t *child;
628
629 if (TLS_TICKET_STATEFUL_DISABLED) return UNLANG_ACTION_CALCULATE_RESULT;
630 if (!tls_session->allow_session_resumption) return UNLANG_ACTION_CALCULATE_RESULT;
631
632 fr_assert(conf->cache.id_name);
633
634 if (tmpl_aexpand(tls_session, &name, request, conf->cache.id_name, NULL, NULL) < 0) {
635 RPEDEBUG("(TLS) Failed expanding the session name");
636 return UNLANG_ACTION_FAIL;
637 }
638
639 /*
640 * Keep the session ID in `load.id`. If the session later fails authentication, we need to run
641 * `clear session` on the session we wanted to load.
642 * i.e. `fr_tls_ticket_stateful_clear_session()` clears a failed session by that ID.
643 */
644 fr_assert(fr_type_is_null(tls_cache->load.id.type));
645 MEM(fr_value_box_memdup(tls_cache, &tls_cache->load.id, NULL,
646 (uint8_t const *) name, talloc_strlen(name), false) == 0);
647
648 MEM(child = tls_subrequest_alloc(request, enum_tls_packet_type_load_session->vb_uint32, &tls_cache->load.id));
649
651
652 ua = fr_tls_call_push(child, tls_ticket_stateful_load_client_resume, conf, tls_session, true);
653 if (ua == UNLANG_ACTION_FAIL) {
654 talloc_free(child);
655 fr_value_box_clear(&tls_cache->load.id);
656 return UNLANG_ACTION_FAIL;
657 }
658
659 return ua;
660}
661
662/** Push a `store session { ... }` or `clear session { ... }` or `load session { ... }`
663 *
664 * Depending on what operation is needed.
665 *
666 * @param[in] request The current request.
667 * @param[in] tls_session The current TLS session.
668 * @return
669 * - UNLANG_ACTION_CALCULATE_RESULT - No pending actions
670 * - UNLANG_ACTION_PUSHED_CHILD - Pending operations to evaluate.
671 */
672unlang_action_t fr_tls_ticket_stateful_pending_push(request_t *request, fr_tls_session_t *tls_session)
673{
674 fr_tls_ticket_stateful_t *tls_cache = tls_session->cache;
675 fr_tls_conf_t *conf = tls_session->conf;
677
678 if (!tls_cache) return UNLANG_ACTION_CALCULATE_RESULT; /* No caching allowed, nothing to discard */
679
680 /*
681 * The caller is asking us to push load / store / etc. Since the cache is disabled, we just
682 * reset the state (and free resources), then return. The callers can then check
683 * fr_tls_ticket_stateful_pending(), which will now return "nope".
684 */
685 if (TLS_TICKET_STATEFUL_DISABLED) {
686 if (tls_cache->load.state == FR_TLS_TICKET_STATEFUL_REQUESTED) {
687 tls_ticket_stateful_load_state_reset(request, tls_cache);
688 }
689 if (tls_cache->clear.state == FR_TLS_TICKET_STATEFUL_REQUESTED) {
690 tls_ticket_stateful_clear_state_reset(request, tls_cache);
691 }
692 if (tls_cache->store.state == FR_TLS_TICKET_STATEFUL_REQUESTED) {
693 tls_ticket_stateful_store_state_reset(request, tls_cache);
694 }
696 }
697
698 /*
699 * Load stateful session data.
700 *
701 * tls_ticket_stateful_load_push() may return
702 * UNLANG_ACTION_CALCULATE_RESULT there's a pending
703 * `clear session`. When that happens, we skip the load,
704 * and run the clear instead.
705 */
706 if (tls_cache->load.state == FR_TLS_TICKET_STATEFUL_REQUESTED) {
707 ua = tls_ticket_stateful_load_push(request, tls_session);
708 if (ua != UNLANG_ACTION_CALCULATE_RESULT) return ua;
709 }
710
711 /*
712 * We only support a single session
713 * ticket currently...
714 */
715 if (tls_cache->clear.state == FR_TLS_TICKET_STATEFUL_REQUESTED) {
716 /*
717 * Enforce that there's no queued store, as it
718 * should have been cancelled.
719 */
720 fr_assert(tls_cache->store.state != FR_TLS_TICKET_STATEFUL_REQUESTED);
721 tls_ticket_stateful_store_state_reset(request, tls_cache);
722
723 return tls_ticket_stateful_clear_push(request, conf, tls_session);
724 }
725
726 if (tls_cache->store.state == FR_TLS_TICKET_STATEFUL_REQUESTED) {
727 return tls_ticket_stateful_store_push(request, conf, tls_session);
728 }
729
731}
732
733/** Run all queued cache operations
734 *
735 * Multiple operations may be pushed at the same time. We set
736 * ourselves as the resume function before each push, so that when the
737 * queued operation is done, we can check for another one, and run it.
738 *
739 * @param[in] request to run the cache sections in.
740 * @param[in] uctx the #fr_tls_session_t whose queued operations to run.
741 * @return
742 * - UNLANG_ACTION_PUSHED_CHILD - a cache section is running.
743 * - UNLANG_ACTION_CALCULATE_RESULT - no operation is left.
744 */
745static unlang_action_t tls_ticket_stateful_drain(request_t *request, void *uctx)
746{
747 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
749
750 if (!fr_tls_ticket_stateful_pending(tls_session->cache)) return UNLANG_ACTION_CALCULATE_RESULT;
751
752 /*
753 * Set our repeat before any child is pushed.
754 */
755 if (unlikely(unlang_function_repeat_set(request, tls_ticket_stateful_drain) < 0)) return UNLANG_ACTION_FAIL;
756
757 ua = fr_tls_ticket_stateful_pending_push(request, tls_session);
758 if (ua == UNLANG_ACTION_PUSHED_CHILD) return ua;
759
760 /*
761 * We didn't push anything. Clear the repeat.
762 */
764
765 /*
766 * On error, log the failure and continue.
767 */
768 if (ua == UNLANG_ACTION_FAIL) {
769 REDEBUG("(TLS) Failed running session cache operations");
771 }
772
773 return ua;
774}
775
776/** Push a frame which runs every queued cache operation
777 *
778 * @param[in] request to run the cache sections in.
779 * @param[in] tls_session whose queued operations to run.
780 * @return
781 * - UNLANG_ACTION_PUSHED_CHILD - the queued operations are running.
782 * - UNLANG_ACTION_CALCULATE_RESULT - no operation was queued.
783 * - UNLANG_ACTION_FAIL - the frame could not be pushed.
784 */
785static unlang_action_t tls_ticket_stateful_drain_push(request_t *request, fr_tls_session_t *tls_session)
786{
787 if (!fr_tls_ticket_stateful_pending(tls_session->cache)) return UNLANG_ACTION_CALCULATE_RESULT;
788
789 return unlang_function_push(request, tls_ticket_stateful_drain, NULL, NULL, FR_SIGNAL_NONE, UNLANG_SUB_FRAME, tls_session);
790}
791
792/** Store a session after a successful authentication
793 *
794 * Remember to run `store session { ... }`.
795 *
796 * Just finishing the TLS handshake is not always enough. EAP runs
797 * inner methods inside of the TLS tunnel which can fail. So we only
798 * run `store session` after the inner method succeeds.
799 *
800 * @note The caller MUST set the caller's own unlang result before calling
801 * fr_tls_ticket_stateful_store_session(). A pushed child returns to the caller's
802 * caller with that result already in place.
803 *
804 * @param[in] request to run the cache sections in.
805 * @param[in] tls_session to keep.
806 * @return
807 * - UNLANG_ACTION_PUSHED_CHILD - cache sections are running.
808 * - UNLANG_ACTION_CALCULATE_RESULT - there was nothing to do.
809 * - UNLANG_ACTION_FAIL - the frame could not be pushed.
810 */
811unlang_action_t fr_tls_ticket_stateful_store_session(request_t *request, fr_tls_session_t *tls_session)
812{
813 return tls_ticket_stateful_drain_push(request, tls_session);
814}
815
816/** Clear a session after a failed authentication
817 *
818 * Cancels any pending `store session { ... }`, because a failed session is never stored. If we did a `load
819 * session`, then call `clear session { ... }` for that session. `load session { ... }` just loads, and does not
820 * remove entries.
821 *
822 * A session which was not loaded is not in the cache, so we don't need to run `clear session { ... }`.
823 *
824 * @note The caller MUST set the unlang result of the caller before calling
825 * `fr_tls_ticket_stateful_clear_session()`. A pushed child returns to the caller's caller with
826 * the result that the caller set.
827 *
828 * @param[in] request to run the cache sections in.
829 * @param[in] tls_session to discard.
830 * @return
831 * - UNLANG_ACTION_PUSHED_CHILD - cache sections are running.
832 * - UNLANG_ACTION_CALCULATE_RESULT - there was nothing to do.
833 * - UNLANG_ACTION_FAIL - a frame could not be pushed.
834 */
835unlang_action_t fr_tls_ticket_stateful_clear_session(request_t *request, fr_tls_session_t *tls_session)
836{
837 fr_tls_ticket_stateful_t *tls_cache = tls_session->cache;
838
839 /*
840 * Caching is not allowed for the session. The session has no cache entry to clear.
841 */
842 if (!tls_cache) return UNLANG_ACTION_CALCULATE_RESULT;
843
844 tls_session->allow_session_resumption = false;
845
846 /*
847 * Cancel any pending `store session { ... }`, because a failed session is never stored.
848 */
849 tls_ticket_stateful_store_state_reset(request, tls_cache);
850
851 /*
852 * Queue a clear for the loaded session using `load.id`, unless OpenSSL already queued a clear.
853 * A queued clear has the ID in `load.id`, because OpenSSL asked for the clear when the loaded
854 * session was invalidated.
855 */
856 if (tls_ticket_stateful_loaded(tls_cache) && (tls_cache->clear.state != FR_TLS_TICKET_STATEFUL_REQUESTED)) {
857 if (fr_value_box_copy(tls_cache, &tls_cache->clear.id, &tls_cache->load.id) < 0) {
858 RPERROR("(TLS) Failed recording the session ID to clear");
859 return UNLANG_ACTION_FAIL;
860 }
861
862 RDEBUG3("(TLS) Session ID %pV - Requested session clear", &tls_cache->clear.id);
863 tls_ticket_stateful_clear_state_request(tls_session);
864 }
865
866 return tls_ticket_stateful_drain_push(request, tls_session);
867}
868
869/** Discard a session after a network failure, without clearing the cache.
870 *
871 * See fr_tls_session_fail_session() for more information.
872 *
873 * @note The caller MUST set the caller's own unlang result before calling
874 * `fr_tls_ticket_stateful_discard_session()`. A pushed child returns to the caller's caller with
875 * that result already in place.
876 *
877 * @param[in] request to run the queued `clear session { ... }` in.
878 * @param[in] tls_session to discard.
879 * @return
880 * - UNLANG_ACTION_PUSHED_CHILD - `clear session { ... }` is running.
881 * - UNLANG_ACTION_CALCULATE_RESULT - no section was pushed.
882 * - UNLANG_ACTION_FAIL - a frame could not be pushed.
883 */
884unlang_action_t fr_tls_ticket_stateful_discard_session(request_t *request, fr_tls_session_t *tls_session)
885{
886 fr_tls_ticket_stateful_t *tls_cache = tls_session->cache;
887
888 if (!tls_cache) return UNLANG_ACTION_CALCULATE_RESULT;
889
890 tls_ticket_stateful_store_state_reset(request, tls_cache);
891
892 /*
893 * Do `clear session ` only if it matches a previous `load session`.
894 */
895 if ((tls_cache->clear.state == FR_TLS_TICKET_STATEFUL_REQUESTED) &&
896 (!tls_ticket_stateful_loaded(tls_cache) ||
897 (fr_value_box_cmp(&tls_cache->clear.id, &tls_cache->load.id) != 0))) {
898 tls_ticket_stateful_clear_state_reset(request, tls_cache);
899 }
900
901 return tls_ticket_stateful_drain_push(request, tls_session);
902}
903
904/** Write a newly created session data to the tls_session->cache structure
905 *
906 * @note If you hit an assert in this function, it was likely called twice, which shouldn't happen
907 * so blame OpenSSL.
908 *
909 * @param[in] ssl session state.
910 * @param[in] sess to serialise and write to the cache.
911 * @return
912 * - 1. What we return is not used by OpenSSL to indicate success
913 * or failure, but to indicate whether it should free its copy of
914 * the session data.
915 * In this case we tell it not to free the session data, as we
916 */
917static int tls_ticket_stateful_store_cb(SSL *ssl, SSL_SESSION *sess)
918{
920 fr_tls_session_t *tls_session;
921 fr_tls_ticket_stateful_t *tls_cache;
922
923 /*
924 * This functions should only be called once during the lifetime
925 * of the tls_session, as the fields aren't re-populated on
926 * resumption.
927 */
928 tls_session = fr_tls_session(ssl);
929 request = fr_tls_session_request(tls_session->ssl);
930
931 /*
932 * OpenSSL runs this callback when a session is established or
933 * when a NewSessionTicket arrives. Both happen inside
934 * fr_tls_session_recv(), fr_tls_session_send() or a handshake
935 * round, and each of those binds the request across the call.
936 */
937 fr_assert(request != NULL);
938
939 /*
940 * When handling TLS 1.3, if they are enabled OpenSSL calls both the callback to create stateless
941 * session tickets and this one. If a stateless ticket has been created, we don't need to store
942 * the data in a stateful store as well.
943 * TLS 1.2 handling does the right thing.
944 */
945 if (tls_session->session_ticket_created) {
946 RDEBUG2("(TLS) Stateless ticket already created, not performing stateful store");
947 return 0;
948 }
949
950 /*
951 * RFC 8446 Section 4.6.1 lets a TLS 1.3 server send NewSessionTicket at any point after its
952 * Finished message, including part way through application data. We do not support that.
953 *
954 * Once application data is moving, we discard any session tickets that we receive. TLS doesn't
955 * require us to do this, but we don't know what else to do. The application is processing it's
956 * data, and we do not (as yet) have the code to pause the application, and run a subrequest to
957 * store the new ticket.
958 *
959 * The current implementation runs the cache sections from the handshake, which is the only place
960 * the interpreter can yield. tls_ticket_stateful_store_cb() reaches them through ASYNC_pause_job(), and
961 * that is only legal while tls_session->can_pause is set. Fixing this is an issue for the
962 * future.
963 *
964 * One possible solution is to spawn a _detached_ subrequest which processes the ticket, and only
965 * the ticket. This has to be a subrequest in order to avoid confusing the main application
966 * request (and state machine) with TLS data. We don't care if the `store session` succeeded or
967 * failed, because there's nothing we can really do with that result. The connection is likely
968 * to stay up, so we might as well just ignore errors on `store session`.
969 *
970 * For those reasons and more, we just discard the session ticket. All this means is that the
971 * peer (client here) is unable to use that ticket for session resumption.
972 */
973 if (tls_session->seen_application_data) {
974 RDEBUG2("(TLS) Ignoring session ticket received after application data started");
975 return 0;
976 }
977
978 /*
979 * We have a session ticket. See fr_tls_session_is_init_finished()
980 */
981 tls_session->session_ticket_received = true;
982
983 /*
984 * A server sees this callback once, before anything else has
985 * recorded a session.
986 *
987 * A client has already recorded one: SSL_get_session() runs
988 * when OpenSSL finishes the handshake, which is before the
989 * NewSessionTicket arrives here. The ticket's session is the
990 * one worth keeping, because it is what the client offers
991 * back, so it supersedes.
992 */
993 fr_assert(!tls_session->session || !SSL_is_server(ssl));
994 tls_session->session = sess;
995 tls_session_id_cache(tls_session, sess);
996
997 tls_cache = tls_session->cache;
998
999 fr_assert(tls_cache);
1000 fr_assert(tls_session->conf->virtual_server);
1001
1002 /*
1003 * Request was cancelled, just get OpenSSL to
1004 * free the session data, and don't do any work.
1005 */
1006 if (unlang_request_is_cancelled(request)) return 0;
1007
1008 /*
1009 * Take a copy of the ID, because "return 0" tells
1010 * OpenSSL that it can delete the session. Which means
1011 * that the cached pointer to the session ID could be
1012 * freed.
1013 *
1014 * We may need to use the ID in the `store session` even
1015 * after the session is gone.
1016 */
1017 if (tls_ticket_id_to_box(tls_cache, &tls_cache->store.id, sess) < 0) {
1018 RDEBUG3("(TLS) No Session ID to store");
1019 return 0;
1020 }
1021
1022 RDEBUG3("(TLS) Session ID %pV - Requested store", &tls_cache->store.id);
1023
1024 /*
1025 * Store the session blob and session id for writing
1026 * later, once all the authentication phases have completed.
1027 */
1028 tls_cache->store.sess = sess;
1029 tls_ticket_stateful_store_state_request(tls_session);
1030
1031 return 1;
1032}
1033
1034/** Read session data from the cache
1035 *
1036 * @param[in] ssl session state.
1037 * @param[in] key to retrieve session data for.
1038 * @param[in] key_len The length of the key.
1039 * @param[out] copy Indicates whether OpenSSL should increment the reference
1040 * count on SSL_SESSION to prevent it being automatically freed. We always
1041 * set this to 0.
1042 * @return
1043 * - Deserialised session data on success.
1044 * - NULL on error.
1045 */
1046static SSL_SESSION *tls_ticket_stateful_load_cb(SSL *ssl,
1047 unsigned char const *key,
1048 int key_len, int *copy)
1049{
1050 fr_tls_session_t *tls_session;
1051 fr_tls_ticket_stateful_t *tls_cache;
1053
1054 tls_session = fr_tls_session(ssl);
1055 request = fr_tls_session_request(tls_session->ssl);
1056 tls_cache = tls_session->cache;
1057
1058 fr_assert(tls_cache);
1059 fr_assert(tls_session->conf->virtual_server);
1060
1061 /*
1062 * The request was cancelled. Do not return a session, and
1063 * let OpenSSL fall back to a full handshake.
1064 */
1065 if (unlang_request_is_cancelled(request)) return NULL;
1066
1067 /*
1068 * Never return a session when session resumption is
1069 * disallowed.
1070 */
1071 if (!tls_cache || !tls_session->allow_session_resumption) return NULL;
1072
1073 /*
1074 * OpenSSL runs the handshake, including this callback, on
1075 * one of its fibers (a 32K micro stack by default).
1076 *
1077 * So that we don't have silent memory corruption we ensure
1078 * all the heavy lifting and unlang execution occurs on the
1079 * main thread, and never on the fiber.
1080 *
1081 * 1. On the first call, the callback records the session
1082 * ID, marks the section as pending, and pauses the
1083 * handshake.
1084 * 2. Control returns to
1085 * tls_session_async_handshake_cont(), which pushes the
1086 * section with fr_tls_ticket_stateful_pending_push().
1087 * 3. Once the section has finished,
1088 * tls_session_async_handshake_cont() resumes the
1089 * handshake, and execution continues after the first
1090 * ASYNC_pause_job() call below.
1091 * 4. The callback jumps back to the switch, where the load
1092 * state records whether the section found a session.
1093 * When the section found a session, the callback pauses
1094 * the handshake a second time, and
1095 * `verify certificate { ... }` re-validates the peer
1096 * certificate.
1097 */
1098again:
1099 switch (tls_cache->load.state) {
1100 case FR_TLS_TICKET_STATEFUL_INIT:
1101 fr_assert(fr_type_is_null(tls_cache->load.id.type));
1102
1103 tls_ticket_stateful_load_state_request(tls_session);
1104 MEM(fr_value_box_memdup(tls_cache, &tls_cache->load.id, NULL,
1105 (uint8_t const *)key, key_len, true) == 0);
1106
1107 /*
1108 * The key is the ID of the session that the peer
1109 * asks to resume, and the key stays the session ID
1110 * for the rest of the handshake. Caching the key
1111 * here keeps the log lines that print the ID
1112 * working after load.id is cleared.
1113 */
1114 if (fr_type_is_null(tls_session->session_id.type)) {
1115 MEM(fr_value_box_memdup(tls_session, &tls_session->session_id, NULL,
1116 (uint8_t const *)key, key_len, true) == 0);
1117 if (tls_cache) tls_cache->session_id = &tls_session->session_id;
1118 }
1119
1120 RDEBUG3("(TLS) Requested session load - ID %pV", &tls_cache->load.id);
1121
1122 /*
1123 * Cache functions are only allowed during the
1124 * handshake.
1125 *
1126 * FIXME: With TLS 1.3 session tickets can be sent
1127 * later. Technically every point where we call
1128 * SSL_read() may need to be a yield point.
1129 */
1130 if (unlikely(!tls_session->can_pause)) {
1131 cant_pause:
1132 fr_assert_msg("Unexpected call to %s. "
1133 "tls_session_async_handshake_cont must be in call stack", __FUNCTION__);
1134 return NULL;
1135 }
1136 /*
1137 * Jumps back to SSL_read() in session.c.
1138 *
1139 * If the request is cancelled, whatever was meant
1140 * to be done while the handshake was paused may
1141 * not have been completed.
1142 */
1143 ASYNC_pause_job();
1144
1145 /*
1146 * `load session { ... }` finished, but the request
1147 * was cancelled. Free any loaded session, reset
1148 * the load state, and tell OpenSSL that the load
1149 * failed.
1150 */
1152 tls_ticket_stateful_load_state_reset(request, tls_cache); /* Clears any loaded session data */
1153 fr_value_box_clear(&tls_cache->load.id);
1154 return NULL;
1155
1156 }
1157 goto again;
1158
1159 case FR_TLS_TICKET_STATEFUL_REQUESTED:
1160 fr_assert(0); /* Called twice without attempting the load?! */
1161 tls_cache->load.state = FR_TLS_TICKET_STATEFUL_FAILED;
1162 break;
1163
1164 case FR_TLS_TICKET_STATEFUL_SUCCESS:
1165 {
1166 fr_pair_t *vp;
1167
1168 /*
1169 * OpenSSL calls this callback once for each ClientHello that it receives. A TLS 1.3
1170 * server which sends a HelloRetryRequest receives a second ClientHello, and we don't
1171 * want to run the full `load session` or `verify certificate` sections twice.
1172 *
1173 * The second time we're called, just return the previously found session.
1174 */
1175 if (tls_cache->load.returned) goto return_session;
1176
1177 /*
1178 * The handshake continues with the loaded session. Cache the ID of the loaded session
1179 * in `tls_session->session_id`. `load.id` stays set after a successful load, because we
1180 * need to clear a failed session by that ID.
1181 */
1182 tls_session_id_cache(tls_session, tls_cache->load.sess);
1183
1184 RDEBUG3("(TLS) Setting session data");
1185
1186 /*
1187 * The SSL_SESSION holds a copy of the peer's
1188 * certificate, but not the peer's certificate
1189 * chain. Re-validation needs the chain.
1190 * tls_ticket_app_data_get() therefore restores the
1191 * session-state list, which holds the certificate
1192 * pairs, from the application data stored with the
1193 * session.
1194 */
1195 if (tls_ticket_app_data_get(request, tls_cache->load.sess, &tls_session->session_id) < 0) {
1196 REDEBUG("(TLS) Denying session resumption via session-id");
1197 verify_error:
1198 /*
1199 * Request the `delete session { ... }`
1200 * section, which runs the next time the
1201 * handshake pauses.
1202 */
1203 tls_ticket_stateful_delete_request(tls_session, tls_cache->load.sess);
1204 tls_ticket_stateful_load_state_reset(request, tls_session->cache); /* Free the session */
1205 fr_value_box_clear(&tls_cache->load.id); /* Nothing is loaded, the clear above has the ID */
1206 return NULL;
1207 }
1208
1209 /*
1210 * Add TLS-Session-Resume-Type to report how the session was resumed.
1211 */
1213 RWDEBUG("(TLS) Session ID %pV - Failed adding %s attribute", &tls_session->session_id,
1215 } else {
1216 vp->vp_uint32 = enum_tls_session_resumed_stateful->vb_uint32;
1217 }
1218
1219 /*
1220 * Mark `verify certificate { ... }` as pending,
1221 * for tls_session_async_handshake_cont() to push
1222 * once the handshake pauses below.
1223 */
1224 fr_tls_verify_resumed_request(tls_session);
1225
1226 if (unlikely(!tls_session->can_pause)) goto cant_pause;
1227
1228 /*
1229 * Jumps back to SSL_read() in session.c.
1230 *
1231 * If the request is cancelled, whatever was meant
1232 * to be done while the handshake was paused may
1233 * not have been completed.
1234 */
1235 ASYNC_pause_job();
1236
1237 /*
1238 * `verify certificate { ... }` finished, but the
1239 * request was cancelled. Free any loaded session,
1240 * reset the load and verify states, and tell
1241 * OpenSSL that the load failed.
1242 */
1244 tls_ticket_stateful_load_state_reset(request, tls_cache); /* Clears any loaded session data */
1245 fr_value_box_clear(&tls_cache->load.id);
1246 fr_tls_verify_cert_reset(tls_session);
1247 return NULL;
1248
1249 }
1250
1251 /*
1252 * The callback denies resumption when the peer
1253 * certificate fails re-validation.
1254 */
1255 if (!fr_tls_verify_cert_result(tls_session)) {
1256 RDEBUG2("(TLS) Certificate re-validation failed, denying session resumption via session-id");
1257 goto verify_error;
1258 }
1259 tls_cache->load.returned = true;
1260
1261 return_session:
1262 /*
1263 * OpenSSL frees the reference which the callback returns, so the callback takes a
1264 * reference for OpenSSL, and tells OpenSSL that the callback has done so with
1265 * *copy = 0. `load.sess` keeps the original reference for a second call, and
1266 * tls_ticket_stateful_load_state_reset() frees the original reference.
1267 */
1268 RDEBUG3("(TLS) Session ID %pV - Giving a reference to the session to libssl", &tls_session->session_id);
1269 SSL_SESSION_up_ref(tls_cache->load.sess);
1270 *copy = 0;
1271 return tls_cache->load.sess;
1272 }
1273
1274
1275 case FR_TLS_TICKET_STATEFUL_FAILED:
1276 RDEBUG3("(TLS) Session data load failed");
1277 break;
1278 }
1279
1280 fr_value_box_clear(&tls_cache->load.id);
1281 fr_assert(!tls_cache->load.sess);
1282
1283 return NULL;
1284}
1285
1286/** Delete session data from the cache
1287 *
1288 * @param[in] ctx Current ssl context.
1289 * @param[in] sess to be deleted.
1290 */
1291static void tls_ticket_stateful_delete_cb(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
1292{
1293 fr_tls_session_t *tls_session;
1294
1295 /*
1296 * Not sure why this happens, but sometimes SSL_SESSION *s
1297 * make it here without the correct ex data.
1298 *
1299 * Maybe it's one OpenSSL created internally?
1300 */
1301 tls_session = SSL_SESSION_get_ex_data(sess, fr_tls_session_ex_index);
1302 if (!tls_session) return;
1303
1304 (void) talloc_get_type_abort(tls_session, fr_tls_session_t);
1305
1306 /*
1307 * Note that tls_session->session CAN be NULL here. That's because that field is set during the
1308 * TLS negotiation. If we get a rejection part way though the TLS negotiation, then the field
1309 * isn't set. But OpenSSL passes the SSL_SESSION to us here, so we use that.
1310 */
1311 tls_ticket_stateful_delete_request(tls_session, sess);
1312}
1313
1314/** Cleanup any memory allocated by OpenSSL
1315 */
1316static int _tls_ticket_stateful_free(fr_tls_ticket_stateful_t *tls_cache)
1317{
1318 /*
1319 * `session_id` points at the session ID in the TLS session, which owns `tls_cache`. Talloc
1320 * frees the children of the TLS session in the reverse order of their allocation, so the
1321 * octets of the session ID are already freed when this destructor runs. The reset functions
1322 * log the session ID, so they must not see the pointer.
1323 */
1324 tls_cache->session_id = NULL;
1325
1326 tls_ticket_stateful_load_state_reset(NULL, tls_cache);
1327 tls_ticket_stateful_store_state_reset(NULL, tls_cache);
1328 tls_ticket_stateful_clear_state_reset(NULL, tls_cache);
1329
1330 return 0;
1331}
1332
1333/** Allocate a session cache state structure, and assign it to a tls_session
1334 *
1335 * @note This must be called if session caching is enabled for a tls session.
1336 *
1337 * @param[in] tls_session to assign cache structure to.
1338 */
1339void fr_tls_ticket_stateful_session_alloc(fr_tls_session_t *tls_session)
1340{
1341 fr_assert(!tls_session->cache);
1342
1343 MEM(tls_session->cache = talloc_zero(tls_session, fr_tls_ticket_stateful_t));
1344 talloc_set_destructor(tls_session->cache, _tls_ticket_stateful_free);
1345}
1346
1347/** Disable stateful session resumption for a given TLS ctx
1348 *
1349 * @param[in] ctx to disable stateful session resumption for.
1350 */
1351void fr_tls_ticket_stateful_disable(SSL_CTX *ctx)
1352{
1353 /*
1354 * Only disables stateful session-resumption.
1355 *
1356 * As per Matt Caswell:
1357 *
1358 * SSL_SESS_CACHE_OFF, when called on the server,
1359 * disables caching of server side sessions.
1360 * It does not switch off resumption. Resumption can
1361 * still occur if a stateless session ticket is used
1362 * (even in TLSv1.2).
1363 */
1364 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1365}
1366
1367/** Generate a session ID which is orthogonal to a configured PSK identity.
1368 *
1369 * A TLS 1.3 stateful ticket is the session ID. OpenSSL passes each PSK identity from the client as a `char
1370 * *` to fr_tls_session_psk_server_cb() before looking the identity up as a ticket. That callback therefore
1371 * only checks the identity up to the first NUL. A random session ID which starts with a NUL, or with "safe"
1372 * bytes and a NUL, passes the check, and `load psk` runs with part of the ticket as the PSK identity. If
1373 * `load psk` returns a key, OpenSSL uses the ticket as an external PSK, and the session isn't resumed.
1374 *
1375 * The ID is #TLS_SESSION_ID_MARKER, followed by random bytes which fill the rest of the buffer. OpenSSL
1376 * passes a buffer of SSL3_SSL_SESSION_ID_LENGTH (32) bytes.
1377 *
1378 * @param[in] ssl session. Unused.
1379 * @param[out] id where to write the session ID.
1380 * @param[in,out] id_len the length of the id buffer. The function fills the whole buffer, and leaves
1381 * id_len unchanged.
1382 * @return
1383 * - 1 on success.
1384 * - 0 on failure, which makes OpenSSL fail the handshake.
1385 */
1386static int tls_ticket_stateful_session_id_generate(UNUSED SSL *ssl, unsigned char *id, unsigned int *id_len)
1387{
1388 if (*id_len < 2) return 0;
1389
1390 id[0] = TLS_SESSION_ID_MARKER;
1391
1392 return (RAND_bytes(id + 1, (int) (*id_len - 1)) == 1);
1393}
1394
1395/** Install the stateful session cache callbacks on an SSL_CTX
1396 *
1397 * The callbacks run `store session`, `load session` and `clear session`.
1398 * Internal lookups are disabled, so every lookup goes through the
1399 * callbacks. OpenSSL calls the store callback only for the role the
1400 * cache mode names, so a client context sets SSL_SESS_CACHE_CLIENT
1401 * rather than SSL_SESS_CACHE_SERVER.
1402 *
1403 * @param[in] ctx to install the callbacks on.
1404 * @param[in] cache_conf Session caching configuration, for the lifetime.
1405 * @param[in] client true when the context is for a client.
1406 */
1407void fr_tls_ticket_stateful_ctx_init(SSL_CTX *ctx, fr_tls_ticket_conf_t const *cache_conf, bool client)
1408{
1409 SSL_CTX_sess_set_new_cb(ctx, tls_ticket_stateful_store_cb);
1410 SSL_CTX_sess_set_get_cb(ctx, tls_ticket_stateful_load_cb);
1411 SSL_CTX_sess_set_remove_cb(ctx, tls_ticket_stateful_delete_cb);
1412
1413 SSL_CTX_set_session_cache_mode(ctx, (client ? SSL_SESS_CACHE_CLIENT : SSL_SESS_CACHE_SERVER) |
1414 SSL_SESS_CACHE_NO_INTERNAL);
1415
1416 /*
1417 * Only a server passes PSK identities to fr_tls_session_psk_server_cb(), so a client
1418 * context doesn't need the marker.
1419 */
1420 if (!client) (void) SSL_CTX_set_generate_session_id(ctx, tls_ticket_stateful_session_id_generate);
1421
1422 /*
1423 * Controls the validity period of the stateful cache.
1424 */
1425 SSL_CTX_set_timeout(ctx, fr_time_delta_to_sec(cache_conf->lifetime));
1426}
1427#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_PUSHED_CHILD
unlang_t pushed a new child onto the stack, execute it instead of continuing.
Definition action.h:40
@ 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:38
static uint8_t request[4]
#define USES_APPLE_DEPRECATED_API
Definition build.h:596
#define RCSID(id)
Definition build.h:609
#define IGNORE(_expr, _type)
Definition build.h:633
#define unlikely(_x)
Definition build.h:492
#define UNUSED
Definition build.h:415
#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:248
#define MEM(x)
Definition debug.h:38
int unlang_function_clear(request_t *request)
Clear pending repeat function calls, and remove the signal handler.
Definition function.c:275
#define unlang_function_repeat_set(_request, _repeat)
Set a new repeat function for an existing function frame.
Definition function.h:110
#define unlang_function_push(_request, _func, _repeat, _signal, _sigmask, _top_frame, _uctx)
Push a generic function onto the unlang stack.
Definition function.h:181
talloc_free(hp)
bool unlang_request_is_cancelled(request_t const *request)
Return whether a request has been cancelled.
Definition interpret.c:1997
#define UNLANG_SUB_FRAME
Definition interpret.h:37
#define DEBUG3(_fmt,...)
Definition log.h:271
#define ROPTIONAL(_l_request, _l_global, _fmt,...)
Use different logging functions depending on whether request is NULL or not.
Definition log.h:545
#define RWDEBUG(fmt,...)
Definition log.h:378
#define RDEBUG_ENABLED3
True if request debug level 1-3 messages are enabled.
Definition log.h:352
#define RDEBUG3(fmt,...)
Definition log.h:360
#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:559
#define RPERROR(fmt,...)
Definition log.h:319
#define RPEDEBUG(fmt,...)
Definition log.h:393
#define RPWDEBUG(fmt,...)
Definition log.h:383
#define DEBUG_ENABLED3
True if global debug level 1-3 messages are enabled.
Definition log.h:264
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
fr_value_box_t const * enum_tls_packet_type_clear_session
fr_value_box_t const * enum_tls_packet_type_notfound
HIDDEN fr_dict_attr_t const * attr_tls_session_resume_type
@ L_DBG_LVL_3
3rd highest priority debug messages (-xxx | -Xx).
Definition log.h:69
@ L_DBG
Only displayed when debugging is enabled.
Definition log.h:56
unsigned char uint8_t
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:716
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:2981
#define fr_assert(_expr)
Definition rad_assert.h:37
#define pair_update_request(_attr, _da)
Definition radclient.c:56
#define REDEBUG(fmt,...)
Definition radclient.h:52
#define RDEBUG2(fmt,...)
Definition radclient.h:54
static rs_t * conf
Definition radsniff.c:52
static char const * name
#define pair_update_session_state(_attr, _da)
Return or allocate a fr_pair_t in the session_state list.
Definition pair.h:151
#define tmpl_aexpand(_ctx, _out, _request, _vpt, _escape, _escape_ctx)
Expand a tmpl to a C type, allocing a new buffer to hold the string.
Definition tmpl.h:1089
@ FR_SIGNAL_NONE
No signals.
Definition signal.h:39
fr_pair_t * vp
Stores an attribute, a value and various bits of other data.
Definition pair.h:68
static size_t talloc_strlen(char const *s)
Returns the length of a talloc array containing a string.
Definition talloc.h:143
#define fr_time_delta_ispos(_a)
Definition time.h:290
static int64_t fr_time_delta_to_sec(fr_time_delta_t delta)
Definition time.h:656
A time delta, a difference in time measured in nanoseconds.
Definition time.h:80
#define fr_type_is_null(_x)
Definition types.h:347
fr_cmp_ret_t fr_value_box_cmp(fr_value_box_t const *a, fr_value_box_t const *b)
Compare two values.
Definition value.c:770
int fr_value_box_copy(TALLOC_CTX *ctx, fr_value_box_t *dst, const fr_value_box_t *src)
Copy value data verbatim duplicating any buffers.
Definition value.c:4526
void fr_value_box_clear(fr_value_box_t *data)
Clear/free any existing value and metadata.
Definition value.c:4509
int fr_value_box_memdup(TALLOC_CTX *ctx, fr_value_box_t *dst, fr_dict_attr_t const *enumv, uint8_t const *src, size_t len, bool tainted)
Copy a buffer to a fr_value_box_t.
Definition value.c:5255
static fr_slen_t data
Definition value.h:1366
static fr_sbuff_err_t char size_t * len
Definition value.h:1061
int nonnull(2, 5))