Radcli library 2.0.2
A simple radius library -- legacy API reference
Loading...
Searching...
No Matches
tls.c
1/*
2 * Copyright (c) 2014-2026, Nikos Mavrogiannopoulos. All rights reserved.
3 * Copyright (c) 2015, Red Hat, Inc. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include <config.h>
27#include <includes.h>
28#include <radcli/radcli.h>
29#include "util.h"
30#include "options.h"
31#include "tls.h"
32#include "session.h"
33
34#ifdef HAVE_GNUTLS
35
48
49#include <gnutls/gnutls.h>
50#include <gnutls/dtls.h>
51#include <poll.h>
52
53#define DEFAULT_DTLS_SECRET "radius/dtls"
54#define DEFAULT_TLS_SECRET "radsec"
55
56/* The credentials rc_init_tls() loaded; the session's rc_session.backend. */
57struct tls_creds {
58 gnutls_psk_client_credentials_t psk_cred;
59 gnutls_certificate_credentials_t x509_cred;
60};
61
63
64/*- GnuTLS certificate-verification callback: verify the peer's
65 * certificate chain and, unless skip_hostname_check is set, that its
66 * hostname matches.
67 *
68 * @param session the GnuTLS session being handshaked; its rc_session is
69 * read back via gnutls_session_get_ptr().
70 * @return 0 if the certificate is acceptable, GNUTLS_E_CERTIFICATE_ERROR
71 * otherwise.
72 -*/
73static int cert_verify_callback(gnutls_session_t session)
74{
75 unsigned int status;
76 int ret;
77 rc_session *ctx;
78 gnutls_datum_t out;
79
80 /* read hostname */
81 ctx = gnutls_session_get_ptr(session);
82 if (ctx == NULL)
83 return GNUTLS_E_CERTIFICATE_ERROR;
84
85 if (ctx->skip_hostname_check)
86 ret = gnutls_certificate_verify_peers2(session, &status);
87 else
88 ret = gnutls_certificate_verify_peers3(session, ctx->hostname, &status);
89 if (ret < 0) {
90 rc_log(LOG_ERR, "%s: error in certificate verification: %s",
91 __func__, gnutls_strerror(ret));
92 return GNUTLS_E_CERTIFICATE_ERROR;
93 }
94
95 if (status != 0) {
96 ret =
97 gnutls_certificate_verification_status_print(status,
98 gnutls_certificate_type_get
99 (session),
100 &out, 0);
101 if (ret < 0) {
102 return GNUTLS_E_CERTIFICATE_ERROR;
103 }
104 rc_log(LOG_INFO, "%s: certificate: %s", __func__, out.data);
105 gnutls_free(out.data);
106 return GNUTLS_E_CERTIFICATE_ERROR;
107 }
108
109 return 0;
110}
111
112/*- rc_sess_ops.start: set up a GnuTLS session on c's connected socket,
113 * for tls_handshake() to drive.
114 *
115 * @param s the session; s->backend holds the credentials.
116 * @param c the connection being opened.
117 * @param timeout the handshake timeout in seconds.
118 * @return 0 on success, -1 on failure.
119 -*/
120static int tls_start(rc_session *s, rc_sess_conn *c, int timeout)
121{
122 struct tls_creds *cr = s->backend;
123 /* GNUTLS_NONBLOCK: without it the handshake waits inside GnuTLS for
124 * its own timeouts, socket blocking or not. */
125 unsigned flags = GNUTLS_CLIENT | GNUTLS_NONBLOCK;
126 char *p;
127 int ret;
128
129 if (s->ops->datagram)
130 flags |= GNUTLS_DATAGRAM;
131 ret = gnutls_init(&c->session, flags);
132 if (ret < 0) {
133 rc_log(LOG_ERR,
134 "%s: error in gnutls_init(): %s", __func__, gnutls_strerror(ret));
135 return -1;
136 }
137
138 if (!s->ops->datagram) {
139 if (timeout > 0) {
140 gnutls_handshake_set_timeout(c->session, timeout*1000);
141 } else {
142 gnutls_handshake_set_timeout(c->session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
143 }
144 } else { /* DTLS */
145 if (timeout > 0)
146 gnutls_dtls_set_timeouts(c->session, 1000, timeout*1000);
147 }
148
149 gnutls_transport_set_int(c->session, c->sockfd);
150 gnutls_session_set_ptr(c->session, s);
151
152 p = rc_conf_str_id(s->rh, OPT_TLS_VERIFY_HOSTNAME);
153 if (p && (strcasecmp(p, "false") == 0 || strcasecmp(p, "no") == 0)) {
154 s->skip_hostname_check = 1;
155 }
156
157 if (cr->psk_cred) {
158 gnutls_credentials_set(c->session,
159 GNUTLS_CRD_PSK, cr->psk_cred);
160
161 ret = gnutls_priority_set_direct(c->session, "NORMAL:-KX-ALL:+ECDHE-PSK:+DHE-PSK:+PSK:-VERS-TLS1.0", NULL);
162 if (ret < 0) {
163 rc_log(LOG_ERR,
164 "%s: error in setting PSK priorities: %s",
165 __func__, gnutls_strerror(ret));
166 return -1;
167 }
168 } else {
169 if (cr->x509_cred) {
170 gnutls_credentials_set(c->session,
171 GNUTLS_CRD_CERTIFICATE,
172 cr->x509_cred);
173 }
174
175 gnutls_set_default_priority(c->session);
176 }
177
178 gnutls_server_name_set(c->session, GNUTLS_NAME_DNS,
179 s->hostname, strlen(s->hostname));
180
181 rc_log(LOG_DEBUG,
182 "%s: performing TLS/DTLS handshake with [%s]:%d",
183 __func__, s->hostname, s->port);
184 return 0;
185}
186
187/*- rc_sess_ops.handshake: advance the (D)TLS handshake without waiting. -*/
188static int tls_handshake(rc_sess_conn *c)
189{
190 int ret;
191
192 do {
193 ret = gnutls_handshake(c->session);
194 } while (ret < 0 && ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED &&
195 ret != GNUTLS_E_LARGE_PACKET && gnutls_error_is_fatal(ret) == 0);
196
197 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
198 return SESS_AGAIN;
199 if (ret < 0) {
200 rc_log(LOG_ERR, "%s: error in handshake: %s",
201 __func__, gnutls_strerror(ret));
202 return -1;
203 }
204
205 c->handshake_done = 1;
206 return 0;
207}
208
209/*- rc_sess_ops.handshake_wait for TLS: the direction GnuTLS last blocked
210 * in. -*/
211static int tls_handshake_wait(rc_sess_conn *c, short *events)
212{
213 *events = gnutls_record_get_direction(c->session) ? POLLOUT : POLLIN;
214 return -1;
215}
216
217/*- rc_sess_ops.handshake_wait for DTLS: also when the retransmission timer
218 * next fires, for tls_handshake() to resend a lost flight. -*/
219static int dtls_handshake_wait(rc_sess_conn *c, short *events)
220{
221 /* GnuTLS can still report "write" after a flight went out and it is
222 * waiting for the reply (gnutls#1992), and polling a writable socket
223 * for POLLOUT would spin, so trust it only if the socket is full. */
224 struct pollfd pfd = { c->sockfd, POLLOUT, 0 };
225
226 if (gnutls_record_get_direction(c->session) && poll(&pfd, 1, 0) == 0) {
227 *events = POLLOUT;
228 /* The timer reads 0 once expired, yet no retransmission can
229 * reset it until this send clears. */
230 return -1;
231 }
232 *events = POLLIN;
233 return (int)gnutls_dtls_get_timeout(c->session);
234}
235
236/*- rc_sess_ops.handshake for DTLS: dtls_handshake_wait() cannot tell a send
237 * that failed on a writable socket from a stale direction, and would leave it
238 * unsent until the retransmission timer, possibly past the attempt's deadline.
239 * Retrying sends nothing if the direction was stale. -*/
240static int dtls_handshake(rc_sess_conn *c)
241{
242 struct pollfd pfd = { c->sockfd, POLLOUT, 0 };
243 int ret = tls_handshake(c);
244
245 if (ret == SESS_AGAIN && gnutls_record_get_direction(c->session) &&
246 poll(&pfd, 1, 0) > 0)
247 ret = tls_handshake(c);
248 return ret;
249}
250
251/*- rc_sess_ops.send: one gnutls_record_send() call. -*/
252static int tls_send(rc_sess_conn *c, const void *buf, size_t len)
253{
254 int ret = gnutls_record_send(c->session, buf, len);
255
256 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
257 return SESS_AGAIN;
258 if (ret < 0) {
259 rc_log(LOG_ERR, "%s: error in sending: %s", __func__, gnutls_strerror(ret));
260 return -1;
261 }
262 return ret;
263}
264
265/*- rc_sess_ops.recv: one gnutls_record_recv() call. -*/
266static int tls_recv(rc_sess_conn *c, void *buf, size_t len)
267{
268 int ret = gnutls_record_recv(c->session, buf, len);
269
270 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
271 return SESS_AGAIN;
272 if (ret == GNUTLS_E_WARNING_ALERT_RECEIVED) {
273 rc_log(LOG_ERR, "%s: received alert: %s", __func__,
274 gnutls_alert_get_name(gnutls_alert_get(c->session)));
275 return SESS_ALERT;
276 }
277 if (ret < 0) {
278 rc_log(LOG_ERR, "%s: error in receiving: %s", __func__, gnutls_strerror(ret));
279 return -1;
280 }
281 return ret;
282}
283
284/*- rc_sess_ops.pending: whether GnuTLS holds decrypted data. -*/
285static int tls_pending(rc_sess_conn *c)
286{
287 return gnutls_record_check_pending(c->session) > 0;
288}
289
290/*- rc_sess_ops.stop: send close_notify if the handshake completed, then
291 * deinit the GnuTLS session. -*/
292static void tls_stop(rc_sess_conn *c)
293{
294 int ret;
295
296 if (c->session == NULL)
297 return;
298 /* Send close_notify before the socket closes so the peer receives a
299 * proper TLS/DTLS shutdown alert. Only valid once the handshake
300 * actually completed -- e.g. a failed connect() leaves an initialized
301 * session with no negotiated cipher state. */
302 if (c->sockfd != -1 && c->handshake_done) {
303 do {
304 ret = gnutls_bye(c->session, GNUTLS_SHUT_WR);
305 } while (ret == GNUTLS_E_INTERRUPTED);
306 }
307 gnutls_deinit(c->session);
308 c->session = NULL;
309}
310
311/*- Free cr and the credentials it holds. -*/
312static void free_creds(struct tls_creds *cr)
313{
314 if (cr == NULL)
315 return;
316 if (cr->x509_cred)
317 gnutls_certificate_free_credentials(cr->x509_cred);
318 if (cr->psk_cred)
319 gnutls_psk_free_client_credentials(cr->psk_cred);
320 free(cr);
321}
322
323/*- rc_sess_ops.free: release the session's credentials. -*/
324static void tls_free(rc_session *s)
325{
326 free_creds(s->backend);
327 s->backend = NULL;
328}
329
330static const rc_sess_ops tls_ops = {
331 .start = tls_start,
332 .handshake = tls_handshake,
333 .handshake_wait = tls_handshake_wait,
334 .send = tls_send,
335 .recv = tls_recv,
336 .pending = tls_pending,
337 .stop = tls_stop,
338 .free = tls_free,
339};
340
341static const rc_sess_ops dtls_ops = {
342 .datagram = 1,
343 .start = tls_start,
344 .handshake = dtls_handshake,
345 .handshake_wait = dtls_handshake_wait,
346 .send = tls_send,
347 .recv = tls_recv,
348 .pending = tls_pending,
349 .stop = tls_stop,
350 .free = tls_free,
351};
352
353/*- Initialize a configuration for TLS or DTLS
354 *
355 * This function will initialize the handle for TLS or DTLS.
356 *
357 * @param rh a handle to parsed configuration
358 * @param flags must be zero or SEC_FLAG_DTLS
359 * @return 0 on success, -1 on failure.
360 -*/
361int rc_init_tls(rc_handle * rh, unsigned flags)
362{
363 int ret;
364 struct tls_creds *cr = NULL;
365 const char *ca_file = rc_conf_str_id(rh, OPT_TLS_CA_FILE);
366 const char *cert_file = rc_conf_str_id(rh, OPT_TLS_CERT_FILE);
367 const char *key_file = rc_conf_str_id(rh, OPT_TLS_KEY_FILE);
368 const char *pskkey = NULL;
369 SERVER *authservers;
370 char *ns = NULL;
371 int ns_def_hdl = 0;
372
373 memset(&rh->so, 0, sizeof(rh->so));
374
375 ns = rc_conf_str_id(rh, OPT_NAMESPACE); /* Check for namespace config */
376 if (ns != NULL) {
377 if(-1 == rc_set_netns(ns, &ns_def_hdl)) {
378 rc_log(LOG_ERR, "rc_send_server: namespace %s set failed", ns);
379 return -1;
380 }
381 }
382
383 if (flags & SEC_FLAG_DTLS) {
384 rh->so_type = RC_SOCKET_DTLS;
385 rh->so.static_secret = DEFAULT_DTLS_SECRET;
386 } else {
387 rh->so_type = RC_SOCKET_TLS;
388 rh->so.static_secret = DEFAULT_TLS_SECRET;
389 }
390
391 cr = calloc(1, sizeof(*cr));
392 if (cr == NULL) {
393 ret = -1;
394 goto cleanup;
395 }
396
397 if (ca_file || (key_file && cert_file)) {
398 ret = gnutls_certificate_allocate_credentials(&cr->x509_cred);
399 if (ret < 0) {
400 ret = -1;
401 rc_log(LOG_ERR,
402 "%s: error in setting X.509 credentials: %s",
403 __func__, gnutls_strerror(ret));
404 goto cleanup;
405 }
406
407 if (ca_file) {
408 ret =
409 gnutls_certificate_set_x509_trust_file(cr->x509_cred,
410 ca_file,
411 GNUTLS_X509_FMT_PEM);
412 if (ret < 0) {
413 ret = -1;
414 rc_log(LOG_ERR,
415 "%s: error in setting X.509 trust file: %s: %s",
416 __func__, gnutls_strerror(ret), ca_file);
417 goto cleanup;
418 }
419 }
420
421 if (cert_file && key_file) {
422 ret =
423 gnutls_certificate_set_x509_key_file(cr->x509_cred,
424 cert_file,
425 key_file,
426 GNUTLS_X509_FMT_PEM);
427 if (ret < 0) {
428 ret = -1;
429 rc_log(LOG_ERR,
430 "%s: error in setting X.509 cert and key files: %s: %s - %s",
431 __func__, gnutls_strerror(ret), cert_file, key_file);
432 goto cleanup;
433 }
434 }
435
436 gnutls_certificate_set_verify_function(cr->x509_cred,
437 cert_verify_callback);
438 }
439
440 /* Read the PSK key if any */
441 authservers = rc_conf_srv_id(rh, OPT_AUTHSERVER);
442 if (authservers == NULL) {
443 rc_log(LOG_ERR,
444 "%s: cannot find authserver", __func__);
445 ret = -1;
446 goto cleanup;
447 }
448
449 if (rh->tls_psk_key != NULL) {
450 /* radcli2.h's radcli_ctx_set_tls_psk(): identity/key set directly
451 * as bytes, not parsed out of a "psk@user@hexkey" secret string --
452 * takes priority over authservers->secret[0] below if both are
453 * somehow set. */
454 gnutls_datum_t rawkey;
455
456 ret = gnutls_psk_allocate_client_credentials(&cr->psk_cred);
457 if (ret < 0) {
458 ret = -1;
459 rc_log(LOG_ERR,
460 "%s: error in setting PSK credentials: %s",
461 __func__, gnutls_strerror(ret));
462 goto cleanup;
463 }
464
465 rawkey.data = rh->tls_psk_key;
466 rawkey.size = rh->tls_psk_key_len;
467
468 ret = gnutls_psk_set_client_credentials(cr->psk_cred,
469 rh->tls_psk_identity ? rh->tls_psk_identity : "",
470 &rawkey, GNUTLS_PSK_KEY_RAW);
471 if (ret < 0) {
472 ret = -1;
473 rc_log(LOG_ERR,
474 "%s: error in setting PSK key: %s",
475 __func__, gnutls_strerror(ret));
476 goto cleanup;
477 }
478
479 goto psk_done;
480 }
481
482 {
483 /* Config-file equivalent of radcli_ctx_set_tls_psk(): identity as
484 * plain text, key as hex text (RC_OPTION_TABLE's tls-psk-identity/
485 * tls-psk-key, radcli-defs.h) -- takes priority over authservers->
486 * secret[0]'s embedded "psk@username@hexkey" form below, but not
487 * over rh->tls_psk_key set via the API call above. GNUTLS_PSK_KEY_HEX
488 * lets gnutls parse the hex text directly, so no manual decoding
489 * is needed here. */
490 const char *psk_identity = rc_conf_str_id(rh, OPT_TLS_PSK_IDENTITY);
491 const char *psk_key = rc_conf_str_id(rh, OPT_TLS_PSK_KEY);
492
493 if ((psk_identity != NULL) != (psk_key != NULL)) {
494 ret = -1;
495 rc_log(LOG_ERR,
496 "%s: tls-psk-identity and tls-psk-key must both be set",
497 __func__);
498 goto cleanup;
499 }
500
501 if (psk_identity != NULL && psk_key != NULL) {
502 gnutls_datum_t hexkey;
503
504 hexkey.data = (uint8_t *)psk_key;
505 hexkey.size = strlen(psk_key);
506
507 ret = gnutls_psk_allocate_client_credentials(&cr->psk_cred);
508 if (ret < 0) {
509 ret = -1;
510 rc_log(LOG_ERR,
511 "%s: error in setting PSK credentials: %s",
512 __func__, gnutls_strerror(ret));
513 goto cleanup;
514 }
515
516 ret = gnutls_psk_set_client_credentials(cr->psk_cred,
517 psk_identity, &hexkey,
518 GNUTLS_PSK_KEY_HEX);
519 if (ret < 0) {
520 ret = -1;
521 rc_log(LOG_ERR,
522 "%s: error in setting PSK key: %s",
523 __func__, gnutls_strerror(ret));
524 goto cleanup;
525 }
526
527 goto psk_done;
528 }
529 }
530
531 if (authservers->secret[0])
532 pskkey = authservers->secret[0];
533
534 if (pskkey && pskkey[0] != 0) {
535 char *p;
536 char username[64];
537 gnutls_datum_t hexkey;
538 int username_len;
539
540 if (strncmp(pskkey, "psk@", 4) != 0) {
541 ret = -1;
542 rc_log(LOG_ERR,
543 "%s: server secret is set but does not start with 'psk@'",
544 __func__);
545 goto cleanup;
546 }
547 pskkey+=4;
548
549 if ((p = strchr(pskkey, '@')) == NULL) {
550 ret = -1;
551 rc_log(LOG_ERR,
552 "%s: PSK key is not in 'username@hexkey' format",
553 __func__);
554 goto cleanup;
555 }
556
557 username_len = p - pskkey;
558 if (username_len + 1 > sizeof(username)) {
559 rc_log(LOG_ERR,
560 "%s: PSK username too big", __func__);
561 ret = -1;
562 goto cleanup;
563 }
564
565 strlcpy(username, pskkey, username_len + 1);
566
567 p++;
568 hexkey.data = (uint8_t*)p;
569 hexkey.size = strlen(p);
570
571 ret = gnutls_psk_allocate_client_credentials(&cr->psk_cred);
572 if (ret < 0) {
573 ret = -1;
574 rc_log(LOG_ERR,
575 "%s: error in setting PSK credentials: %s",
576 __func__, gnutls_strerror(ret));
577 goto cleanup;
578 }
579
580 ret =
581 gnutls_psk_set_client_credentials(cr->psk_cred,
582 username, &hexkey,
583 GNUTLS_PSK_KEY_HEX);
584 if (ret < 0) {
585 ret = -1;
586 rc_log(LOG_ERR,
587 "%s: error in setting PSK key: %s",
588 __func__, gnutls_strerror(ret));
589 goto cleanup;
590 }
591 }
592
593 psk_done:
594 /* The connection and handshake happen on first use. */
595 ret = radcli2_priv_sess_init(rh, (flags & SEC_FLAG_DTLS) ? &dtls_ops : &tls_ops, cr);
596 if (ret < 0)
597 goto cleanup;
598 if (ns != NULL) {
599 if(-1 == rc_reset_netns(&ns_def_hdl)) {
600 rc_log(LOG_ERR, "rc_send_server: namespace %s reset failed", ns);
601 return -1; /* the session, now owning cr, goes with rh */
602 }
603 }
604 return 0;
605 cleanup:
606 free_creds(cr);
607 if (ns != NULL) {
608 if(-1 == rc_reset_netns(&ns_def_hdl))
609 rc_log(LOG_ERR, "rc_send_server: namespace %s reset failed", ns);
610 }
611 return ret;
612}
613
614#endif /* HAVE_GNUTLS */
@ RC_SOCKET_DTLS
DTLS socket.
Definition radcli.h:115
@ RC_SOCKET_TLS
TLS socket.
Definition radcli.h:114