The FreeRADIUS server $Id: a4e7f8c94e8038b7627bcf52356b7ed15955c1d7 $
Loading...
Searching...
No Matches
session.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: 9a686fa6d95e45847f808625a31cb6f437fcade3 $
19 *
20 * @file tls/session.c
21 * @brief Initialise OpenSSL sessions, and read/write data to/from them.
22 *
23 * @copyright 2026 Network RADIUS SAS (legal@networkradius.com)
24 */
25#ifdef WITH_TLS
26#define LOG_PREFIX "tls"
27#define _TLS_PRIVATE 1
28
29#include <freeradius-devel/server/pair.h>
30#include <freeradius-devel/server/log.h>
31
32#include <freeradius-devel/util/debug.h>
33#include <freeradius-devel/util/math.h>
34#include <freeradius-devel/util/base16.h>
35#include <freeradius-devel/util/skip.h>
36#include <freeradius-devel/util/pair_legacy.h>
37
38#include <freeradius-devel/protocol/freeradius/freeradius.internal.h>
39
40#include <freeradius-devel/unlang/action.h>
41#include <freeradius-devel/unlang/call.h>
42#include <freeradius-devel/unlang/interpret.h>
43#include <freeradius-devel/unlang/subrequest.h>
44
45#include <sys/stat.h>
46#include <fcntl.h>
47
48#include <freeradius-devel/protocol/tls/freeradius.h>
49
50#include "attrs.h"
51#include "base.h"
52#include "dtls.h"
53#include "log.h"
54
55#include <openssl/x509v3.h>
56#include <openssl/ssl.h>
57
58static char const *tls_version_str[] = {
59 [SSL2_VERSION] = "SSL 2.0",
60 [SSL3_VERSION] = "SSL 3.0",
61 [TLS1_VERSION] = "TLS 1.0",
62 [TLS1_1_VERSION] = "TLS 1.1",
63 [TLS1_2_VERSION] = "TLS 1.2",
64 [TLS1_3_VERSION] = "TLS 1.3",
65#ifdef TLS1_4_VERSION
66 [TLS1_4_VERSION] = "TLS 1.4",
67#endif
68};
69
70static char const *tls_content_type_str[] = {
71 [SSL3_RT_CHANGE_CIPHER_SPEC] = "change_cipher_spec",
72 [SSL3_RT_ALERT] = "alert",
73 [SSL3_RT_HANDSHAKE] = "handshake",
74 [SSL3_RT_APPLICATION_DATA] = "application_data",
75#ifdef SSL3_RT_HEADER
76 [SSL3_RT_HEADER] = "header",
77#endif
78#ifdef SSL3_RT_INNER_CONTENT_TYPE
79 [SSL3_RT_INNER_CONTENT_TYPE] = "inner_content_type",
80#endif
81};
82
83static char const *tls_alert_description_str[] = {
84 [SSL3_AD_CLOSE_NOTIFY] = "close_notify",
85 [SSL3_AD_UNEXPECTED_MESSAGE] = "unexpected_message",
86 [SSL3_AD_BAD_RECORD_MAC] = "bad_record_mac",
87 [TLS1_AD_DECRYPTION_FAILED] = "decryption_failed",
88 [TLS1_AD_RECORD_OVERFLOW] = "record_overflow",
89 [SSL3_AD_DECOMPRESSION_FAILURE] = "decompression_failure",
90 [SSL3_AD_HANDSHAKE_FAILURE] = "handshake_failure",
91 [SSL3_AD_BAD_CERTIFICATE] = "bad_certificate",
92 [SSL3_AD_UNSUPPORTED_CERTIFICATE] = "unsupported_certificate",
93 [SSL3_AD_CERTIFICATE_REVOKED] = "certificate_revoked",
94 [SSL3_AD_CERTIFICATE_EXPIRED] = "certificate_expired",
95 [SSL3_AD_CERTIFICATE_UNKNOWN] = "certificate_unknown",
96 [SSL3_AD_ILLEGAL_PARAMETER] = "illegal_parameter",
97 [TLS1_AD_UNKNOWN_CA] = "unknown_ca",
98 [TLS1_AD_ACCESS_DENIED] = "access_denied",
99 [TLS1_AD_DECODE_ERROR] = "decode_error",
100 [TLS1_AD_DECRYPT_ERROR] = "decrypt_error",
101 [TLS1_AD_EXPORT_RESTRICTION] = "export_restriction",
102 [TLS1_AD_PROTOCOL_VERSION] = "protocol_version",
103 [TLS1_AD_INSUFFICIENT_SECURITY] = "insufficient_security",
104 [TLS1_AD_INTERNAL_ERROR] = "internal_error",
105 [TLS1_AD_USER_CANCELLED] = "user_cancelled",
106 [TLS1_AD_NO_RENEGOTIATION] = "no_renegotiation",
107#ifdef TLS13_AD_MISSING_EXTENSION
108 [TLS13_AD_MISSING_EXTENSION] = "missing_extension",
109#endif
110#ifdef TLS13_AD_CERTIFICATE_REQUIRED
111 [TLS13_AD_CERTIFICATE_REQUIRED] = "certificate_required",
112#endif
113#ifdef TLS1_AD_UNSUPPORTED_EXTENSION
114 [TLS1_AD_UNSUPPORTED_EXTENSION] = "unsupported_extension",
115#endif
116#ifdef TLS1_AD_CERTIFICATE_UNOBTAINABLE
117 [TLS1_AD_CERTIFICATE_UNOBTAINABLE] = "certificate_unobtainable",
118#endif
119#ifdef TLS1_AD_UNRECOGNIZED_NAME
120 [TLS1_AD_UNRECOGNIZED_NAME] = "unrecognised_name",
121#endif
122#ifdef TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE
123 [TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE] = "bad_certificate_status_response",
124#endif
125#ifdef TLS1_AD_BAD_CERTIFICATE_HASH_VALUE
126 [TLS1_AD_BAD_CERTIFICATE_HASH_VALUE] = "bad_certificate_hash_value",
127#endif
128#ifdef TLS1_AD_UNKNOWN_PSK_IDENTITY
129 [TLS1_AD_UNKNOWN_PSK_IDENTITY] = "unknown_psk_identity",
130#endif
131#ifdef TLS1_AD_NO_APPLICATION_PROTOCOL
132 [TLS1_AD_NO_APPLICATION_PROTOCOL] = "no_application_protocol",
133#endif
134};
135
136static char const *tls_handshake_type_str[] = {
137 [SSL3_MT_HELLO_REQUEST] = "hello_request",
138 [SSL3_MT_CLIENT_HELLO] = "client_hello",
139 [SSL3_MT_SERVER_HELLO] = "server_hello",
140#ifdef SSL3_MT_NEWSESSION_TICKET
141 [SSL3_MT_NEWSESSION_TICKET] = "new_session_ticket",
142#endif
143#ifdef SSL3_MT_END_OF_EARLY_DATA
144 [SSL3_MT_END_OF_EARLY_DATA] = "end_of_early_data",
145#endif
146#ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
147 [SSL3_MT_ENCRYPTED_EXTENSIONS] = "encrypted_extensions",
148#endif
149 [SSL3_MT_CERTIFICATE] = "certificate",
150 [SSL3_MT_SERVER_KEY_EXCHANGE] = "server_key_exchange",
151 [SSL3_MT_CERTIFICATE_REQUEST] = "certificate_request",
152 [SSL3_MT_SERVER_DONE] = "server_hello_done",
153 [SSL3_MT_CERTIFICATE_VERIFY] = "certificate_verify",
154 [SSL3_MT_CLIENT_KEY_EXCHANGE] = "client_key_exchange",
155 [SSL3_MT_FINISHED] = "finished",
156#ifdef SSL3_MT_CERTIFICATE_URL
157 [SSL3_MT_CERTIFICATE_URL] = "certificate_url",
158#endif
159#ifdef SSL3_MT_CERTIFICATE_STATUS
160 [SSL3_MT_CERTIFICATE_STATUS] = "certificate_status",
161#endif
162#ifdef SSL3_MT_SUPPLEMENTAL_DATA
163 [SSL3_MT_SUPPLEMENTAL_DATA] = "supplemental_data",
164#endif
165#ifdef SSL3_MT_KEY_UPDATE
166 [SSL3_MT_KEY_UPDATE] = "key_update",
167#endif
168#ifdef SSL3_MT_NEXT_PROTO
169 [SSL3_MT_NEXT_PROTO] = "next_proto",
170#endif
171#ifdef SSL3_MT_MESSAGE_HASH
172 [SSL3_MT_MESSAGE_HASH] = "message_hash",
173#endif
174#ifdef DTLS1_MT_HELLO_VERIFY_REQUEST
175 [DTLS1_MT_HELLO_VERIFY_REQUEST] = "hello_verify_request",
176#endif
177#ifdef SSL3_MT_CHANGE_CIPHER_SPEC
178 [SSL3_MT_CHANGE_CIPHER_SPEC] = "change_cipher_spec",
179#endif
180};
181
182/** Return the static private key password we have configured
183 *
184 * @param[out] buf Where to write the password to.
185 * @param[in] size The length of buf.
186 * @param[in] rwflag
187 * - 0 if password used for decryption.
188 * - 1 if password used for encryption.
189 * @param[in] u The static password.
190 * @return
191 * - 0 on error.
192 * - >0 on success (the length of the password).
193 */
194int fr_tls_session_password_cb(char *buf, int size, int rwflag UNUSED, void *u)
195{
196 size_t len;
197
198 /*
199 * We do this instead of not registering the callback
200 * to ensure OpenSSL doesn't try and read a password
201 * from stdin (causes server to block).
202 */
203 if (!u) {
204 ERROR("Private key encrypted but no private_key_password configured");
205 return 0;
206 }
207
208 len = strlcpy(buf, (char *)u, size);
209 if (len >= (size_t)size) {
210 ERROR("Password too long. Maximum length is %i bytes", size - 1);
211 return 0;
212 }
213
214 return (int)len;
215}
216
217#ifdef PSK_MAX_IDENTITY_LEN
218/** Verify the PSK identity contains no reserved chars
219 *
220 * @param identity to check.
221 * @return
222 * - true identity does not contain reserved chars.
223 * - false identity contains reserved chars.
224 */
225static bool session_psk_identity_is_safe(const char *identity)
226{
227 char c;
228
229 if (!identity) return true;
230
231 while ((c = *(identity++)) != '\0') {
232 if (isalpha((uint8_t) c) || isdigit((uint8_t) c) || isspace((uint8_t) c) ||
233 (c == '@') || (c == '-') || (c == '_') || (c == '.')) {
234 continue;
235 }
236
237 return false;
238 }
239
240 return true;
241}
242
243/** Determine the PSK to use for an outgoing connection
244 *
245 * @param[in] ssl session.
246 * @param[in] identity The identity of the PSK to search for.
247 * @param[out] psk Where to write the PSK we found (if any).
248 * @param[in] max_psk_len The length of the buffer provided for PSK.
249 * @return
250 * - 0 if no PSK matching identity was found.
251 * - >0 if a PSK matching identity was found (the length of bytes written to psk).
252 */
253unsigned int fr_tls_session_psk_client_cb(SSL *ssl, UNUSED char const *hint,
254 char *identity, unsigned int max_identity_len,
255 unsigned char *psk, unsigned int max_psk_len)
256{
257 unsigned int psk_len;
258 fr_tls_conf_t *conf;
259
260 conf = (fr_tls_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
261 if (!conf) return 0;
262
263 psk_len = talloc_array_length(conf->psk.key);
264 if (psk_len > max_psk_len) return 0;
265
266 strlcpy(identity, conf->psk.identity, max_identity_len);
267 memcpy(psk, conf->psk.key, psk_len);
268
269 return psk_len;
270}
271
272/** Forget the result of `load psk`, so that the next handshake starts with no pending call
273 *
274 * @param[in] tls_session The TLS session that the section ran for.
275 */
276static void tls_session_psk_reset(fr_tls_session_t *tls_session)
277{
278 TALLOC_FREE(tls_session->psk.key);
279 tls_session->psk.key_len = 0;
280 tls_session->psk.state = FR_TLS_PSK_INIT;
281}
282
283/** Determine the PSK to use for an incoming connection
284 *
285 * When the virtual server has a `load psk` section, the callback pauses
286 * the handshake. tls_session_async_handshake_cont() then pushes the
287 * section with fr_tls_session_psk_pending_push(). Once the section has
288 * finished, the callback returns the key that the section placed in
289 * `reply.TLS-PSK-Key`.
290 *
291 * @param[in] ssl session.
292 * @param[in] identity The identity of the PSK to search for.
293 * @param[out] psk Where to write the PSK we found (if any).
294 * @param[in] max_psk_len The length of the buffer provided for PSK.
295 * @return
296 * - 0 if no PSK matching identity was found.
297 * - >0 if a PSK matching identity was found (the length of bytes written to psk).
298 */
299unsigned int fr_tls_session_psk_server_cb(SSL *ssl, const char *identity,
300 unsigned char *psk, unsigned int max_psk_len)
301{
302 size_t psk_len = 0;
303 fr_tls_conf_t *conf;
305
306 if (!identity) return 0;
307
308 conf = (fr_tls_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
309 if (!conf) return 0;
310
311 /*
312 * TLS_SESSION_ID_MARKER indicates that the identity is a stateful ticket which we issued, so we
313 * return "no, it's not a configured PSK identity". OpenSSL then checks if the PSK is a session
314 * ticket.
315 *
316 * Since a session ticket is not an invalid identity, we don't log an error, and we don't add
317 * PSK-Identity-Invalid to the request.
318 */
319 if ((uint8_t) identity[0] == TLS_SESSION_ID_MARKER) return 0;
320
321 request = fr_tls_session_request(ssl);
322 if (request && conf->load_psk) {
323 fr_tls_session_t *tls_session = fr_tls_session(ssl);
324 fr_pair_t *vp;
325
326 /*
327 * The passed identity is weird. Deny it.
328 */
329 if (!session_psk_identity_is_safe(identity)) {
330 RWDEBUG("(TLS) Invalid characters in PSK identity %s", identity);
331 fr_tls_session_error_add(request, FR_ERROR_VALUE_PSK_IDENTITY_INVALID);
332 return 0;
333 }
334
335 /*
336 * The `TLS-PSK-Identity` pair stays in the request after the handshake,
337 * so that policies can read the identity. fr_tls_session_psk_pending_push()
338 * copies the pair into the `load psk` subrequest.
339 */
341 if (fr_pair_value_from_str(vp, identity, strlen(identity), NULL, true) < 0) {
342 RPWDEBUG2("Failed parsing TLS PSK Identity");
344 return 0;
345 }
346
347 /*
348 * OpenSSL runs the handshake, including the PSK callback, on a fibre whose
349 * stack OpenSSL sizes. The unlang interpreter never runs on that stack, so
350 * the section runs on the request's own stack:
351 *
352 * 1. The callback records that `load psk` needs to run, and pauses the
353 * handshake.
354 * 2. Control returns to tls_session_async_handshake_cont(), which pushes the
355 * section with fr_tls_session_psk_pending_push().
356 * 3. Once the section has finished, tls_session_async_handshake_cont() resumes
357 * the handshake.
358 * 4. Execution continues after the ASYNC_pause_job() call below.
359 *
360 * The `verify certificate` and session cache sections pause the handshake the
361 * same way.
362 */
363 if (!fr_cond_assert_msg(tls_session->can_pause,
364 "Unexpected call to %s. tls_session_async_handshake_cont must be in call stack",
365 __FUNCTION__)) return 0;
366
367 fr_assert(tls_session->psk.state == FR_TLS_PSK_INIT);
368 tls_session->psk.state = FR_TLS_PSK_REQUESTED;
369 TLS_PENDING_SET(tls_session, FR_TLS_PENDING_PSK);
370 tls_session->psk.max_psk_len = max_psk_len;
371
372 ASYNC_pause_job();
373
374 /*
375 * If the request was cancelled while the handshake was paused,
376 * the section may not have run.
377 */
379 tls_session_psk_reset(tls_session);
380 return 0;
381 }
382
383 switch (tls_session->psk.state) {
384 case FR_TLS_PSK_SUCCESS:
385 break;
386
387 case FR_TLS_PSK_FAILED:
388 tls_session_psk_reset(tls_session);
389 return 0;
390
391 case FR_TLS_PSK_INIT:
392 case FR_TLS_PSK_REQUESTED:
393 fr_assert_msg(0, "Handshake resumed with `load psk` in state %u",
394 tls_session->psk.state);
395 tls_session_psk_reset(tls_session);
396 return 0;
397 }
398
399 /*
400 * _tls_session_psk_load_resume() checked the key, so the
401 * callback only copies the key into the `psk` buffer that
402 * OpenSSL passed.
403 */
404 psk_len = tls_session->psk.key_len;
405 memcpy(psk, tls_session->psk.key, psk_len);
406 tls_session_psk_reset(tls_session);
407
408 return (unsigned int)psk_len;
409 }
410
411 if (!conf->psk.identity) {
412 DEBUG("Rejecting the client, no fixed psk.identity set");
413 return 0;
414 }
415
416 /*
417 * Compare the identity against the fixed `psk.identity`, then
418 * copy the fixed `psk.key` into the `psk` buffer that OpenSSL
419 * passed.
420 */
421 if (strcmp(identity, conf->psk.identity) != 0) {
422 fr_tls_log_error("Supplied PSK identity %s does not match configuration. Rejecting.",
423 identity);
424 fr_tls_session_error_add(request, FR_ERROR_VALUE_PSK_IDENTITY_UNKNOWN);
425 return 0;
426 }
427
428 psk_len = talloc_array_length(conf->psk.key);
429 if (psk_len > max_psk_len) return 0;
430
431 memcpy(psk, conf->psk.key, psk_len);
432
433 return (unsigned int)psk_len;
434}
435
436/** Process the result of `load psk`
437 *
438 * The function runs in the subrequest, once the section has finished.
439 * The interpreter frees the subrequest when the function returns, so the
440 * function copies the key out of the reply and into the session. The
441 * function logs every error, because the function runs on the request's
442 * own stack rather than on the OpenSSL fibre. fr_tls_session_psk_server_cb()
443 * then only copies the key into the `psk` buffer that OpenSSL passed.
444 *
445 * @param[in] request The subrequest that ran the section.
446 * @param[in] uctx The #fr_tls_session_t that the section ran for.
447 * @return UNLANG_ACTION_CALCULATE_RESULT
448 */
449static unlang_action_t _tls_session_psk_load_resume(request_t *request, void *uctx)
450{
451 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
452 fr_pair_t *vp;
453
454 fr_assert(tls_session->psk.state == FR_TLS_PSK_REQUESTED);
455
456 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_packet_type);
457 if (!vp || (vp->vp_uint32 != enum_tls_packet_type_success->vb_uint32)) {
458 RWDEBUG("(TLS) Failed loading the pre-shared key, `load psk` did not return success");
459
460 /*
461 * `notfound` says that the policy does not know the
462 * identity, and an unknown identity is the peer's error.
463 * Any other failure is the policy's error.
464 */
465 fr_tls_session_error_add(request->parent,
466 (vp && (vp->vp_uint32 == enum_tls_packet_type_notfound->vb_uint32)) ?
467 FR_ERROR_VALUE_PSK_IDENTITY_UNKNOWN :
468 FR_ERROR_VALUE_LOAD_PSK_FAILED);
469 failed:
470 tls_session->psk.state = FR_TLS_PSK_FAILED;
472 }
473
474 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_tls_psk_key);
475 if (!vp || (vp->vp_length == 0)) {
476 RWDEBUG("(TLS) `load psk` returned success, but reply.TLS-PSK-Key is missing or empty");
477 fr_tls_session_error_add(request->parent, FR_ERROR_VALUE_PSK_EMPTY);
478 goto failed;
479 }
480
481 if (vp->vp_length > tls_session->psk.max_psk_len) {
482 RWDEBUG("(TLS) Rejecting reply.TLS-PSK-Key of %zu bytes, OpenSSL accepts at most %u bytes", vp->vp_length,
483 tls_session->psk.max_psk_len);
484 fr_tls_session_error_add(request->parent, FR_ERROR_VALUE_PSK_TOO_LONG);
485 goto failed;
486 }
487
488 MEM(tls_session->psk.key = talloc_memdup(tls_session, vp->vp_octets, vp->vp_length));
489 tls_session->psk.key_len = vp->vp_length;
490 tls_session->psk.state = FR_TLS_PSK_SUCCESS;
491
492 RDEBUG2("(TLS) Loaded a %zu-byte pre-shared key", vp->vp_length);
493
495}
496
497/** Push a `load psk` call into the current request, using a subrequest
498 *
499 * tls_session_async_handshake_cont() calls the function once the
500 * handshake has paused, after the pushes for pending session cache
501 * sections and before the push for a pending `verify certificate`
502 * section.
503 *
504 * @param[in] request The current request.
505 * @param[in] tls_session The current TLS session.
506 * @return
507 * - UNLANG_ACTION_CALCULATE_RESULT on noop.
508 * - UNLANG_ACTION_PUSHED_CHILD on success.
509 * - UNLANG_ACTION_FAIL on failure.
510 */
511unlang_action_t fr_tls_session_psk_pending_push(request_t *request, fr_tls_session_t *tls_session)
512{
513 fr_tls_conf_t *conf = tls_session->conf;
514 request_t *child;
515 fr_pair_t *identity;
517
518 if (tls_session->psk.state != FR_TLS_PSK_REQUESTED) return UNLANG_ACTION_CALCULATE_RESULT;
519
520 fr_assert(conf->virtual_server);
521
522 /*
523 * fr_tls_session_psk_server_cb() added the `TLS-PSK-Identity` pair to
524 * the request before pausing the handshake.
525 */
526 identity = fr_pair_find_by_da(&request->request_pairs, NULL, attr_tls_psk_identity);
527 fr_assert(identity);
528
529 RDEBUG2("(TLS) Loading the pre-shared key for identity \"%pV\"", &identity->data);
530
531 MEM(child = tls_subrequest_alloc(request, enum_tls_packet_type_load_psk->vb_uint32,
532 &tls_session->session_id));
533
534 /*
535 * Add extra pairs to the subrequest
536 */
537 fr_tls_session_extra_pairs_copy_to_child(child, tls_session);
538
539 fr_pair_append(&child->request_pairs, fr_pair_copy(child->request_ctx, identity));
540
541 /*
542 * Push the call to the TLS virtual server into the child.
543 */
544 ua = fr_tls_call_push(child, _tls_session_psk_load_resume, conf, tls_session, false);
545 if (ua == UNLANG_ACTION_FAIL) {
546 REDEBUG("(TLS) Failed calling TLS virtual server");
547 talloc_free(child);
548 return UNLANG_ACTION_FAIL;
549 }
550
551 return ua;
552}
553#endif /* PSK_MAX_IDENTITY_LEN */
554
555/** Record a TLS alert in a pair list
556 *
557 * A TLS Alert says why the handshake ended, so we only keep the last one.
558 *
559 * A peer can send multiple alerts, and if we left earlier `Alert` in
560 * the list, the policies would be looking at the wrong one.
561 *
562 * When we receive a TLS Alert, it gets copied into the `request`
563 * list. When we send a TLS Alert, it gets copied into the `reply`
564 * list.
565 *
566 * We also update `session-state.Error` to describe the TLS Alert.
567 * See fr_tls_session_error_add().
568 *
569 * @param[in] request to log through. A NULL request is ignored,
570 * because several OpenSSL callbacks run without one.
571 * @param[in] list_ctx the pair which holds the list, either
572 * `request->request_ctx` or `request->reply_ctx`.
573 * @param[in] prefix names the list in the log line.
574 * @param[in] level of the alert, warning or fatal.
575 * @param[in] description of the alert.
576 */
577static void tls_session_alert_pair_add(request_t *request, fr_pair_t *list_ctx, char const *prefix,
578 uint8_t level, uint8_t description)
579{
580 fr_pair_t *alert, *vp;
581
582 if (!request) return;
583
584 fr_pair_delete_by_da(&list_ctx->vp_group, attr_tls_alert);
585
586 MEM(fr_pair_append_by_da(list_ctx, &alert, &list_ctx->vp_group, attr_tls_alert) >= 0);
587
588 MEM(fr_pair_append_by_da(alert, &vp, &alert->vp_group, attr_tls_alert_level) >= 0);
589 vp->vp_uint8 = level;
590
591 MEM(fr_pair_append_by_da(alert, &vp, &alert->vp_group, attr_tls_alert_description) >= 0);
592 vp->vp_uint8 = description;
593
594 RDEBUG2("(TLS) Adding %s%pP", prefix, alert);
595}
596
597
598DIAG_OFF_OPTIONAL(used-but-marked-unused) /* Fix spurious warnings for sk_ macros */
599/** Record session state changes
600 *
601 * Called by OpenSSL whenever the session state changes, an alert is received or an error occurs.
602 *
603 * @param[in] ssl session.
604 * @param[in] where Which context the callback is being called in.
605 * See https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_info_callback.html
606 * for additional info.
607 * @param[in] ret 0 if an error occurred, or the alert type if an alert was received.
608 */
609void fr_tls_session_info_cb(SSL const *ssl, int where, int ret)
610{
611 char const *role, *state;
612 request_t *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
613
614 /*
615 * OpenSSL runs the info callback from inside a handshake round,
616 * and the library binds the request across a round.
617 */
618 fr_assert(request != NULL);
619
620 if ((where & ~SSL_ST_MASK) & SSL_ST_CONNECT) {
621 role = "Client ";
622 } else if (((where & ~SSL_ST_MASK)) & SSL_ST_ACCEPT) {
623 role = "Server ";
624 } else {
625 role = "";
626 }
627
628 state = SSL_state_string_long(ssl);
629 state = state ? state : "<INVALID>";
630
631 if ((where & SSL_CB_LOOP) || (where & SSL_CB_HANDSHAKE_START) || (where & SSL_CB_HANDSHAKE_DONE)) {
632 if (RDEBUG_ENABLED3) {
633 char const *abbrv = SSL_state_string(ssl);
634 size_t len;
635
636 /*
637 * Trim crappy OpenSSL state strings...
638 */
639 len = strlen(abbrv);
640 if ((len > 1) && (abbrv[len - 1] == ' ')) len--;
641
642 RDEBUG3("(TLS) Handshake state [%.*s] - %s%s", (int)len, abbrv, role, state);
643
644#ifdef OPENSSL_NO_SSL_TRACE
645 {
646 STACK_OF(SSL_CIPHER) *server_ciphers;
647 STACK_OF(SSL_CIPHER) *client_ciphers;
648
649 /*
650 * After a ClientHello, list all the proposed ciphers
651 * from the client.
652 *
653 * Only do this if we don't have SSL_trace() as
654 * SSL_trace() prints this information and we don't
655 * want to duplicate it.
656 */
657 if (SSL_get_state(ssl) == TLS_ST_SR_CLNT_HELLO &&
658 (client_ciphers = SSL_get_client_ciphers(ssl))) {
659 int i;
660 int num_ciphers;
661 const SSL_CIPHER *this_cipher;
662
663 server_ciphers = SSL_get_ciphers(ssl);
664 /*
665 * These are printed on startup, so not usually
666 * required.
667 */
668 RDEBUG4("(TLS) Our preferred ciphers (by priority)");
669 if (RDEBUG_ENABLED4) {
670 RINDENT();
671 num_ciphers = sk_SSL_CIPHER_num(server_ciphers);
672 for (i = 0; i < num_ciphers; i++) {
673 this_cipher = sk_SSL_CIPHER_value(server_ciphers, i);
674 RDEBUG4("(TLS) [%i] %s", i, SSL_CIPHER_get_name(this_cipher));
675 }
676 REXDENT();
677 }
678
679 /*
680 * Print information about the client's
681 * handshake message.
682 */
683 if (RDEBUG_ENABLED3) {
684 RDEBUG3("(TLS) Client's preferred ciphers (by priority)");
685 RINDENT();
686 num_ciphers = sk_SSL_CIPHER_num(client_ciphers);
687 for (i = 0; i < num_ciphers; i++) {
688 this_cipher = sk_SSL_CIPHER_value(client_ciphers, i);
689 RDEBUG3("(TLS) [%i] %s", i, SSL_CIPHER_get_name(this_cipher));
690 }
691 REXDENT();
692 }
693 }
694 }
695# endif
696 } else {
697 RDEBUG2("(TLS) Handshake state - %s%s (%u)", role, state, SSL_get_state(ssl));
698 }
699 return;
700 }
701
702 if (where & SSL_CB_ALERT) {
703 if ((ret & 0xff) == SSL_AD_CLOSE_NOTIFY) return;
704
705 /*
706 * We got an alert...
707 */
708 if (where & SSL_CB_READ) {
709 REDEBUG("(TLS) Client sent %s TLS alert (%i) - %s", SSL_alert_type_string_long(ret),
710 ret & 0xff, SSL_alert_desc_string_long(ret));
711
712 /*
713 * Offer helpful advice... Should be expanded.
714 */
715 switch (ret & 0xff) {
716 case TLS1_AD_UNKNOWN_CA:
717 REDEBUG("(TLS) Verify the client has a copy of the server's Certificate "
718 "Authority (CA) installed, and trusts that CA");
719 break;
720
721 default:
722 break;
723 }
724
725 /*
726 * The alert level is packed into the high octet of `ret`. The alert
727 * description is packed into the low octet.
728 *
729 * A peer can send alerts are multiple points in the handshake, so
730 * earlier alerts are removed before the latest one is added.
731 *
732 * We could just find an earlier alert and update its members, but that's
733 * more code.
734 */
735 tls_session_alert_pair_add(request, request->request_ctx, "",
736 (ret >> 8) & 0xff, ret & 0xff);
737 fr_tls_session_error_add(request, FR_ERROR_VALUE_RECEIVED_ALERT);
738 /*
739 * We're sending the client an alert.
740 */
741 } else {
742 REDEBUG("(TLS) Sending client %s TLS alert (%i) - %s",
743 SSL_alert_type_string_long(ret), ret & 0xff, SSL_alert_desc_string_long(ret));
744
745 /*
746 * Offer helpful advice... Should be expanded.
747 */
748 switch (ret & 0xff) {
749 case TLS1_AD_PROTOCOL_VERSION:
750 REDEBUG("(TLS) Client requested a TLS protocol version that is not "
751 "enabled or not supported. Upgrade FreeRADIUS + OpenSSL to their latest "
752 "versions and/or adjust 'tls_max_version'/'tls_min_version' if you want "
753 "authentication to succeed");
754 break;
755
756 default:
757 break;
758 }
759
760 /*
761 * A sent alert goes in the reply list, where a received one
762 * goes in the request list. `ret` packs the two octets the
763 * same way in both directions.
764 */
765 tls_session_alert_pair_add(request, request->reply_ctx, "reply.",
766 (ret >> 8) & 0xff, ret & 0xff);
767 fr_tls_session_error_add(request, FR_ERROR_VALUE_SENT_ALERT);
768 }
769 return;
770 }
771
772 if (where & SSL_CB_EXIT) {
773 if (ret == 0) {
774 REDEBUG("(TLS) Handshake exit state %s%s", role, state);
775 return;
776 }
777
778 if (ret < 0) {
779 if (SSL_want_read(ssl)) {
780 RDEBUG2("(TLS) Need more data from client"); /* State same as previous call, don't print */
781 return;
782 }
783 REDEBUG("(TLS) Handshake exit state %s%s", role, state);
784 }
785 }
786}
787DIAG_ON_OPTIONAL(used-but-marked-unused)
788
789/** Print a message to the request or global log detailing handshake state
790 *
791 * @param[in] request The current #request_t.
792 * @param[in] tls_session The current TLS session.
793 */
794static void session_msg_log(request_t *request, fr_tls_session_t *tls_session, uint8_t const *data, size_t data_len)
795{
796 char const *version, *content_type;
797 char const *str_details1 = NULL;
798 char const *str_details2 = NULL;
799 char unknown_version[32];
800 char unknown_content_type[32];
801 char unknown_alert_level[32];
802 char unknown_alert_description[32];
803 char unknown_handshake_type[32];
804
805 /*
806 * Both callers hold a request: fr_tls_session_msg_cb() takes it
807 * off the SSL *, and fr_tls_session_alert_send() is handed one.
808 */
809 fr_assert(request != NULL);
810
811 /*
812 * Don't print this out in the normal course of
813 * operations.
814 */
815 if (!RDEBUG_ENABLED2) return;
816
817 if (((size_t)tls_session->info.version >= NUM_ELEMENTS(tls_version_str)) ||
818 !tls_version_str[tls_session->info.version]) {
819 snprintf(unknown_version, sizeof(unknown_version), "unknown_tls_version_0x%04x",
820 (unsigned int) tls_session->info.version);
821 version = unknown_version;
822 } else {
823 version = tls_version_str[tls_session->info.version];
824 }
825
826 /*
827 * TLS 1.0, 1.1, 1.2 content types are the same as SSLv3
828 */
829 if (((size_t)tls_session->info.content_type >= NUM_ELEMENTS(tls_content_type_str)) ||
830 !tls_content_type_str[tls_session->info.content_type]) {
831 snprintf(unknown_content_type, sizeof(unknown_content_type),
832 "unknown_content_type_0x%04x", (unsigned int) tls_session->info.content_type);
833 content_type = unknown_content_type;
834 } else {
835 content_type = tls_content_type_str[tls_session->info.content_type];
836 }
837
838 if (tls_session->info.content_type == SSL3_RT_ALERT) {
839 if (tls_session->info.record_len == 2) {
840 switch (tls_session->info.alert_level) {
841 case SSL3_AL_WARNING:
842 str_details1 = "warning";
843 break;
844 case SSL3_AL_FATAL:
845 str_details1 = "fatal";
846 break;
847
848 default:
849 snprintf(unknown_alert_level, sizeof(unknown_alert_level),
850 "unknown_alert_level_0x%04x", tls_session->info.alert_level);
851 str_details1 = unknown_alert_level;
852 break;
853 }
854
855 if (((size_t)tls_session->info.alert_description >= NUM_ELEMENTS(tls_alert_description_str)) ||
856 !tls_alert_description_str[tls_session->info.alert_description]) {
857 snprintf(unknown_alert_description, sizeof(unknown_alert_description),
858 "unknown_alert_0x%04x", tls_session->info.alert_description);
859 str_details2 = unknown_alert_description;
860 } else {
861 str_details2 = tls_alert_description_str[tls_session->info.alert_description];
862 }
863 } else {
864 str_details1 = "unknown_alert_level";
865 str_details2 = "unknown_alert";
866 }
867 }
868
869 if ((size_t)tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
870 if (tls_session->info.record_len > 0) {
871 /*
872 * Range guard not needed due to size of array
873 * and underlying type.
874 */
875 if (!tls_handshake_type_str[tls_session->info.handshake_type]) {
876 snprintf(unknown_handshake_type, sizeof(unknown_handshake_type),
877 "unknown_handshake_type_0x%02x", tls_session->info.handshake_type);
878 str_details1 = unknown_handshake_type;
879 } else {
880 str_details1 = tls_handshake_type_str[tls_session->info.handshake_type];
881 }
882 }
883 }
884
885 snprintf(tls_session->info.info_description, sizeof(tls_session->info.info_description),
886 "%s %s, %s[length %lu]%s%s%s%s",
887 tls_session->info.origin ? ">>> send" : "<<< recv",
888 version,
889 content_type,
890 (unsigned long)tls_session->info.record_len,
891 str_details1 ? ", " : "",
892 str_details1 ? str_details1 : "",
893 str_details2 ? ", " : "",
894 str_details2 ? str_details2 : "");
895
896 /*
897 * Print out information about the record and print the
898 * data at higher debug levels.
899 */
900 if (RDEBUG_ENABLED4) {
901 RHEXDUMP4(data, data_len, "(TLS) %s", tls_session->info.info_description);
902 } else {
903 RDEBUG2("(TLS) %s", tls_session->info.info_description);
904 }
905}
906
907/** Record the progression of the TLS handshake
908 *
909 * This callback is called by OpenSSL whenever a protocol message relating to a handshake is sent
910 * or received.
911 *
912 * This function copies state information from the various arguments into the state->info
913 * structure of the #fr_tls_session_t, to allow us to track the progression of the handshake.
914 *
915 * @param[in] write_p
916 * - 0 when a message has been received.
917 * - 1 when a message has been sent.
918 *
919 * @param[in] msg_version The TLS version negotiated, should be one of:
920 * - TLS1_VERSION
921 * - TLS1_1_VERSION
922 * - TLS1_2_VERSION
923 * - TLS1_3_VERSION
924 *
925 * @param[in] content_type One of the contentType values defined for TLS:
926 * - SSL3_RT_CHANGE_CIPHER_SPEC (20)
927 * - SSL3_RT_ALERT (21)
928 * - SSL3_RT_HANDSHAKE (22)
929 * - TLS1_RT_HEARTBEAT (24)
930 *
931 * @param[in] inbuf The raw protocol message.
932 * @param[in] len Length of the raw protocol message.
933 * @param[in] ssl The SSL session.
934 * @param[in] arg The #fr_tls_session_t holding the SSL session.
935 */
936void fr_tls_session_msg_cb(int write_p, int msg_version, int content_type,
937 void const *inbuf, size_t len,
938 SSL *ssl, void *arg)
939{
940 uint8_t const *buf = inbuf;
941 fr_tls_session_t *tls_session = talloc_get_type_abort(arg, fr_tls_session_t);
942 request_t *request = fr_tls_session_request(tls_session->ssl);
943
944 /*
945 * OpenSSL runs the message callback for every record it reads
946 * or writes, and every one of those happens while the library
947 * has the request bound. _fr_dtls_timer_expired() binds across
948 * DTLSv1_handle_timeout() for exactly this reason.
949 */
950 fr_assert(request != NULL);
951
952 /*
953 * Mostly to check for memory corruption...
954 */
955 if (!fr_cond_assert(tls_session->ssl == ssl)) {
956 REDEBUG("(TLS) fr_tls_session_t and ssl arg do not match in fr_tls_session_msg_cb");
957 fr_tls_session_error_alert(request, tls_session,
958 FR_ERROR_VALUE_SESSION_MISMATCH, SSL_AD_INTERNAL_ERROR);
959 tls_session->invalid = true;
960 return;
961 }
962
963 /*
964 * As per https://tools.ietf.org/html/rfc7568
965 *
966 * We explicitly disable SSLv2/v3, hence the asserts.
967 */
968#ifdef SSL2_VERSION
969 if (!fr_cond_assert(msg_version != SSL2_VERSION)) {
970 REDEBUG("(TLS) Invalid version (SSLv2) in handshake");
971 fr_tls_session_error_alert(request, tls_session,
972 FR_ERROR_VALUE_INVALID_VERSION_SSLV2, SSL_AD_PROTOCOL_VERSION);
973 tls_session->invalid = true;
974 return;
975 }
976#endif
977
978#ifdef SSL3_VERSION
979 if (!fr_cond_assert(msg_version != SSL3_VERSION)) {
980 REDEBUG("(TLS) Invalid version (SSLv3) in handshake");
981 fr_tls_session_error_alert(request, tls_session,
982 FR_ERROR_VALUE_INVALID_VERSION_SSLV3, SSL_AD_PROTOCOL_VERSION);
983 tls_session->invalid = true;
984 return;
985 }
986#endif
987
988 /*
989 * OpenSSL >= 1.0.2 calls this function with 'pseudo'
990 * content types. Which breaks our tracking of
991 * the SSL Session state.
992 */
993 if ((msg_version == 0) && (content_type > UINT8_MAX)) {
994 REDEBUG4("(TLS) Ignoring fr_tls_session_msg_cb call with pseudo content type %i, version %i",
995 content_type, msg_version);
996 return;
997 }
998
999 if ((write_p != 0) && (write_p != 1)) {
1000 REDEBUG4("(TLS) Ignoring fr_tls_session_msg_cb call with invalid write_p %d", write_p);
1001 return;
1002 }
1003
1004 /*
1005 * 0 - received (from peer)
1006 * 1 - sending (to peer)
1007 */
1008 tls_session->info.origin = write_p;
1009 tls_session->info.content_type = content_type;
1010 tls_session->info.record_len = len;
1011 tls_session->info.version = msg_version;
1012 tls_session->info.initialized = true;
1013
1014 switch (content_type) {
1015 case SSL3_RT_ALERT:
1016 if (len < 2) {
1017 invalid_alert:
1018 REDEBUG("(TLS) Invalid TLS Alert. Closing connection");
1019 fr_tls_session_error_alert(request, tls_session,
1020 FR_ERROR_VALUE_INVALID_RECORD_LENGTH, SSL_AD_DECODE_ERROR);
1021 tls_session->invalid = true;
1022 return;
1023 }
1024
1025 tls_session->info.alert_level = buf[0];
1026 tls_session->info.alert_description = buf[1];
1027 tls_session->info.handshake_type = 0x00;
1028 break;
1029
1030 case SSL3_RT_HANDSHAKE:
1031 if (!len) goto invalid_alert;
1032
1033 tls_session->info.handshake_type = buf[0];
1034 tls_session->info.alert_level = 0x00;
1035 tls_session->info.alert_description = 0x00;
1036 break;
1037
1038#ifdef SSL3_RT_HEARTBEAT
1039 case TLS1_RT_HEARTBEAT:
1040 uint8_t *p = buf;
1041
1042 if ((len >= 3) && (p[0] == 1)) {
1043 size_t payload_len;
1044
1045 payload_len = fr_nbo_to_uint16(p + 1);
1046 if ((payload_len + 3) > len) {
1047 tls_session->invalid = true;
1048 REDEBUG("(TLS) OpenSSL Heartbeat attack detected. Closing connection");
1049 fr_tls_session_error_alert(request, tls_session,
1050 FR_ERROR_VALUE_HEARTBEAT_OVERFLOW, SSL_AD_DECODE_ERROR);
1051 return;
1052 }
1053 }
1054 break;
1055#endif
1056 default:
1057 break;
1058 }
1059
1060 /*
1061 * Manually track when records are encrypted. Once records are encrypted, we can't manually
1062 * create a TLS alert. OpenSSL doesn't have an API to send alerts. And it doesn't have an API
1063 * to tell us when the records are encrypted.
1064 */
1065 switch (content_type) {
1066 /*
1067 * Everything after ChangeCipherSpec is encrypted.
1068 */
1069 case SSL3_RT_CHANGE_CIPHER_SPEC:
1070 if (write_p != TLS_INFO_ORIGIN_RECORD_SENT) break;
1071 if (tls_session->write_encrypted) break;
1072
1073 tls_session->write_encrypted = true;
1074 RDEBUG3("(TLS) The records we write are encrypted, from the ChangeCipherSpec onwards");
1075 break;
1076
1077 /*
1078 * For TLS 1.3, everything after ServerHello is encrypted. After ServerHello, SSL_version()
1079 * finally returns the correct TLS version number which was negotiated. Before ServerHello,
1080 * SSL_version() returns the highest allowed TLS version.
1081 */
1082 case SSL3_RT_HANDSHAKE:
1083 if (tls_session->info.handshake_type != SSL3_MT_SERVER_HELLO) break;
1084 if (SSL_version(ssl) < TLS1_3_VERSION) break;
1085
1086 /*
1087 * We allow one session ticket, which is fine for TLS 1.2. The tickets are sent in the
1088 * header. For TLS 1.3 and stateful session tickets, the server also sends the ticket
1089 * immediately. For EAP, the `store session` code is delayed until after the inner
1090 * methods succeed. So it doesn't matter if the peer has a ticket.
1091 */
1092 if (tls_session->conf->delayed_tickets && (tls_session->conf->cache.mode & FR_TLS_TICKET_STATELESS) &&
1093 SSL_is_server(ssl)) {
1094 RDEBUG3("(TLS) TLS 1.3 session ticket is delayed until inner tunnel indicates success");
1095 SSL_set_num_tickets(ssl, 0);
1096 }
1097
1098 if (tls_session->write_encrypted) break;
1099
1100 tls_session->write_encrypted = true;
1101 RDEBUG3("(TLS) The records we write are encrypted, from the ServerHello onwards");
1102 break;
1103
1104 default:
1105 break;
1106 }
1107
1108 session_msg_log(request, tls_session, (uint8_t const *)inbuf, len);
1109
1110#ifndef OPENSSL_NO_SSL_TRACE
1111 if (RDEBUG_ENABLED3) {
1112 SSL_trace(tls_session->info.origin,
1113 tls_session->info.version,
1114 tls_session->info.content_type,
1115 inbuf, len,
1116 ssl,
1117 request ?
1118 fr_tls_request_log_bio(request, L_DBG, L_DBG_LVL_3) :
1119 fr_tls_global_log_bio(L_DBG, L_DBG_LVL_3));
1120 }
1121#endif
1122}
1123
1124/*
1125 * By setting the environment variable SSLKEYLOGFILE to a filename keying
1126 * material will be exported that you may use with Wireshark to decode any
1127 * TLS flows. Please see the following for more details:
1128 *
1129 * https://gitlab.com/wireshark/wireshark/-/wikis/TLS#tls-decryption
1130 *
1131 * An example logging session is (you should delete the file on each run):
1132 *
1133 * rm -f /tmp/sslkey.log; env SSLKEYLOGFILE=/tmp/sslkey.log freeradius -X | tee /tmp/debug
1134 *
1135 * Note that we rely on the OS to check file permissions. If the
1136 * caller can run radiusd, then they can only write to files which
1137 * they own. If radiusd is running as root, then only root can
1138 * change the environment variables for radiusd.
1139 */
1140void fr_tls_session_keylog_cb(const SSL *ssl, const char *line)
1141{
1142 int fd;
1143 size_t len;
1144 const char *filename;
1145 char buffer[64 + 2*SSL3_RANDOM_SIZE + 2*SSL_MAX_MASTER_KEY_LENGTH];
1146
1147 /*
1148 * Prefer the environment variable definition to the
1149 * configuration file. This allows for "one-shot"
1150 * dumping of EAP keys when you know you're not using
1151 * RadSec, and you don't want to edit the configuration.
1152 */
1153 filename = getenv("SSLKEYLOGFILE");
1154 if (!filename) {
1155 fr_tls_conf_t *conf;
1156
1157 conf = (fr_tls_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1158 if (!conf || !conf->keylog_file || !*conf->keylog_file) return;
1159
1160 filename = conf->keylog_file;
1161 }
1162
1163 /*
1164 * We write all of the data at once. This is *generally*
1165 * atomic on most systems.
1166 */
1167 len = strlen(line);
1168 if ((len + 1) > sizeof(buffer)) {
1169 DEBUG("SSLKEYLOGFILE buffer not large enough, max %lu, required %lu", sizeof(buffer), len + 1);
1170 return;
1171 }
1172
1173 /*
1174 * Add a \n, which means that in order to write() the
1175 * buffer AND the trailing \n, we have to place both
1176 * strings into the same buffer.
1177 */
1178 memcpy(buffer, line, len);
1179 buffer[len] = '\n';
1180
1181 fd = open(filename, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
1182 if (fd < 0) {
1183 DEBUG("Failed to open file %s: %s", filename, strerror(errno));
1184 return;
1185 }
1186
1187 /*
1188 * This should work in most situations.
1189 */
1190 if (write(fd, buffer, len + 1) < 0) {
1191 DEBUG("Failed to write to file %s: %s", filename, strerror(errno));
1192 }
1193
1194 close(fd);
1195}
1196
1197/** Check if all TLS initialization has finished.
1198 *
1199 * SSL_is_init_finished() tells us if the TLS handshake has finished,
1200 * which is enough for TLS 1.2, or TLS 1.3 without session tickets, or
1201 * TLS 1.3 with stateful session tickets.
1202 *
1203 * For TLS 1.3 with stateless session tickets, the ticket is sent
1204 * after the handshake has completed. The application gets to
1205 * send/recv its application data only after the handshake has
1206 * finished, the stateless session ticket has been received, and after
1207 * the `load session` has been run.
1208 *
1209 * Callers outside this library MUST use this function rather than
1210 * SSL_is_init_finished().
1211 *
1212 * @param[in] tls_session to check.
1213 * @return
1214 * - true if every part of the setup has finished.
1215 * - false if OpenSSL is still handshaking, or a `load session` which
1216 * the caller has to wait for has not run yet.
1217 */
1218bool fr_tls_session_is_init_finished(fr_tls_session_t *tls_session)
1219{
1220 fr_tls_conf_t *conf;
1221
1222 if (!SSL_is_init_finished(tls_session->ssl)) return false;
1223
1224 /*
1225 * TLS 1.3 servers send the session ticket (stateless or stateful) after the handshake has
1226 * finished. That adds a step after the TLS handshake is done. If we're not doing TLS 1.3, or
1227 * we're not using tickets, then we're done all negotiation, and application data can flow.
1228 */
1229 if (tls_session->info.version != TLS1_3_VERSION) return true;
1230
1231 if (!tls_session->cache) return true;
1232
1233 /*
1234 * If we're not a server, then we're a client, and we need to receive a ticket. For TLS 1.3, the
1235 * TLS handshake is finished, and then we might fet a ticket (stateless or stateful).
1236 *
1237 * We can either wait for a ticket (with timeout), or notice that receiption of application data
1238 * means that the ticket was sent (or not).
1239 */
1240 if (!SSL_is_server(tls_session->ssl)) {
1241 return tls_session->session_ticket_received || tls_session->seen_application_data;
1242 }
1243
1244 /*
1245 * A server which keeps its sessions in a cache has no
1246 * `load session` to wait for after the handshake.
1247 */
1248 conf = tls_session->conf;
1249 if (!(conf->cache.mode & FR_TLS_TICKET_STATELESS)) return true;
1250
1251 /*
1252 * Something has requested `load session`, but it hasn't
1253 * yet been run. Once that section completes, its state
1254 * returns to INIT. A session which never sends a ticket
1255 * is therefore also marked as finished.
1256 */
1257 return (tls_session->cache->load.state != FR_TLS_TICKET_STATEFUL_REQUESTED);
1258}
1259
1260/** Decrypt application data
1261 *
1262 * @note Handshake must have completed before this function may be called.
1263 *
1264 * Feed data from dirty_in to OpenSSL, and read the clean data into clean_out.
1265 *
1266 * @param[in] request The current #request_t.
1267 * @param[in] tls_session The current TLS session.
1268 * @return
1269 * - -1 on error.
1270 * - 1 if more fragments are required to fully reassemble the record for decryption.
1271 * - 0 if we decrypted a complete record.
1272 */
1273int fr_tls_session_recv(request_t *request, fr_tls_session_t *tls_session)
1274{
1275 int ret;
1276
1277 if (!tls_session->seen_application_data) {
1278 if (!SSL_is_init_finished(tls_session->ssl)) {
1279 REDEBUG("(TLS) Attempted to read application data before handshake completed");
1280 fr_tls_session_error_add(request, FR_ERROR_VALUE_APPLICATION_DATA_TOO_EARLY);
1281 return -1;
1282 }
1283
1284 /*
1285 * The handshake is over and we are about to move application
1286 * data, so we are past the point where a session ticket is
1287 * wanted. tls_ticket_stateful_store_cb() refuses any which arrive from
1288 * here on.
1289 */
1290 tls_session->seen_application_data = true;
1291 }
1292
1293 fr_tls_session_request_bind(tls_session->ssl, request);
1294
1295 /*
1296 * Nothing is copied here. The caller filled dirty_in, which
1297 * is into_ssl's producer cursor, so OpenSSL can already see
1298 * the record, and the BIO read callback reclaims the space as
1299 * OpenSSL consumes it.
1300 *
1301 * Init the clean_out buffer to store the decrypted data.
1302 */
1303 fr_tls_record_init(&tls_session->clean_out);
1304
1305 /*
1306 * Prevent spurious errors on the thread local error
1307 * stack causing SSL_get_error() to return SSL_ERROR_SSL
1308 * instead of what of the SSL_ERROR_WANT_* values.
1309 */
1310 ERR_clear_error();
1311
1312 /*
1313 * Read (and decrypt) the tunneled data from the
1314 * SSL session, and put it into the decrypted
1315 * data buffer.
1316 */
1317 ret = SSL_read(tls_session->ssl, fr_dbuff_current(&tls_session->clean_out),
1318 (int)fr_dbuff_remaining(&tls_session->clean_out));
1319 if (ret < 0) {
1320 int code;
1321
1322 code = SSL_get_error(tls_session->ssl, ret);
1323 switch (code) {
1324 case SSL_ERROR_WANT_READ:
1325 RWDEBUG("(TLS) Peer indicated record was complete, but OpenSSL returned SSL_WANT_READ. "
1326 "Attempting to continue");
1327 ret = 1;
1328 goto finish;
1329
1330 case SSL_ERROR_WANT_WRITE:
1331 REDEBUG("(TLS) Error in fragmentation logic: SSL_WANT_WRITE");
1332 error:
1333 ret = -1;
1334 goto finish;
1335
1336 case SSL_ERROR_NONE:
1337 RDEBUG2("(TLS) No application data received. Assuming handshake is continuing...");
1338 ret = 0;
1339 break;
1340
1341 default:
1342 REDEBUG("(TLS) Error in fragmentation logic");
1343 fr_tls_log_io_error(request, code, "SSL_read (%s)", __FUNCTION__);
1344 goto error;
1345 }
1346 }
1347
1348 /*
1349 * Passed all checks, successfully decrypted data
1350 */
1351 fr_dbuff_advance(&tls_session->clean_out, (size_t) ret);
1352 ret = 0;
1353
1354 if (RDEBUG_ENABLED3) {
1355 RHEXDUMP3(fr_dbuff_start(&tls_session->clean_out), fr_dbuff_used(&tls_session->clean_out),
1356 "(TLS) Decrypted TLS application data (%zu bytes)", fr_dbuff_used(&tls_session->clean_out));
1357 } else {
1358 RDEBUG2("(TLS) Decrypted TLS application data (%zu bytes)", fr_dbuff_used(&tls_session->clean_out));
1359 }
1360finish:
1361 fr_tls_session_request_unbind(tls_session->ssl);
1362
1363 return ret;
1364}
1365
1366/** Encrypt application data
1367 *
1368 * @note Handshake must have completed before this function may be called.
1369 *
1370 * Take cleartext data from clean_in, and feed it to OpenSSL, reading
1371 * the encrypted data into dirty_out.
1372 *
1373 * @param[in] request The current request.
1374 * @param[in] tls_session The current TLS session.
1375 * @return
1376 * - -1 on failure.
1377 * - 0 on success.
1378 */
1379int fr_tls_session_send(request_t *request, fr_tls_session_t *tls_session)
1380{
1381 int ret = 0;
1382
1383 if (!tls_session->seen_application_data) {
1384 if (!SSL_is_init_finished(tls_session->ssl)) {
1385 REDEBUG("(TLS) Attempted to write application data before handshake completed");
1386 fr_tls_session_error_add(request, FR_ERROR_VALUE_APPLICATION_DATA_TOO_EARLY);
1387 return -1;
1388 }
1389
1390 tls_session->seen_application_data = true;
1391 }
1392
1393 fr_tls_session_request_bind(tls_session->ssl, request);
1394
1395 /*
1396 * If there's un-encrypted data in 'clean_in', then write
1397 * that data to the SSL session, and then call the BIO function
1398 * to get that encrypted data from the SSL session, into
1399 * a buffer which we can then package into an EAP packet.
1400 *
1401 * Based on Server's logic this clean_in is expected to
1402 * contain the data to send to the client.
1403 */
1404 if (fr_dbuff_used(&tls_session->clean_in) > 0) {
1405 size_t used = fr_dbuff_used(&tls_session->clean_in);
1406
1407 /*
1408 * Ensure spurious errors aren't printed
1409 */
1410 ERR_clear_error();
1411
1412 if (RDEBUG_ENABLED3) {
1413 RHEXDUMP3(fr_dbuff_start(&tls_session->clean_in), used,
1414 "(TLS) TLS application data to encrypt (%zu bytes)", used);
1415 } else {
1416 RDEBUG2("(TLS) TLS application data to encrypt (%zu bytes)", used);
1417 }
1418
1419 ret = SSL_write(tls_session->ssl, fr_dbuff_start(&tls_session->clean_in), (int)used);
1420 if (ret < 0) {
1421 /*
1422 * ret<0 means that we have a real error.
1423 *
1424 * ret=0 means the "error" is SSL_WANT_READ, SSL_WANT_WRITE, etc.
1425 */
1426 ret = fr_tls_log_io_error(request, SSL_get_error(tls_session->ssl, ret),
1427 "SSL_write (%s)", __FUNCTION__);
1428 goto finish;
1429 }
1430
1431 /*
1432 * SSL_MODE_ENABLE_PARTIAL_WRITE is not set, so SSL_write()
1433 * either takes everything or fails. The whole buffer is
1434 * therefore consumed.
1435 */
1436 fr_assert((size_t) ret == used);
1437 fr_tls_record_init(&tls_session->clean_in);
1438
1439 /*
1440 * SSL_write() passes the encrypted record in
1441 * dirty_in to the BIO callback, which put the
1442 * output data into from_ssl. We're therefore
1443 * done here.
1444 */
1445 ret = 0;
1446 }
1447
1448finish:
1449 fr_tls_session_request_unbind(tls_session->ssl);
1450
1451 return ret;
1452}
1453
1454/** Create a TLS 1.3 session ticket after the handshake, and queue the ticket for the peer
1455 *
1456 * SSL_new_session_ticket() queues a ticket, and we need to call SSL_do_handshake() to put the ticket into
1457 * dirty_out for writing.
1458 *
1459 * The ticket creation callback runs inside SSL_do_handshake(). It cannot pause the request, so the caller
1460 * MUST have run `encode session` already, and set tls_session->app_data_ready.
1461 *
1462 * @param[in] request bound to the session for the duration of the call.
1463 * @param[in] tls_session to create a ticket for. Must be a server, and TLS 1.3.
1464 * @return
1465 * - 0 on success. tls_session->session_ticket_created says if OpenSSL made a ticket.
1466 * - -1 on failure.
1467 */
1468int fr_tls_session_ticket_write(request_t *request, fr_tls_session_t *tls_session)
1469{
1470 int ret;
1471
1472 fr_tls_session_request_bind(tls_session->ssl, request);
1473
1474 ERR_clear_error();
1475
1476 tls_session->session_ticket_created = false;
1477
1478 if (SSL_new_session_ticket(tls_session->ssl) != 1) {
1479 fr_tls_log_perror(request, "SSL_new_session_ticket failed");
1480 tls_session->app_data_ready = false;
1481 fr_tls_session_request_unbind(tls_session->ssl);
1482 return -1;
1483 }
1484
1485 ret = SSL_do_handshake(tls_session->ssl);
1486 if (ret <= 0) {
1487 ret = fr_tls_log_io_error(request, SSL_get_error(tls_session->ssl, ret),
1488 "SSL_do_handshake (%s)", __FUNCTION__);
1489 if (ret < 0) {
1490 tls_session->app_data_ready = false;
1491 fr_tls_session_request_unbind(tls_session->ssl);
1492 return -1;
1493 }
1494 }
1495
1496 /*
1497 * The app_data_set() callback clears the flag when the callback uses the data. If the flag is
1498 * still set, then OpenSSL did not create a ticket. Don't leave stale data for the next ticket.
1499 */
1500 if (tls_session->app_data_ready) {
1501 RWDEBUG("(TLS) OpenSSL did not create a session ticket");
1502 tls_session->app_data_ready = false;
1503 }
1504
1505 fr_tls_session_request_unbind(tls_session->ssl);
1506 return 0;
1507}
1508
1509/** Record a failure which FreeRADIUS itself decided
1510 *
1511 * The `session-state` list is where these go, because the list is what
1512 * survives from one round of the handshake to the next, and because it is
1513 * the list which `fail session { ... }` is given.
1514 *
1515 * Errors append rather than replace. A record which FreeRADIUS refuses
1516 * marks the session invalid, and the round after that reports
1517 * `Session-Invalid`. Replacing would keep that second report and lose the
1518 * refusal which caused it, which is the part an administrator needs.
1519 *
1520 * @param[in] request to add the error to. A NULL request is ignored,
1521 * because several OpenSSL callbacks run without one.
1522 * @param[in] error an `FR_ERROR_VALUE_*` value from
1523 * `protocol/tls/freeradius.h`, which is generated from
1524 * `share/dictionary/tls/dictionary.freeradius`.
1525 */
1526void fr_tls_session_error_add(request_t *request, uint32_t error)
1527{
1528 fr_pair_t *vp;
1529
1530 if (!request) return;
1531
1533 vp->vp_uint32 = error;
1534
1535 RDEBUG2("(TLS) request.%pP", vp);
1536}
1537
1538/** Instruct fr_tls_session_async_handshake to create a synthesised TLS alert record and send it to the peer
1539 *
1540 */
1541int fr_tls_session_alert(request_t *request, fr_tls_session_t *session, uint8_t level, uint8_t description)
1542{
1543 fr_assert(request != NULL);
1544
1545 if (session->alerts_sent > 3) return -1; /* Some kind of state machine brokenness */
1546
1547 /*
1548 * Ignore an alert which has lower severity than the one already queued.
1549 *
1550 * Two alerts of the same severity means the first one is the cause, and the second one is a
1551 * later round noticing the damage. fr_tls_session_msg_cb() refuses a record and marks the
1552 * session invalid, and the round after that reports FR_ERROR_VALUE_SESSION_INVALID. The first
1553 * alert says what was wrong with the record, which is the part the peer can act on.
1554 */
1555 if (session->pending_alert && (level <= session->pending_alert_level)) return 0;
1556
1557 /*
1558 * Check our internal flag is write_encrypted. We track that above in fr_tls_session_msg_cb()
1559 *
1560 * Refusing here rather than when the alert is sent lets the caller act on the refusal. A caller
1561 * which queued the alert in order to reject the session has to fail the session some other way,
1562 * and both callers outside this file already check the return code.
1563 *
1564 * The caller still records the error, so `fail session { ... }` reports the same reason either
1565 * way. However, the peer never gets the alert.
1566 */
1567 if (session->write_encrypted) {
1568 RDEBUG2("(TLS) Not sending TLS alert (%u), the records we write are already encrypted",
1569 description);
1570 return -1;
1571 }
1572
1573 session->pending_alert = true;
1574 session->pending_alert_level = level;
1575 session->pending_alert_description = description;
1576
1577 return 0;
1578}
1579
1580/** Record an application error, and queue a fatal TLS alert for sending to the peer.
1581 *
1582 * We can refuse handshakes for a number of policy or application-layer reasons. RFC9846 Section 6.2 says
1583 * that we should send an alert to the peer, and then close the connection.
1584 *
1585 * This function should be used only when OpenSSL hasn't already sent an alert of its own.
1586 *
1587 * fr_tls_session_alert_send() builds the alert by hand, and overwrites whatever OpenSSL left in
1588 * the buffer.
1589 *
1590 * @param[in] request to add the error to.
1591 * @param[in] session to queue the alert on.
1592 * @param[in] error an `FR_ERROR_VALUE_*` value, as for
1593 * fr_tls_session_error_add().
1594 * @param[in] description the TLS alert description to send. Pass
1595 * `SSL_AD_INTERNAL_ERROR` where no more specific
1596 * description fits the rule which was broken.
1597 */
1598void fr_tls_session_error_alert(request_t *request, fr_tls_session_t *session,
1599 uint32_t error, uint8_t description)
1600{
1601 fr_tls_session_error_add(request, error);
1602
1603 (void) fr_tls_session_alert(request, session, SSL3_AL_FATAL, description);
1604}
1605
1606static void fr_tls_session_alert_send(request_t *request, fr_tls_session_t *session)
1607{
1608 ssize_t slen;
1609
1610 /*
1611 * Update our internal view of the session
1612 */
1613 session->info.origin = TLS_INFO_ORIGIN_RECORD_SENT;
1614 session->info.content_type = SSL3_RT_ALERT;
1615 session->info.alert_level = session->pending_alert_level;
1616 session->info.alert_description = session->pending_alert_description;
1617
1618 /*
1619 * session_msg_log() reads both of these, and decodes the
1620 * level and the description only when the length says two.
1621 * Without them the log line reports whatever record came
1622 * before this one, which is not the alert it claims to
1623 * describe. They have to agree with the record written
1624 * below.
1625 */
1626 session->info.version = TLS1_VERSION;
1627 session->info.record_len = 2;
1628
1629 /*
1630 * Sending an alert over-rides whatever was in the
1631 * buffer, waiting to be sent. But for nearly all cases,
1632 * the from_ssl buffer will already be empty.
1633 *
1634 * The application then sees the data, and writes it to
1635 * the peer.
1636 */
1637 fr_tls_bio_dbuff_clear(session->from_ssl);
1638
1639 slen = fr_dbuff_in_bytes(fr_tls_bio_dbuff_in(session->from_ssl),
1640 (uint8_t) session->info.content_type,
1641 (uint8_t) 3, (uint8_t) 1, (uint8_t) 0, (uint8_t) 2,
1642 session->pending_alert_level,
1643 session->pending_alert_description);
1644 if (!fr_cond_assert(slen == 7)) return;
1645
1646 /*
1647 * We're building the TLS Alert manually, so we have to
1648 * manually record it here.
1649 */
1650 tls_session_alert_pair_add(request, request->reply_ctx, "reply.",
1651 session->pending_alert_level, session->pending_alert_description);
1652 fr_tls_session_error_add(request, FR_ERROR_VALUE_SENT_ALERT);
1653
1654 session->pending_alert = false;
1655 session->alerts_sent++;
1656
1657 SSL_clear(session->ssl); /* Reset the SSL *, to allow the client to restart the session */
1658
1659 session_msg_log(request, session, fr_dbuff_current(session->dirty_out),
1660 fr_dbuff_remaining(session->dirty_out));
1661}
1662
1663/** Tell the peer about any pending errors before we close the connection.
1664 *
1665 * A connection which is about to close sends a `close_notify`, as RFC 9846 Section 6.1 says "Each party MUST
1666 * send a 'close_notify' alert before closing its write side of the connection, unless it has already sent
1667 * some error alert." If there's an error alert, then don't send that.
1668 *
1669 * - A queued fatal alert is an error, and we send that. The end of a handshake round sends any queued alert.
1670 * An error path does not reach the end of the round, so the "send alert" function has to be called
1671 * explicitly.
1672 *
1673 * - if there's no queued alert, then we just send a close_notify alert. OpenSSL doesn't provide any other
1674 * way to send a TLS alert to the peer.
1675 *
1676 * - If the handshake doesn't finish, then we can't send anything. The connection is likely not TLS, and
1677 * sending a TLS alert won't help.
1678 *
1679 * The application should send the remaining data, and then close the socket.
1680 *
1681 * @param[in] request to log against, and to bind while OpenSSL runs.
1682 * @param[in] session which is closing.
1683 */
1684void fr_tls_session_close_send(request_t *request, fr_tls_session_t *session)
1685{
1686 bool bound;
1687 int ret;
1688
1689 if (session->pending_alert) {
1690 fr_tls_session_alert_send(request, session);
1691 return;
1692 }
1693
1694 /*
1695 * We've already sent an error alert, and RFC 9846 Section 6.1 says we don't need to follow that
1696 * with a close_notify. OpenSSL alerts don't need to be counted, because they result in
1697 * handshake failures, and this function is never reached.
1698 */
1699 if (session->alerts_sent > 0) return;
1700
1701 if (!SSL_is_init_finished(session->ssl)) return;
1702
1703 /*
1704 * Make this function idempotent. The source of the fatal error calls us, and we might be called
1705 * again after `fail sessions { ... }` finishes. The application doesn't know what's up, so it
1706 * calls us just to be safe.
1707 */
1708 if (SSL_get_shutdown(session->ssl) & SSL_SENT_SHUTDOWN) return;
1709
1710 /*
1711 * A failure inside of a handshake results in fr_tls_session_msg_cb() being called, and it needs
1712 * the request bound. Do that here, if it wasn't already done/
1713 */
1714 bound = (fr_tls_session_request(session->ssl) != NULL);
1715 if (!bound) fr_tls_session_request_bind(session->ssl, request);
1716
1717 /*
1718 * Disable the OpenSSL quiet shutdown, so it sends close_notify. We need to do that on our
1719 * timeframe, so the quiet shutdown is on by default.
1720 *
1721 * OpenSSL drops a session from its internal cache (and maybe ours) when a connection closes
1722 * without seeing a `close_notify`.
1723 */
1724 SSL_set_quiet_shutdown(session->ssl, 0);
1725
1726 ret = SSL_shutdown(session->ssl);
1727
1728 /*
1729 * We're non-blocking, so a zero return is "we sent it, but we didn't see a response from the
1730 * peer", which is expected.
1731 */
1732 if (ret < 0) {
1733 RDEBUG2("(TLS) Failed sending close_notify");
1734 ERR_clear_error();
1735 } else {
1736 RDEBUG2("(TLS) Sending close_notify");
1737 }
1738
1739 if (!bound) fr_tls_session_request_unbind(session->ssl);
1740}
1741
1742/** Push an `establish session { ... }` call into the current request, using a subrequest
1743 *
1744 * @param[in] request The current request.
1745 * @param[in] conf TLS configuration.
1746 * @param[in] tls_session The current TLS session.
1747 * @return
1748 * - UNLANG_ACTION_PUSHED_CHILD on success.
1749 * - UNLANG_ACTION_FAIL on failure.
1750 */
1751static inline CC_HINT(always_inline)
1752unlang_action_t tls_establish_session_push(request_t *request, fr_tls_conf_t *conf, fr_tls_session_t *tls_session)
1753{
1754 request_t *child;
1755 unlang_action_t ua;
1756
1757 fr_assert(conf->virtual_server);
1758
1759 MEM(child = tls_subrequest_alloc(request, enum_tls_packet_type_establish_session->vb_uint32,
1760 &tls_session->session_id));
1761
1762 /*
1763 * Allocate a child, and set it up to call
1764 * the TLS virtual server.
1765 */
1766 ua = fr_tls_call_push(child, NULL, conf, tls_session, false);
1767 if (ua == UNLANG_ACTION_FAIL) {
1768 talloc_free(child);
1769 return UNLANG_ACTION_FAIL;
1770 }
1771
1772 return ua;
1773}
1774
1775/** Discard the session, once `fail session { ... }` has run
1776 *
1777 */
1778static unlang_action_t tls_session_fail_clear(request_t *request, void *uctx)
1779{
1780 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
1781
1782 return fr_tls_ticket_stateful_clear_session(request, tls_session);
1783}
1784
1785/** Discard the session without clearing the cached session, once `fail session { ... }` has run
1786 *
1787 */
1788static unlang_action_t tls_session_fail_discard(request_t *request, void *uctx)
1789{
1790 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
1791
1792 return fr_tls_ticket_stateful_discard_session(request, tls_session);
1793}
1794
1795/** The TLS session failed
1796 *
1797 * Runs `fail session { ... }`, so that the admin can run policies on
1798 * TLS connection failure. When `fail session { ... }` has finished, the function runs
1799 * `clear session { ... }` to remove any cached session information, unless `clear` is false.
1800 *
1801 * Pass `clear` as false after a network failure. A network failure is normal, and shouldn't invalidate the
1802 * session ticket.
1803 *
1804 * When `clear` is false, the function cancels any pending `store session { ... }`. A `clear session { ... }`
1805 * that was already queued for the loaded session still runs to invalidate the previous ticket, and any other
1806 * queued clear is dropped.
1807 *
1808 * A session can fail without session tickets, and a session ticket can be removed without a TLS
1809 * negotiation failure.
1810 *
1811 * @note The caller MUST set the caller's own unlang result before calling
1812 * `fr_tls_session_fail_session()`. A pushed child returns to the caller's
1813 * caller with that result already in place.
1814 *
1815 * @param[in] request to run the sections in.
1816 * @param[in] tls_session which failed.
1817 * @param[in] clear true to run `clear session { ... }` for a loaded session, false to
1818 * keep the cached session.
1819 * @return
1820 * - UNLANG_ACTION_PUSHED_CHILD - the sections are running.
1821 * - UNLANG_ACTION_CALCULATE_RESULT - there is no `fail session { ... }` section, and no
1822 * `clear session { ... }` was pushed.
1823 * - UNLANG_ACTION_FAIL - a frame could not be pushed.
1824 */
1825unlang_action_t fr_tls_session_fail_session(request_t *request, fr_tls_session_t *tls_session, bool clear)
1826{
1827 fr_tls_conf_t *conf = tls_session->conf;
1828 request_t *child;
1829 unlang_action_t ua;
1830 unlang_function_no_result_t finish = clear ? tls_session_fail_clear : tls_session_fail_discard;
1831
1832 if (!conf->fail_session) return finish(request, tls_session);
1833
1835 NULL,
1836 finish,
1837 NULL, FR_SIGNAL_NONE, UNLANG_SUB_FRAME, tls_session) == UNLANG_ACTION_FAIL) {
1838 return UNLANG_ACTION_FAIL;
1839 }
1840
1841 /*
1842 * A session which failed before OpenSSL established one has
1843 * no ID to report, which tls_subrequest_alloc() handles.
1844 */
1845 MEM(child = tls_subrequest_alloc(request, enum_tls_packet_type_fail_session->vb_uint32,
1846 &tls_session->session_id));
1847
1848 ua = fr_tls_call_push(child, NULL, conf, tls_session, false);
1850 talloc_free(child);
1852 return UNLANG_ACTION_FAIL;
1853 }
1854
1855 return ua;
1856}
1857
1858/** Finish off a handshake round, possibly adding attributes to the request
1859 *
1860 */
1861static unlang_action_t tls_session_async_handshake_done_round(request_t *request, void *uctx)
1862{
1863 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
1864 bool init_finished = false;
1865
1866 RDEBUG3("(TLS) entered state %s", __FUNCTION__);
1867
1868 /*
1869 * This only occurs once per session, where calling
1870 * SSL_read updates the state of the SSL session, setting
1871 * this flag to true.
1872 *
1873 * Callbacks provide enough info so we don't need to
1874 * print debug statements when the handshake is in other
1875 * states.
1876 *
1877 * This function is also called by the application when reading application data, because the
1878 * application shouldn't know about the internals of the TLS state machine. The flag ensures
1879 * that we only run this block once.
1880 */
1881 if (!tls_session->init_finished_processed && SSL_is_init_finished(tls_session->ssl)) {
1882 SSL_CIPHER const *cipher;
1883 fr_pair_t *vp;
1884 char const *version;
1885
1886 char cipher_desc[256], cipher_desc_clean[256];
1887 char *p = cipher_desc, *q = cipher_desc_clean;
1888
1889 tls_session->init_finished_processed = true;
1890 init_finished = true;
1891
1892 /*
1893 * Check if ALPN was successfully negotiated. We
1894 * can do this without caring about session
1895 * tickets.
1896 */
1897 if (fr_tls_session_alpn_check(request, tls_session) < 0) {
1898 fr_tls_session_close_send(request, tls_session);
1899 tls_session->result = FR_TLS_RESULT_ERROR;
1900 fr_tls_session_request_unbind(tls_session->ssl);
1902 }
1903
1904 cipher = SSL_get_current_cipher(tls_session->ssl);
1905 SSL_CIPHER_description(cipher, cipher_desc, sizeof(cipher_desc));
1906
1907 /*
1908 * Cleanup the output from OpenSSL
1909 * Seems to print info in a tabular format.
1910 */
1911 while (*p != '\0') {
1912 if (isspace((uint8_t) *p)) {
1913 p++;
1914 continue;
1915 }
1916 *q++ = *p++;
1917 }
1918 *q = '\0';
1919
1920 RDEBUG2("(TLS) Cipher suite: %s", cipher_desc_clean);
1921
1922 RDEBUG2("(TLS) Adding TLS session information to request");
1923 RINDENT();
1925 fr_pair_value_strdup(vp, SSL_CIPHER_get_name(cipher), false);
1926 RDEBUG2("(TLS) session-state.%pP", vp);
1927
1928 if (((size_t)tls_session->info.version >= NUM_ELEMENTS(tls_version_str)) ||
1929 !tls_version_str[tls_session->info.version]) {
1930 version = "UNKNOWN";
1931 } else {
1932 version = tls_version_str[tls_session->info.version];
1933 }
1934
1936 fr_pair_value_strdup(vp, version, false);
1937 RDEBUG2("(TLS) session-state.%pP", vp);
1938 REXDENT();
1939
1940 /*
1941 * Cache the SSL_SESSION pointer.
1942 *
1943 * Which contains all the data we need for session resumption.
1944 */
1945 if (!tls_session->session) {
1946 tls_session->session = SSL_get_session(tls_session->ssl);
1947 if (tls_session->session) {
1948 tls_session_id_cache(tls_session, tls_session->session);
1949 }
1950 if (!tls_session->session) {
1951 REDEBUG("(TLS) Failed getting TLS session");
1952 fr_tls_session_error_alert(request, tls_session,
1953 FR_ERROR_VALUE_SESSION_MISSING, SSL_AD_INTERNAL_ERROR);
1954 fr_tls_session_close_send(request, tls_session);
1955 tls_session->result = FR_TLS_RESULT_ERROR;
1956 fr_tls_session_request_unbind(tls_session->ssl);
1958 }
1959 }
1960
1961 if (RDEBUG_ENABLED3) {
1962 if (SSL_SESSION_print(fr_tls_request_log_bio(request, L_DBG, L_DBG_LVL_3),
1963 tls_session->session) != 1) {
1964 RDEBUG3("(TLS) Failed retrieving session data");
1965 }
1966 }
1967
1968 /*
1969 * Session was resumed, add attribute to mark it as such.
1970 */
1971 if (SSL_session_reused(tls_session->ssl)) {
1972 /*
1973 * Mark the request as resumed.
1974 */
1976 vp->vp_bool = true;
1977 }
1978 }
1979
1980 /*
1981 * Get the data to send to the peer. OpenSSL already did
1982 * it's magic, so we can just do ours here.
1983 *
1984 * No encrypted data means that OpenSSL produced no TLS
1985 * content, so the output is likely application data.
1986 */
1987 if ((tls_session->last_ret <= 0) && (fr_dbuff_remaining(tls_session->dirty_out) == 0)) {
1988 /* Its clean application data, do whatever we want */
1989 fr_tls_record_init(&tls_session->clean_out);
1990 }
1991
1992 /*
1993 * Trash the current data in dirty_out, and synthesize
1994 * a TLS error record.
1995 *
1996 * OpensSL annoyingly provides no mechanism for us to
1997 * send alerts, and we need to send alerts as part of
1998 * RFC 5216, so this is our only option.
1999 */
2000 if (tls_session->pending_alert) fr_tls_session_alert_send(request, tls_session);
2001
2002 tls_session->result = FR_TLS_RESULT_SUCCESS;
2003 fr_tls_session_request_unbind(tls_session->ssl);
2004 if (init_finished) {
2005 fr_tls_conf_t *conf = tls_session->conf;
2006 if (conf->establish_session) return tls_establish_session_push(request, conf, tls_session);
2007 }
2009}
2010
2011/** Try very hard to get the SSL * into a consistent state where it's not yielded
2012 *
2013 * ...because if it's yielded, we'll probably leak thread contexts and all kinds of memory.
2014 *
2015 * @param[in] request being cancelled.
2016 * @param[in] action we're being signalled with.
2017 * @param[in] uctx the SSL * to cancel.
2018 */
2019static void tls_session_async_handshake_signal(UNUSED request_t *request, UNUSED fr_signal_t action, void *uctx)
2020{
2021 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
2022 int ret;
2023
2024 /*
2025 * We might want to set can_pause = false here
2026 * but that would trigger asserts in the
2027 * cache code.
2028 */
2029
2030 /*
2031 * If SSL_get_error returns SSL_ERROR_WANT_ASYNC
2032 * it means we're yielded in the middle of a
2033 * callback.
2034 *
2035 * Keep calling SSL_read() in a loop until we
2036 * no longer get SSL_ERROR_WANT_ASYNC, then
2037 * shut it down so it's in a consistent state.
2038 *
2039 * It'll get freed later when the request is
2040 * freed.
2041 */
2042 for (ret = tls_session->last_ret;
2043 SSL_get_error(tls_session->ssl, ret) == SSL_ERROR_WANT_ASYNC;
2044 ret = SSL_read(tls_session->ssl, fr_dbuff_current(&tls_session->clean_out),
2045 (int)fr_dbuff_remaining(&tls_session->clean_out)));
2046
2047 /*
2048 * Unbind the cancelled request from the SSL *
2049 */
2050 fr_tls_session_request_unbind(tls_session->ssl);
2051}
2052
2053/** Push the section for one bit of #fr_tls_pending_t
2054 *
2055 */
2056typedef unlang_action_t (*fr_tls_pending_push_t)(request_t *request, fr_tls_session_t *tls_session);
2057
2058/** Push the section for every raised bit, then call SSL_read() to continue the TLS state machine
2059 *
2060 * This function may be called multiple times, once after every asynchronous request.
2061 *
2062 * @param[in] request The current request.
2063 * @param[in] uctx #fr_tls_session_t to continue.
2064 * @return
2065 * - UNLANG_ACTION_CALCULATE_RESULT - We're done with this round, or a push
2066 * failed and `tls_session->result` is FR_TLS_RESULT_ERROR.
2067 * - UNLANG_ACTION_PUSHED_CHILD - Need to perform more asynchronous actions.
2068 */
2069static unlang_action_t tls_session_async_handshake_cont(request_t *request, void *uctx)
2070{
2071 /*
2072 * `push[idx]` is the push function for bit `1 << idx`.
2073 */
2074 static fr_tls_pending_push_t const push[] = {
2075 [0] = fr_tls_ticket_stateful_pending_push, /* FR_TLS_PENDING_STATEFUL_TICKET */
2076 [1] = fr_tls_ticket_stateless_pending_push, /* FR_TLS_PENDING_STATELESS_TICKET */
2077#ifdef PSK_MAX_IDENTITY_LEN
2078 [2] = fr_tls_session_psk_pending_push, /* FR_TLS_PENDING_PSK */
2079#endif
2080 [3] = fr_tls_verify_cert_pending_push, /* FR_TLS_PENDING_VERIFY */
2081 };
2082 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
2083 int err;
2084
2085 RDEBUG3("(TLS) (re-)entered state %s", __FUNCTION__);
2086
2087again:
2088 while (tls_session->pending) {
2089 unsigned int idx = fr_low_bit_pos(tls_session->pending) - 1;
2090 fr_tls_pending_t bit = (fr_tls_pending_t)(UINT64_C(1) << idx);
2091 unlang_action_t ua;
2092
2093 fr_assert(idx < NUM_ELEMENTS(push));
2094 fr_assert(push[idx]);
2095
2096 /*
2097 * Each bit is one shot. The push function is called once for
2098 * the bit, and raises the bit again if the callback asks again.
2099 */
2100 TLS_PENDING_CLEAR(tls_session, bit);
2101
2102 /*
2103 * Set this function as the repeat function before the push, so
2104 * the frame runs this function again once the section has finished.
2105 */
2106 if (unlikely(unlang_function_repeat_set(request, tls_session_async_handshake_cont) < 0)) {
2107 error:
2108 tls_session->result = FR_TLS_RESULT_ERROR;
2109 goto finish;
2110 }
2111
2112 ua = push[idx](request, tls_session);
2113 switch (ua) {
2115 return ua;
2116
2117 case UNLANG_ACTION_FAIL:
2119 goto error;
2120
2121 default:
2122 /*
2123 * The push function found nothing to push for this bit, so the
2124 * repeat function never runs. Clear the repeat function and
2125 * service the next raised bit.
2126 */
2128 break;
2129 }
2130 }
2131
2132 /*
2133 * Clear OpenSSL's thread local error stack.
2134 *
2135 * Why do we need to do this here? Although SSL_get_error
2136 * takes an `SSL *`, which would make you _think_ it was
2137 * operating on the error stack for that SSL, it will also
2138 * return SSL_ERROR_SSL if there are any errors in the stack.
2139 *
2140 * When operating normally SSL_read() can return < 0, to
2141 * indicate it wants more data, or that we need to perform
2142 * asynchronous processing.
2143 *
2144 * If spurious errors have been left on the thread local
2145 * stack they MUST be cleared before we can call SSL_get_error
2146 * otherwise stale errors mask the async notifications
2147 * and cause random handshake failures.
2148 */
2149 ERR_clear_error();
2150
2151 /*
2152 * Magic/More magic? Although SSL_read is normally
2153 * used to read application data, it will also
2154 * continue the TLS handshake. Removing this call will
2155 * cause the handshake to fail.
2156 *
2157 * We don't ever expect to actually *receive* application
2158 * data here.
2159 *
2160 * The reason why we call SSL_read instead of SSL_accept,
2161 * or SSL_connect, as it allows this function
2162 * to be used, irrespective or whether we're acting
2163 * as a client or a server.
2164 *
2165 * If acting as a client SSL_set_connect_state must have
2166 * been called before this function.
2167 *
2168 * If acting as a server SSL_set_accept_state must have
2169 * been called before this function.
2170 */
2171 tls_session->can_pause = true;
2172 tls_session->last_ret = SSL_read(tls_session->ssl, fr_dbuff_current(&tls_session->clean_out),
2173 (int)fr_dbuff_remaining(&tls_session->clean_out));
2174 tls_session->can_pause = false;
2175 if (tls_session->last_ret > 0) {
2176 fr_dbuff_advance(&tls_session->clean_out, (size_t) tls_session->last_ret);
2177
2178 /*
2179 * We've received application data. This is a positive
2180 * signal that all session tickets have been sent.
2181 * This flag informs fr_tls_session_is_init_finished().
2182 */
2183 tls_session->seen_application_data = true;
2184
2185 /*
2186 * The peer can send application data in the same read() as the end of the handshake.
2187 * Therefore once we've decided that we're done the handshake, we also check for
2188 * application data.
2189 */
2190 return tls_session_async_handshake_done_round(request, uctx);
2191
2192 finish:
2193 /*
2194 * Was bound by caller
2195 */
2196 fr_tls_session_request_unbind(tls_session->ssl);
2198 }
2199
2200 /*
2201 * Bug in OpenSSL 3.0 - Normal handshaking behaviour
2202 * results in spurious "BIO_R_UNSUPPORTED_METHOD"
2203 * errors.
2204 *
2205 * SSL_get_error apparently returns SSL_ERROR_SSL if
2206 * there are any errors in the stack. This masks
2207 * SSL_ERROR_WANT_ASYNC and causes the handshake to
2208 * fail.
2209 *
2210 * Note: We may want some version of this code
2211 * included for all OpenSSL versions.
2212 *
2213 * It would call ERR_GET_FATAL() on each of the errors
2214 * in the stack to drain non-fatal errors and prevent
2215 * the other (more useful) return codes of
2216 * SSL_get_error from being masked. I guess we'll see
2217 * if this occurs in other scenarios.
2218 */
2219 if (SSL_get_error(tls_session->ssl, tls_session->last_ret) == SSL_ERROR_SSL) {
2220 unsigned long ssl_err;
2221
2222 /*
2223 * Some weird OpenSSL thing marking ERR_GET_REASON
2224 * as "unused". Unclear why this is done as it's
2225 * not deprecated.
2226 */
2227DIAG_OFF_OPTIONAL(used-but-marked-unused)
2228 while ((ssl_err = ERR_peek_error()) && (ERR_GET_REASON(ssl_err) == BIO_R_UNSUPPORTED_METHOD)) {
2229 (void) ERR_get_error();
2230 }
2231DIAG_ON_OPTIONAL(used-but-marked-unused)
2232 }
2233
2234 /*
2235 * Deal with asynchronous requests from OpenSSL.
2236 * These aren't actually errors, they're the
2237 * result of one of our callbacks indicating that
2238 * it'd like to perform the operation
2239 * asynchronously.
2240 */
2241 switch (err = SSL_get_error(tls_session->ssl, tls_session->last_ret)) {
2242 case SSL_ERROR_WANT_ASYNC: /* Certification validation or cache loads */
2243 goto again;
2244
2245 case SSL_ERROR_WANT_ASYNC_JOB:
2246 REDEBUG("(TLS) No async jobs available in pool, increase thread.openssl_async_pool_max");
2247 goto error;
2248
2249 default:
2250 /*
2251 * Returns 0 if we can continue processing the handshake
2252 * Returns -1 if we encountered a fatal error.
2253 */
2254 if (fr_tls_log_io_error(request,
2255 err, "SSL_read (%s)", __FUNCTION__) < 0) goto error;
2256 return tls_session_async_handshake_done_round(request, uctx);
2257 }
2258}
2259
2260/** Ingest data for another handshake round
2261 *
2262 * Advance the TLS handshake by feeding OpenSSL data from dirty_in,
2263 * and reading data from OpenSSL into dirty_out.
2264 *
2265 * Calls #tls_session_async_handshake_read to perform the actual ingestion.
2266 * #tls_session_async_handshake_read is split out because we may need to call
2267 * it multiple times, once after every async action.
2268 *
2269 * @param[in] request The current request.
2270 * @param[in] uctx #fr_tls_session_t to continue.
2271 * @return
2272 * - UNLANG_ACTION_CALCULATE_RESULT - We're done with this round.
2273 * - UNLANG_ACTION_PUSHED_CHILD - Need to perform more asynchronous actions.
2274 */
2275static unlang_action_t tls_session_handshake_round(request_t *request, void *uctx)
2276{
2277 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
2278
2279 RDEBUG3("(TLS) entered state %s", __FUNCTION__);
2280
2281 tls_session->result = FR_TLS_RESULT_IN_PROGRESS;
2282
2283 fr_tls_session_request_bind(tls_session->ssl, request); /* May be unbound in this function or asynchronously */
2284
2285 /*
2286 * This is a logic error.
2287 * fr_tls_session_async_handshake() must not be called if
2288 * the handshake is complete. fr_tls_session_recv() must
2289 * be called instead.
2290 *
2291 * Check for full init finished, including TLS 1.3 for a
2292 * client with stateless session tickets. Those arrive
2293 * after the TLS handshake has completed.
2294 */
2295 if (fr_tls_session_is_init_finished(tls_session)) {
2296 REDEBUG("(TLS) Attempted to continue TLS handshake, but handshake has completed");
2297 fr_tls_session_error_alert(request, tls_session,
2298 FR_ERROR_VALUE_HANDSHAKE_FINISHED, SSL_AD_INTERNAL_ERROR);
2299 error:
2300 /*
2301 * The end of the round is what normally sends a
2302 * queued alert, and this exit does not reach it.
2303 * EAP has no other chance: it pushes the handshake
2304 * itself and never touches fr_tls_connection_t.
2305 */
2306 fr_tls_session_close_send(request, tls_session);
2307 tls_session->result = FR_TLS_RESULT_ERROR;
2308 fr_tls_session_request_unbind(tls_session->ssl); /* Was bound in this function */
2310 }
2311
2312 if (tls_session->invalid) {
2313 REDEBUG("(TLS) Preventing invalid session from continuing");
2314 fr_tls_session_error_alert(request, tls_session,
2315 FR_ERROR_VALUE_SESSION_INVALID, SSL_AD_INTERNAL_ERROR);
2316 goto error;
2317 }
2318
2319 /*
2320 * This function runs once per handshake message, and
2321 * only for handshake messages. Count the number of
2322 * handshakes, and if there are too many, then forcibly
2323 * stop the TLS negotiation.
2324 */
2325 tls_session->rounds++;
2326 if (tls_session->rounds >= FR_TLS_MAX_ROUNDS) {
2327 REDEBUG("(TLS) Failing TLS session due to too many handshake rounds (limit %u)", FR_TLS_MAX_ROUNDS);
2328 fr_tls_session_error_alert(request, tls_session,
2329 FR_ERROR_VALUE_TOO_MANY_ROUNDS, SSL_AD_INTERNAL_ERROR);
2330 goto error;
2331 }
2332
2333 /*
2334 * OpenSSL does it's magic to convert the encrypted
2335 * dirty_in data to clean_out application data.
2336 */
2337 return tls_session_async_handshake_cont(request, uctx); /* Must unbind request, possibly asynchronously */
2338}
2339
2340/** Ask the virtual server for a session to resume, then start the handshake
2341 *
2342 * Only a client picks a session to resume before the handshake starts. A
2343 * server is asked for one by OpenSSL, part way through the handshake, and
2344 * answers from tls_ticket_stateful_load_cb().
2345 *
2346 * Nothing is bound to the SSL * yet, so the `load session { ... }` section can
2347 * push a subrequest without the handshake holding the SSL * while that
2348 * subrequest runs.
2349 */
2350static unlang_action_t tls_session_load_session(request_t *request, void *uctx)
2351{
2352 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
2353 unlang_action_t ua;
2354
2355 /*
2356 * The round runs next whatever happens here, so arm it before
2357 * pushing anything. unlang_function_repeat_set() only works
2358 * while this frame is on top of the stack, and pushing a child
2359 * puts another frame on top.
2360 */
2361 if (unlikely(unlang_function_repeat_set(request, tls_session_handshake_round) < 0)) {
2362 error:
2363 tls_session->result = FR_TLS_RESULT_ERROR;
2365 }
2366
2367 ua = fr_tls_ticket_stateful_load_client_push(request, tls_session);
2368 if (ua == UNLANG_ACTION_PUSHED_CHILD) return ua;
2369 if (ua == UNLANG_ACTION_FAIL) goto error;
2370
2371 return tls_session_handshake_round(request, uctx);
2372}
2373
2374/** Run one round of the handshake, and the policy which precedes the first one
2375 *
2376 * The caller pushes this once per round, so the work which happens only once
2377 * is keyed off the round counter. `tls_session->rounds` is incremented by
2378 * tls_session_handshake_round(), so a zero here means no round has run yet.
2379 *
2380 * `new session { ... }` is not run here. That section runs before the
2381 * session is allocated, so that it can set control attributes which decide how
2382 * the session is allocated, such as EAP-TLS-Require-Client-Cert. By the time
2383 * a handshake round runs, the session already exists and the decision has been
2384 * taken. Running `new session { ... }` from here would be too late, so the
2385 * caller runs it.
2386 */
2387static unlang_action_t tls_session_async_handshake(request_t *request, void *uctx)
2388{
2389 fr_tls_session_t *tls_session = talloc_get_type_abort(uctx, fr_tls_session_t);
2390
2391 if ((tls_session->rounds == 0) && !SSL_is_server(tls_session->ssl)) {
2392 return tls_session_load_session(request, uctx);
2393 }
2394
2395 return tls_session_handshake_round(request, uctx);
2396}
2397
2398/** Push a handshake call onto the stack
2399 *
2400 * We push the handshake frame (as opposed to having the caller do it),
2401 * so that we guarantee there's a frame that the handshake function can
2402 * manipulate to manage its own state.
2403 *
2404 * The result of processing this handshake round can be found in
2405 * tls_session->result.
2406 *
2407 * @param[in] request The current request.
2408 * @param[in] tls_session to continue handshaking.
2409 * @return
2410 * - UNLANG_ACTION_PUSHED_CHILD on success.
2411 * - UNLANG_ACTION_FAIL on failure.
2412 */
2413unlang_action_t fr_tls_session_async_handshake_push(request_t *request, fr_tls_session_t *tls_session)
2414{
2416 tls_session_async_handshake,
2417 NULL,
2418 tls_session_async_handshake_signal,
2421 tls_session);
2422}
2423
2424/** Will this handshake negotiate TLS 1.3?
2425 *
2426 * OpenSSL decides whether to send a TLS 1.2 ticket while it parses the ClientHello extensions, so which means that
2427 * we need to check TLS versions in the ClientHello callback.
2428 *
2429 * TLS 1.3 is negotiated when the server allows it, and the client lists it in `supported_versions`.
2430 * A client which sends no `supported_versions` extension (including a DTLS client) cannot do TLS 1.3.
2431 *
2432 * @param[in] ssl to check. Must be inside the ClientHello callback.
2433 * @return
2434 * - true if TLS 1.3 will be negotiated.
2435 * - false if TLS 1.2 or earlier will be negotiated.
2436 */
2437static bool tls_client_hello_is_tls13(SSL *ssl)
2438{
2439 uint8_t const *p;
2440 size_t len, i;
2441 int max = SSL_get_max_proto_version(ssl);
2442
2443 if (max && (max < TLS1_3_VERSION)) return false;
2444
2445 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_supported_versions, &p, &len) != 1) return false;
2446
2447 /*
2448 * One byte of length, then a list of two byte versions.
2449 */
2450 if ((len < 1) || (p[0] != (len - 1)) || (p[0] & 0x01)) return false;
2451
2452 for (i = 1; (i + 1) < len; i += 2) {
2453 if (((p[i] << 8) | p[i + 1]) == TLS1_3_VERSION) return true;
2454 }
2455
2456 return false;
2457}
2458
2459/** Callback run during ClientHello phase of handshake
2460 *
2461 * The SSL_client_hello* functions can only be called inside a callback like this.
2462 */
2463static int fr_tls_session_client_hello_cb(SSL *ssl, int *al, UNUSED void *arg)
2464{
2465 fr_tls_conf_t *conf = fr_tls_session_conf(ssl);
2466 request_t *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
2467
2468 /*
2469 * If there's an ALPN table set, fail now if we can't agree on an ALPN string.
2470 */
2471 if (conf->alpn_table) {
2472 int ret = fr_tls_session_alpn_client_hello(ssl, request, al, tls_client_hello_is_tls13(ssl));
2473
2474 if (ret != SSL_CLIENT_HELLO_SUCCESS) return ret;
2475 }
2476
2477 /*
2478 * Is there a session_ticket extension in the CLientHello?
2479 * If not, the client doesn't support session tickets - disable them.
2480 */
2481 if (conf->cache.mode != FR_TLS_TICKET_DISABLED) {
2482 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_session_ticket, NULL, NULL) == 1) {
2483 fr_tls_session_t *tls_session = fr_tls_session(ssl);
2484 tls_session->session_ticket_supported = true;
2485 } else {
2486 long ssl_options = SSL_get_options(ssl);
2487 RDEBUG2("(TLS) Session ticket extension not found in ClientHello");
2488 ssl_options |= SSL_OP_NO_TICKET;
2489 SSL_set_options(ssl, ssl_options);
2490 }
2491
2492 /*
2493 * Session tickets interact badly with EAP. For EAP success, we would ideally like to
2494 * send the session ticket only after the inner-tunnel method has succeeded. However,
2495 * for TLS 1.2, the ticket it sent during the TLS handshake, and there's nothing we can
2496 * do about that.
2497 *
2498 * So for stateful session tickets, we just skip `store session` if the inner-tunnel
2499 * method fails. The peer has a ticket (with an ID), but the server doesn't know about
2500 * that ticket or ID, and therefore won't be able to resume the session.
2501 *
2502 * For TLS 1.3, the session ticket is sent after the TLS handshake has completed.
2503 * HOWEVER, the EAP peers will process that ticket only in a few situations. (1) if they
2504 * see the ticket immediately after the TLS handshake has completed, or (2) when the
2505 * ticket arrives with expected inner-tunnel "success" from the server.
2506 *
2507 * i.e. for EAP-TLS, with the inner "protected success indicator". For PEAP / TTLS /
2508 * FAST, with the MS-CHAPv2 success. For TTLS with PAP or CHAP, you're out of luck.
2509 *
2510 * Overall, stateless session tickets are poorly tested with TLS 1.2, even outside of EAP.
2511 *
2512 * All of the above menas that We allow stateless session tickets only when TLS 1.3 has
2513 * been negotiated. In `auto` mode with TLS 1.2, we forced the use of stateful session
2514 * IDs.
2515 */
2516 if ((conf->cache.mode & FR_TLS_TICKET_STATELESS) && !tls_client_hello_is_tls13(ssl)) {
2517 fr_tls_session_t *tls_session = fr_tls_session(ssl);
2518
2519 RDEBUG2("(TLS) Stateless session tickets are not used below TLS 1.3");
2520 SSL_set_options(ssl, SSL_get_options(ssl) | SSL_OP_NO_TICKET);
2521 tls_session->session_ticket_supported = false;
2522 }
2523 }
2524
2525 if (conf->client_hello_parse) return fr_tls_session_client_hello_pairs(ssl, request);
2526
2527 return SSL_CLIENT_HELLO_SUCCESS;
2528}
2529
2530/** Free a TLS session and any associated OpenSSL data
2531 *
2532 * @param session to free.
2533 * @return 0.
2534 */
2535static int _fr_tls_session_free(fr_tls_session_t *session)
2536{
2537 /*
2538 * The application can free the session before the cache operations have run, for example
2539 * when the peer closes the connection after the handshake has finished. A cache section
2540 * needs a request to run, and no request exists in this destructor. Because of that, the
2541 * cache destructor discards the queued operations.
2542 *
2543 * A discarded `store session` is harmless. Because the server never stored the session
2544 * that the ticket names, the peer cannot resume from the ticket. A discarded
2545 * `clear session` leaves the session in the cache until the cache entry for the session
2546 * expires.
2547 */
2548 if (fr_tls_ticket_stateful_pending(session->cache)) {
2549 DEBUG2("(TLS) Discarding queued cache operations, session freed before the operations ran");
2550 }
2551
2552 if (session->ssl) {
2553 /*
2554 * The OpenSSL docs state:
2555 *
2556 * SSL_shutdown() can be modified to only set the
2557 * connection to "shutdown" state but not actually
2558 * send the "close notify" alert messages, see
2559 * SSL_CTX_set_quiet_shutdown(3). When "quiet shutdown"
2560 * is enabled, SSL_shutdown() will always succeed and
2561 * return 1.
2562 *
2563 * This is only partially correct. This call does mean
2564 * we don't notify the other party, but the SSL_shutdown
2565 * call can still fail if the handshake hasn't begun, leaving
2566 * spurious errors on the thread local error stack.
2567 */
2568 SSL_set_quiet_shutdown(session->ssl, 1);
2569
2570 /*
2571 * Don't leave spurious errors raised by SSL_shutdown on
2572 * the error stack.
2573 */
2574 if (SSL_shutdown(session->ssl) != 1) ERR_clear_error();
2575
2576 SSL_free(session->ssl);
2577 session->ssl = NULL;
2578 }
2579
2580 return 0;
2581}
2582
2583/** Set the sizes of the record buffers from `conf->buffer_size`
2584 *
2585 * The clean buffers hold `conf->buffer_size` bytes of application data. The dirty buffers can be larger due
2586 * to TLS headers, MAC, and padding. The dirty buffers are therefore larger than the clean ones.
2587 *
2588 * The into_ssl buffer has to hold at least one complete record, because OpenSSL decrypts only complete
2589 * records, and the peer decides how large its records are.
2590 *
2591 * Both sizes are rounded up to a 1K boundary, just because.
2592 *
2593 * @param[in] tls_session to set the sizes for.
2594 */
2595static void tls_session_set_buffer_sizes(fr_tls_session_t *tls_session)
2596{
2597 size_t records;
2598
2599 tls_session->clean_size = ROUND_UP_POW2((size_t) tls_session->conf->buffer_size, 1024);
2600
2601 records = ROUND_UP_DIV(tls_session->clean_size, SSL3_RT_MAX_PLAIN_LENGTH);
2602
2603 tls_session->dirty_size = tls_session->clean_size + (records * (FR_TLS_MAX_PACKET_SIZE - SSL3_RT_MAX_PLAIN_LENGTH));
2604 if (tls_session->dirty_size < FR_TLS_MAX_PACKET_SIZE) tls_session->dirty_size = FR_TLS_MAX_PACKET_SIZE;
2605
2606 tls_session->dirty_size = ROUND_UP_POW2(tls_session->dirty_size, 1024);
2607}
2608
2609/** Allocate a new #fr_tls_session_t and initialize it
2610 *
2611 */
2612static fr_tls_session_t *tls_session_alloc(TALLOC_CTX *ctx, request_t *request, SSL_CTX *ssl_ctx)
2613{
2614 fr_tls_session_t *tls_session;
2615
2616 tls_session = talloc_zero(ctx, fr_tls_session_t);
2617 if (!tls_session) return NULL;
2618
2619 /*
2620 * The socket type determines whether we use TLS or DTLS.
2621 */
2622 tls_session->socket_type = (SSL_CTX_get_ssl_method(ssl_ctx) == DTLS_method()) ? SOCK_DGRAM : SOCK_STREAM;
2623
2624 /*
2625 * Cache the configuration pointer, because it doesn't change during the lifetime of the
2626 * connection.
2627 */
2628 tls_session->conf = fr_tls_ctx_conf(ssl_ctx);
2629 tls_session_set_buffer_sizes(tls_session);
2630
2631 tls_session->ctx = ssl_ctx;
2632
2633 tls_session->ssl = SSL_new(ssl_ctx);
2634 if (!tls_session->ssl) {
2635 talloc_free(tls_session);
2636 fr_tls_log_perror(request, "Error creating new TLS session");
2637 return NULL;
2638 }
2639
2640 talloc_set_destructor(tls_session, _fr_tls_session_free);
2641 fr_pair_list_init(&tls_session->extra_pairs);
2642
2643 fr_value_box_init_null(&tls_session->session_id);
2644
2645 tls_session->alpn_id = FR_TLS_ALPN_ID_NONE;
2646
2647 /*
2648 * Add the message callback to identify what type of
2649 * message/handshake is passed
2650 */
2651 SSL_set_msg_callback(tls_session->ssl, fr_tls_session_msg_cb);
2652 SSL_set_msg_callback_arg(tls_session->ssl, tls_session);
2653 SSL_set_info_callback(tls_session->ssl, fr_tls_session_info_cb);
2654
2655 SSL_set_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_TLS_SESSION, (void *)tls_session);
2656
2657 /*
2658 * The client sometimes doesn't have a request. The server always has one.
2659 */
2660 if (!request) return tls_session;
2661
2662 /*
2663 * If there is a request, then allocate the record buffers and
2664 * create the BIOs. Otherwise leave the record buffers empty and
2665 * the bio handles as NULL, so that any accidental use
2666 * causes problems.
2667 */
2668 {
2669 fr_dbuff_t *record[] = { &tls_session->clean_in, &tls_session->clean_out };
2670 size_t i;
2671
2672 for (i = 0; i < NUM_ELEMENTS(record); i++) {
2673 uint8_t *buff;
2674
2675 MEM(buff = talloc_array(tls_session, uint8_t, tls_session->clean_size));
2676 fr_dbuff_init(record[i], buff, tls_session->clean_size);
2677 }
2678 }
2679
2680 /*
2681 * Create & hook the BIOs to handle the dirty side of the
2682 * SSL. The caller writes encrypted data into the
2683 * "dirty_in" side via some external mechanism, and
2684 * writes encrypted data out of the "dirty_out" side via
2685 * an external mechanism. This design allows us to use
2686 * the same TLS code for both RadSec, and for all
2687 * TLS-enabled EAP methods.
2688 *
2689 * OpenSSL either reads "dirty_in" and writes
2690 * "clean_out", or reads "clean_in" and writes
2691 * "dirty_out".
2692 *
2693 * We allocate a fixed size buffer going into_ssl,
2694 * because an extensible buffer could allow the peer to
2695 * send us unbounded data. A fixed size buffer allows
2696 * this code to limit that usage.
2697 *
2698 * @todo - make the input buffer extendable, but with
2699 * a maximum limit, and only after all TLS negotiation
2700 * has completed, and the session is fully authenticated.
2701 *
2702 * The size is dirty_size and not clean_size. Data
2703 * OpenSSL has not used stay in the buffer, as they are
2704 * generally partial TLS records. But the buffer has to
2705 * be large enough to hold an entire TLS record. See
2706 * tls_session_set_buffer_sizes().
2707 *
2708 * Init and max are the same, so the buffer is allocated
2709 * once, and does not grow unless a caller explicitly
2710 * raises it. See fr_tls_bio_dbuff_max_set()`
2711 *
2712 * We don't limit the data coming out of from_ssl,
2713 * because OpenSSL decides how much it writes. Multiple
2714 * handshakes could carry a long certificate chain, which
2715 * exceeds one record in size.
2716 */
2717 {
2718 BIO *rbio, *wbio;
2719
2720 /*
2721 * free_buff is false because tls_session is the talloc
2722 * parent of the buffer as well as of the
2723 * fr_tls_bio_dbuff_t. talloc frees the buffer with the
2724 * session, and a destructor which freed it too would
2725 * free it twice.
2726 */
2727 MEM(rbio = fr_tls_bio_dbuff_alloc(&tls_session->into_ssl, tls_session, tls_session,
2728 tls_session->dirty_size, tls_session->dirty_size, false));
2729 MEM(wbio = fr_tls_bio_dbuff_alloc(&tls_session->from_ssl, tls_session, tls_session,
2730 tls_session->dirty_size, 0, false));
2731
2732 tls_session->dirty_in = fr_tls_bio_dbuff_in(tls_session->into_ssl);
2733 tls_session->dirty_out = fr_tls_bio_dbuff_out(tls_session->from_ssl);
2734
2735 /*
2736 * SSL_set_bio() takes ownership of both BIOs, and the
2737 * fr_tls_bio_dbuff_t destructor frees its own BIO. Give
2738 * each owner a reference to drop.
2739 */
2740 BIO_up_ref(rbio);
2741 BIO_up_ref(wbio);
2742 SSL_set_bio(tls_session->ssl, rbio, wbio);
2743 }
2744
2745 return tls_session;
2746}
2747
2748/** Create a new client TLS session
2749 *
2750 * Configures a new client TLS session, configuring options, setting callbacks etc...
2751 *
2752 * If request is not passed, the caller gets a bare SSL*, and owns
2753 * the transport itself. The session has no memory BIOs, and OpenSSL
2754 * does the certificate validation on its own. This API is used by
2755 * hiredis, which needs direct access to the bare SSL*
2756 *
2757 * If a request is passed, the session management follows the server
2758 * session path. Data goes through memory BIOs,
2759 * fr_tls_session_async_handshake_push() is run for each round, and
2760 * certificate verification calls the `verify certificate` section of
2761 * the configured virtual_server.
2762 *
2763 * @param[in] ctx to alloc session data in. Should usually be NULL unless the lifetime of the
2764 * session is tied to another talloc'd object.
2765 * @param[in] ssl_ctx containing the base configuration for this session.
2766 * @param[in] request which the handshake runs under, or NULL for a session whose transport
2767 * is owned by the caller.
2768 * @return
2769 * - A new session on success.
2770 * - NULL on error.
2771 */
2772fr_tls_session_t *fr_tls_session_alloc_client(TALLOC_CTX *ctx, SSL_CTX *ssl_ctx, request_t *request)
2773{
2774 int verify_mode;
2775 fr_tls_session_t *tls_session;
2776 fr_tls_conf_t *conf = fr_tls_ctx_conf(ssl_ctx);
2777
2778 tls_session = tls_session_alloc(ctx, request, ssl_ctx);
2779 if (!tls_session) return NULL;
2780
2781 /*
2782 * In Client mode we only connect.
2783 *
2784 * This sets up the SSL session to work correctly with
2785 * fr_tls_session_handshake.
2786 */
2787 SSL_set_connect_state(tls_session->ssl);
2788
2789 /*
2790 * Always verify the peer, but only require a certificate
2791 * when we're doing certificate authentication.
2792 *
2793 * PSK doesn't use certs, so we can't require certs if
2794 * we're using PSK.
2795 */
2796 verify_mode = SSL_VERIFY_PEER;
2797 if (!conf->psk.identity) {
2798 ROPTIONAL(RDEBUG2, DEBUG2, "Requiring Server certificate");
2799 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2800 }
2801
2802 if (request) {
2803 /*
2804 * fr_tls_verify_cert_cb() pauses the handshake and runs
2805 * the `verify certificate` section. It needs a request,
2806 * and it needs to be called from inside
2807 * tls_session_async_handshake_cont().
2808 */
2809 tls_session->verify_peer_cert = true;
2810 SSL_set_verify(tls_session->ssl, verify_mode, fr_tls_verify_cert_cb);
2811 } else {
2812 /*
2813 * With no request there is nowhere to run a policy, so
2814 * OpenSSL does the validating. When the callback is
2815 * NULL OpenSSL uses its own validation function, and the
2816 * flags modify that function's behaviour.
2817 */
2818 SSL_set_verify(tls_session->ssl, verify_mode, NULL);
2819 }
2820
2821 SSL_set_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
2822
2823 /*
2824 * Datagrams need to be limited to a pre-configured MTU. So we remember that, and tell OpenSSL
2825 * to limit the MTU.
2826 */
2827 if ((tls_session->socket_type == SOCK_DGRAM) && (fr_dtls_session_init(tls_session, conf) < 0)) {
2828 talloc_free(tls_session);
2829 return NULL;
2830 }
2831
2832 /*
2833 * Session resumption needs somewhere to keep its state, and is
2834 * driven by the caller. See fr_tls_ticket_stateful_load_client_push() and
2835 * fr_tls_ticket_stateful_pending_push().
2836 */
2837 if (request && (conf->cache.mode != FR_TLS_TICKET_DISABLED)) {
2838 tls_session->allow_session_resumption = true; /* otherwise it's false */
2839 fr_tls_ticket_stateful_session_alloc(tls_session);
2840 }
2841
2842 return tls_session;
2843}
2844
2845/** Create a new server TLS session
2846 *
2847 * Configures a new server TLS session, configuring options, setting callbacks etc...
2848 *
2849 * @param[in] ctx to alloc session data in. Should usually be NULL
2850 * unless the lifetime of the session is tied to another
2851 * talloc'd object.
2852 * @param[in] ssl_ctx containing the base configuration for this session.
2853 * @param[in] request The current #request_t.
2854 * @param[in] client_cert Whether to require a client_cert.
2855 * @return
2856 * - A new session on success.
2857 * - NULL on error.
2858 */
2859fr_tls_session_t *fr_tls_session_alloc_server(TALLOC_CTX *ctx, SSL_CTX *ssl_ctx, request_t *request, bool client_cert)
2860{
2861 fr_tls_session_t *tls_session;
2862 int verify_mode = 0;
2863 fr_pair_t *vp;
2864 fr_tls_conf_t *conf = fr_tls_ctx_conf(ssl_ctx);
2865
2866 RDEBUG2("(TLS) Initiating new TLS session");
2867
2868 tls_session = tls_session_alloc(ctx, request, ssl_ctx);
2869 if (!tls_session) return NULL;
2870
2871 fr_tls_session_request_bind(tls_session->ssl, request); /* Is unbound in this function */
2872
2873 /*
2874 * This sets the context sessions can be resumed in.
2875 * This is to prevent sessions being created by one application
2876 * and used by another. In our case it prevents sessions being
2877 * reused between modules, or TLS server components such as
2878 * RADSEC.
2879 *
2880 * A context must always be set when doing session resumption
2881 * otherwise session resumption will fail.
2882 *
2883 * As the context ID must be <= 32, we digest the context
2884 * data with sha256.
2885 *
2886 * This seems to only be used for stateful session resumption
2887 * not session-tickets
2888 */
2889 if (conf->cache.mode != FR_TLS_TICKET_DISABLED) {
2890 char *context_id;
2891 EVP_MD_CTX *md_ctx;
2892 uint8_t digest[SHA256_DIGEST_LENGTH];
2893
2894 static_assert(sizeof(digest) <= SSL_MAX_SSL_SESSION_ID_LENGTH,
2895 "SSL_MAX_SSL_SESSION_ID_LENGTH must be >= SHA256_DIGEST_LENGTH");
2896 fr_assert(conf->cache.id_name);
2897
2898 if (tmpl_aexpand(tls_session, &context_id, request, conf->cache.id_name, NULL, NULL) < 0) {
2899 RPEDEBUG("(TLS) Failed expanding session ID");
2900 error:
2901 fr_tls_session_request_unbind(tls_session->ssl); /* Was bound in this function */
2902 talloc_free(tls_session);
2903 return NULL;
2904 }
2905
2906 MEM(md_ctx = EVP_MD_CTX_create());
2907 EVP_DigestInit_ex(md_ctx, EVP_sha256(), NULL);
2908 EVP_DigestUpdate(md_ctx, context_id, talloc_strlen(context_id));
2909 EVP_DigestFinal_ex(md_ctx, digest, NULL);
2910 EVP_MD_CTX_destroy(md_ctx);
2911 talloc_free(context_id);
2912
2913 if (!fr_cond_assert(SSL_set_session_id_context(tls_session->ssl,
2914 digest, sizeof(digest)) == 1)) goto error;
2915 }
2916
2917 /*
2918 * Add the session certificate to the session.
2919 */
2920 vp = fr_pair_find_by_da(&request->control_pairs, NULL, attr_tls_session_cert_file);
2921 if (vp) {
2922 RDEBUG2("(TLS) Loading TLS session certificate \"%pV\"", &vp->data);
2923
2924 if (SSL_use_certificate_file(tls_session->ssl, vp->vp_strvalue, SSL_FILETYPE_PEM) != 1) {
2925 fr_tls_log_perror(request, "Failed loading TLS session certificate \"%s\"",
2926 vp->vp_strvalue);
2927 goto error;
2928 }
2929
2930 if (SSL_use_PrivateKey_file(tls_session->ssl, vp->vp_strvalue, SSL_FILETYPE_PEM) != 1) {
2931 fr_tls_log_perror(request, "Failed loading TLS session certificate \"%s\"",
2932 vp->vp_strvalue);
2933 goto error;
2934 }
2935
2936 if (SSL_check_private_key(tls_session->ssl) != 1) {
2937 fr_tls_log_perror(request, "Failed validating TLS session certificate \"%s\"",
2938 vp->vp_strvalue);
2939 goto error;
2940 }
2941 /*
2942 * Better to perform explicit checks, than rely
2943 * on OpenSSL's opaque error messages.
2944 */
2945 } else {
2946 if (!conf->chains || !conf->chains[0]->private_key_file) {
2947 REDEBUG("(TLS) Server requires a private key file");
2948 fr_tls_session_error_add(request, FR_ERROR_VALUE_NO_SERVER_PRIVATE_KEY);
2949 goto error;
2950 }
2951
2952 if (!conf->chains || !conf->chains[0]->certificate_file) {
2953 REDEBUG("(TLS) Server requires a certificate file");
2954 fr_tls_session_error_add(request, FR_ERROR_VALUE_NO_SERVER_CERTIFICATE);
2955 goto error;
2956 }
2957 }
2958
2959 /** Dynamic toggle for allowing disallowing client certs
2960 *
2961 * This is mainly used for testing in environments where we can't
2962 * get test credentials for the host.
2963 */
2965 if (vp) client_cert = vp->vp_bool;
2966
2967 /*
2968 * In Server mode we only accept.
2969 *
2970 * This sets up the SSL session to work correctly with
2971 * fr_tls_session_handshake.
2972 */
2973 SSL_set_accept_state(tls_session->ssl);
2974
2975 /*
2976 * Verify the peer certificate, if asked.
2977 */
2978 if (client_cert) {
2979 RDEBUG2("(TLS) Setting verify mode to require certificate from client");
2980 verify_mode = SSL_VERIFY_PEER;
2981 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2982 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2983 }
2984 tls_session->verify_peer_cert = client_cert;
2985
2986 SSL_set_verify(tls_session->ssl, verify_mode, fr_tls_verify_cert_cb);
2987 SSL_set_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
2988
2989 /*
2990 * Datagrams need to be limited to a pre-configured MTU. So we remember that, and tell OpenSSL
2991 * to limit the MTU.
2992 */
2993 if ((tls_session->socket_type == SOCK_DGRAM) && (fr_dtls_session_init(tls_session, conf) < 0)) {
2994 goto error;
2995 }
2996
2997 SSL_CTX_set_client_hello_cb(ssl_ctx, fr_tls_session_client_hello_cb, NULL);
2998
2999 if (conf->cache.mode != FR_TLS_TICKET_DISABLED) {
3000 tls_session->allow_session_resumption = true; /* otherwise it's false */
3001 if (conf->cache.mode & FR_TLS_TICKET_STATEFUL) fr_tls_ticket_stateful_session_alloc(tls_session);
3002 }
3003
3004 fr_tls_session_request_unbind(tls_session->ssl); /* Was bound in this function */
3005
3006 return tls_session;
3007}
3008
3009static unlang_action_t tls_new_session_result(request_t *request, UNUSED void *uctx)
3010{
3011 request_t *parent = request->parent;
3012
3014
3015 /*
3016 * Copy control attributes back to the parent.
3017 */
3018 if (fr_pair_list_copy(parent->control_ctx, &parent->control_pairs, &request->control_pairs) < 0) return UNLANG_ACTION_FAIL;
3019
3021}
3022
3023unlang_action_t fr_tls_new_session_push(request_t *request, fr_tls_conf_t const *tls_conf)
3024{
3025 request_t *child;
3026 fr_value_box_t id;
3027
3028 /*
3029 * There is no session yet, so there is no ID to report.
3030 */
3032
3033 MEM(child = tls_subrequest_alloc(request, enum_tls_packet_type_new_session->vb_uint32, &id));
3034
3035 if (unlang_subrequest_child_push(NULL, child, request, true, UNLANG_SUB_FRAME) < 0) {
3036 /*
3037 * The child hasn't run, so we shouldn't call
3038 * unlang_subrequest_detach_and_free().
3039 */
3041 talloc_free(child);
3042 return UNLANG_ACTION_FAIL;
3043 }
3044
3046 NULL,
3047 tls_new_session_result,
3048 NULL, FR_SIGNAL_NONE,
3050 /*
3051 * We just pushed the child frame onto the stack.
3052 * We don't want the subrequest to execute, if we then
3053 * failed to push the function that executes after it
3054 * returns.
3055 */
3056 error:
3059 talloc_free(child);
3060 return UNLANG_ACTION_FAIL;
3061 }
3062
3063 /*
3064 * unlang_call_push() fails when the virtual server was never
3065 * compiled, not only when memory runs out. So this is a
3066 * configuration error, and is reachable.
3067 */
3068 if (unlang_call_push(NULL, child, tls_conf->virtual_server, UNLANG_SUB_FRAME) < 0) goto error;
3069
3071}
3072#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 int const char char buffer[256]
Definition acutest.h:641
void int line
Definition acutest.h:810
static uint8_t request[4]
#define IGNORE(_expr, _type)
Definition build.h:633
#define DIAG_OFF_OPTIONAL(_x)
Definition build.h:583
#define unlikely(_x)
Definition build.h:492
#define UNUSED
Definition build.h:415
#define NUM_ELEMENTS(_t)
Definition build.h:443
#define DIAG_ON_OPTIONAL(_x)
Definition build.h:584
unlang_action_t unlang_call_push(unlang_result_t *p_result, request_t *request, CONF_SECTION *server_cs, bool top_frame)
Push a virtual server CONF_SECTION as a call frame onto the stack.
Definition call.c:151
#define fr_dbuff_advance(_dbuff_or_marker, _len)
Advance 'current' position in dbuff or marker by _len bytes.
Definition dbuff.h:1121
#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:819
#define fr_dbuff_current(_dbuff_or_marker)
Return the 'current' position of a dbuff or marker.
Definition dbuff.h:963
#define fr_dbuff_init(_out, _start, _len_or_end)
Initialise an dbuff for encoding or decoding.
Definition dbuff.h:387
#define fr_dbuff_start(_dbuff_or_marker)
Return the 'start' position of a dbuff or marker.
Definition dbuff.h:950
#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:795
#define fr_dbuff_in_bytes(_dbuff_or_marker,...)
Copy a byte sequence into a dbuff or marker.
Definition dbuff.h:1518
#define fr_cond_assert(_x)
Calls panic_action ifndef NDEBUG, else logs error and evaluates to value of _x.
Definition debug.h:177
#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 fr_cond_assert_msg(_x, _fmt,...)
Calls panic_action ifndef NDEBUG, else logs error and evaluates to value of _x.
Definition debug.h:194
#define MEM(x)
Definition debug.h:38
#define ERROR(fmt,...)
Definition dhcpclient.c:40
#define DEBUG(fmt,...)
Definition dhcpclient.c:38
int unlang_function_clear(request_t *request)
Clear pending repeat function calls, and remove the signal handler.
Definition function.c:275
int unlang_function_repeat_clear(request_t *request)
Clear the pending repeat function, and keep the signal handler.
Definition function.c:309
unlang_action_t(* unlang_function_no_result_t)(request_t *request, void *uctx)
A generic function pushed by a module or xlat to functions deeper in the C call stack to create resum...
Definition function.h:68
#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)
void unlang_interpet_frame_discard(request_t *request)
Discard the bottom most frame on the request's stack.
Definition interpret.c:2763
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 REXDENT()
Exdent (unindent) R* messages by one level.
Definition log.h:460
#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 RHEXDUMP4(_data, _len, _fmt,...)
Definition log.h:725
#define RPEDEBUG(fmt,...)
Definition log.h:393
#define RHEXDUMP3(_data, _len, _fmt,...)
Definition log.h:724
#define RDEBUG4(fmt,...)
Definition log.h:361
#define RDEBUG_ENABLED4
True if request debug level 1-4 messages are enabled.
Definition log.h:353
#define RPWDEBUG2(fmt,...)
Definition log.h:384
#define REDEBUG4(fmt,...)
Definition log.h:391
#define RINDENT()
Indent R* messages by one level.
Definition log.h:447
fr_value_box_t const * enum_tls_packet_type_load_psk
HIDDEN fr_dict_attr_t const * attr_tls_packet_type
HIDDEN fr_dict_attr_t const * attr_session_resumed
HIDDEN fr_dict_attr_t const * attr_tls_session_version
HIDDEN fr_dict_attr_t const * attr_tls_alert_level
fr_value_box_t const * enum_tls_packet_type_success
HIDDEN fr_dict_attr_t const * attr_tls_psk_key
HIDDEN fr_dict_attr_t const * attr_tls_session_require_client_cert
fr_value_box_t const * enum_tls_packet_type_new_session
fr_value_box_t const * enum_tls_packet_type_establish_session
HIDDEN fr_dict_attr_t const * attr_tls_error
fr_value_box_t const * enum_tls_packet_type_fail_session
HIDDEN fr_dict_attr_t const * attr_tls_session_cipher_suite
HIDDEN fr_dict_attr_t const * attr_tls_psk_identity
HIDDEN fr_dict_attr_t const * attr_tls_alert_description
fr_value_box_t const * enum_tls_packet_type_notfound
HIDDEN fr_dict_attr_t const * attr_tls_alert
HIDDEN fr_dict_attr_t const * attr_tls_session_cert_file
@ 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
#define ROUND_UP_POW2(_num, _mul)
Round up - Only works if _mul is a power of 2 but avoids division.
Definition math.h:205
#define ROUND_UP_DIV(_x, _y)
Get the ceiling value of integer division.
Definition math.h:214
static uint8_t fr_low_bit_pos(uint64_t num)
Find the lowest order high bit in an unsigned 64 bit integer.
Definition math.h:113
unsigned int uint32_t
long int ssize_t
unsigned char uint8_t
#define UINT8_MAX
static size_t used
static uint16_t fr_nbo_to_uint16(uint8_t const data[static sizeof(uint16_t)])
Read an unsigned 16bit integer from wire format (big endian)
Definition nbo.h:146
int fr_pair_append_by_da(TALLOC_CTX *ctx, fr_pair_t **out, fr_pair_list_t *list, fr_dict_attr_t const *da)
Alloc a new fr_pair_t (and append)
Definition pair.c:1425
int fr_pair_list_copy(TALLOC_CTX *ctx, fr_pair_list_t *to, fr_pair_list_t const *from)
Duplicate a list of pairs.
Definition pair.c:2312
int fr_pair_value_strdup(fr_pair_t *vp, char const *src, bool tainted)
Copy data into an "string" data type.
Definition pair.c:2607
int fr_pair_value_from_str(fr_pair_t *vp, char const *value, size_t inlen, fr_sbuff_unescape_rules_t const *uerules, UNUSED bool tainted)
Convert string value to native attribute value.
Definition pair.c:2561
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_append(fr_pair_list_t *list, fr_pair_t *to_add)
Add a VP to the end of the list.
Definition pair.c:1306
int fr_pair_delete_by_da(fr_pair_list_t *list, fr_dict_attr_t const *da)
Delete matching pairs from the specified list.
Definition pair.c:1650
void fr_pair_list_init(fr_pair_list_t *list)
Initialise a pair list header.
Definition pair.c:47
fr_pair_t * fr_pair_copy(TALLOC_CTX *ctx, fr_pair_t const *vp)
Copy a single valuepair.
Definition pair.c:509
#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 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:52
#define request_is_detachable(_x)
Definition request.h:188
#define pair_append_request(_attr, _da)
Allocate and append a fr_pair_t to the request list.
Definition pair.h:37
#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
#define FR_SIGNAL_ALLOW(_signals)
Signal mask which blocks every signal except the ones in _signals.
Definition signal.h:58
fr_signal_t
Signals that can be generated/processed by request signal handlers.
Definition signal.h:38
@ FR_SIGNAL_NONE
No signals.
Definition signal.h:39
@ FR_SIGNAL_CANCEL
Request has been cancelled.
Definition signal.h:40
static char buff[sizeof("18446744073709551615")+3]
Definition size_tests.c:37
PUBLIC int snprintf(char *string, size_t length, char *format, va_alist)
Definition snprintf.c:689
fr_pair_t * vp
size_t strlcpy(char *dst, char const *src, size_t siz)
Definition strlcpy.c:34
Stores an attribute, a value and various bits of other data.
Definition pair.h:68
int unlang_subrequest_child_push(unlang_result_t *p_result, request_t *child, void const *unique_session_ptr, bool free_child, bool top_frame)
Push a pre-existing child back onto the stack as a subrequest.
Definition subrequest.c:440
static size_t talloc_strlen(char const *s)
Returns the length of a talloc array containing a string.
Definition talloc.h:143
static fr_slen_t parent
Definition pair.h:864
static fr_sbuff_err_t char size_t fr_sbuff_t size_t max
Definition value.h:1061
static fr_slen_t data
Definition value.h:1366
#define fr_value_box_init_null(_vb)
Initialise an empty/null box that will be filled later.
Definition value.h:640
static fr_sbuff_err_t char size_t * len
Definition value.h:1061