Radcli library 2.0.2
A simple radius library -- new API reference
Loading...
Searching...
No Matches
dae.c
1/*
2 * Copyright (C) 2026 Nikos Mavrogiannopoulos
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 */
24
28
29/* radcli2.h's RFC 5176 dynamic-authorization listener (radcli_dae_new()/
30 * _set_handler()/_start()/_free(), plus the ctx-level poll surface
31 * radcli_ctx_get_poll()/radcli_ctx_dispatch(), doc/requirements/dae.md's
32 * INIT/NET/SEC/DATA categories).
33 *
34 * radcli_dae_new() validates the dae-* configuration and resolves every
35 * dae-server entry to concrete addresses, but opens no socket
36 * (REQ-DAE-INIT-*); radcli_dae_start() does that, non-blocking and
37 * close-on-exec (REQ-DAE-SEC-010/011). There is deliberately no
38 * radcli_dae_fd(): the descriptor is exposed only via
39 * radcli_ctx_get_poll(), which operates on ctx rather than on any one
40 * radcli_dae, so a future dynamic-authorization transport that shares one
41 * descriptor with the ordinary request path (rather than a separate
42 * UDP/3799 listener) never leaves an application holding two accessors
43 * that alias the same descriptor -- see radcli_ctx_get_poll()'s doc
44 * comment in radcli2.h. radcli never calls poll()/select()/epoll_wait()
45 * itself (REQ-NET2-NET-001, REQ-GEN-SEC-003).
46 *
47 * radcli_ctx_dispatch() runs the full validation pipeline (REQ-NET2-NET-002)
48 * before ever invoking the registered radcli_dae_handler: source-address
49 * authorization, Request Authenticator, Message-Authenticator, Event-
50 * Timestamp freshness, then duplicate suppression against a fixed
51 * 256-slot table shared by every configured dae-server entry
52 * (REQ-DAE-SEC-001..006). Session-selector convenience accessors
53 * (radcli_dae_req_session_id()/_user_name()/_framed_ip()/_nas_port()/
54 * _check_nas(), doc/requirements/dae.md's DATA category) are implemented
55 * below; an application can still reach the same data via
56 * radcli_dae_req_attrs() directly instead. */
57
58#include <config.h>
59#include <includes.h>
60#include <radcli/radcli.h>
61#include <radcli/radcli2.h>
62#include "util.h"
63#include "avp.h"
64#include "options.h"
65#include "rc-crypto.h"
66#include "rc-random.h"
67#include <poll.h>
68#include <fcntl.h>
69#include <time.h>
70
71#define RADCLI_DAE_DEFAULT_PORT 3799
72/* Sane bound on the number of addresses dae-server's entries resolve to --
73 * not a protocol limit, just parse-loop hygiene against an operator config
74 * mistake (e.g. a hostname with an unexpectedly large RRset). */
75#define RADCLI_DAE_MAX_DACS 64
76
77/* Duplicate suppression is keyed on (Identifier, Request Authenticator)
78 * alone; Identifier is one octet, so this is the whole space -- a fixed
79 * table, not a cache with an eviction policy (REQ-DAE-SEC-005). RFC 5176
80 * SS2.3 names source address and source port as part of the tuple too, but
81 * neither is part of what the Request/Message-Authenticator actually hash
82 * (Code+Identifier+Length+Authenticator+Attributes+Secret): the source
83 * address is not cryptographically bound to the packet at all, so it was
84 * never real proof of anything -- only the Authenticator, keyed on the
85 * shared secret, is. One shared table per listener (not one per configured
86 * dae-server entry) follows from that: source port was dropped from the
87 * match first (an off-path attacker replaying one captured packet controls
88 * the port freely, so requiring it to match let the packet be replayed as
89 * "new" from a fresh port indefinitely); partitioning the table per
90 * configured sender address reopened the identical bypass one level up,
91 * since dae-server entries commonly share one secret (no per-entry
92 * :secret override) -- a captured packet replayed with the source address
93 * spoofed to a DIFFERENT configured entry sharing that secret still
94 * verified, but landed in that entry's own empty table and was delivered
95 * as new. A single shared table closes both: whichever configured sender
96 * the replay is spoofed as, the same dedup key lands in the same slot.
97 * (A genuine collision between two different, unrelated packets would need
98 * the 256-bit SHA-256 dedup key -- REQ-DAE-SEC-005, computed by
99 * process_packet() itself over the verified packet, not the wire's 128-bit
100 * MD5 Request Authenticator -- to coincide by chance: not a practical
101 * concern.) */
102#define RADCLI_DAE_SLOTS 256
103
104struct radcli_dae_slot {
105 unsigned valid;
106 time_t timestamp;
107 uint8_t dedup_key[RC_SHA256_DIGEST_SIZE]; /* REQ-DAE-SEC-005: an
108 * SHA-256 digest process_
109 * packet() computes itself
110 * over the verified packet
111 * -- not the wire's MD5
112 * Request Authenticator. */
113 unsigned pending; /* 1 = PENDING (awaiting an application decision) */
114 uint8_t reply_code;
115 uint32_t error_cause; /* 0 = no Error-Cause attribute (an ACK) */
116};
117
118struct radcli_dae_dac {
119 struct sockaddr_storage addr;
120 socklen_t addrlen;
121 char *secret; /* NULL => use radcli_dae_st.secret */
122};
123
124/* Fixed bound on radcli2_priv_dae_on_radsec_packet()'s queue of validated
125 * RadSec requests awaiting delivery via radcli_ctx_dispatch() -- never
126 * grown at run time, same "no unbounded packet-driven allocation"
127 * principle as RADCLI_DAE_SLOTS/RADCLI_DAE_MAX_DACS above. It fills when
128 * requests arrive faster than the application calls radcli_ctx_dispatch(),
129 * or during a blocking exchange (radcli2_priv_sess_route()); overflow
130 * drops the oldest queued entry and logs, rather than growing without
131 * limit. */
132#define RADCLI_DAE_RADSEC_QUEUE_SIZE 8
133
134struct radcli_dae_st {
135 rc_handle *rh;
136 char *secret;
137 struct radcli_dae_dac *dacs;
138 unsigned n_dacs;
139 struct radcli_dae_slot *slots; /* RADCLI_DAE_SLOTS entries, shared by
140 * every configured dae-server entry --
141 * see RADCLI_DAE_SLOTS's comment. */
142 int max_clock_skew;
143 int require_message_authenticator;
144 unsigned no_nas_check; /* RADCLI_DAE_NO_NAS_CHECK passed to radcli_dae_new() */
145 char *listen_host; /* NULL => any address */
146 int listen_port;
147 int fd;
148 radcli_dae_handler handler;
149 void *handler_user;
150
151 /* Set at construction when dae-accept=yes follows serv-type=tls/dtls
152 * (radcli_dae_new()): CoA/Disconnect flow over rh's own established
153 * TLS/DTLS session (lib/sendserver.c's radcli2_priv_sess_route(),
154 * radcli2_priv_dae_on_radsec_packet()) instead of a dae-owned UDP
155 * listener -- dacs/n_dacs/secret/listen_host/listen_port/fd above are
156 * all unused in this mode (dae->fd stays -1 throughout). */
157 unsigned radsec;
158 unsigned started; /* radcli_dae_start() already called -- radsec mode
159 * has no fd to test "already started" against. */
160
161 /* radcli2_priv_dae_on_radsec_packet()'s queue -- see
162 * RADCLI_DAE_RADSEC_QUEUE_SIZE's comment. FIFO: radsec_queue[0] is
163 * the oldest still-undelivered request. */
164 struct radcli_dae_request_st *radsec_queue[RADCLI_DAE_RADSEC_QUEUE_SIZE];
165 unsigned radsec_queue_len;
166};
167
168struct radcli_dae_request_st {
169 struct radcli_dae_st *dae;
170 struct radcli_dae_dac *dac; /* the authorized sender this arrived from */
171 uint8_t code;
172 uint8_t id;
173 uint8_t request_authenticator[AUTH_VECTOR_LEN];
174 uint8_t dedup_key[RC_SHA256_DIGEST_SIZE]; /* REQ-DAE-SEC-005: SHA-256
175 * over the verified packet,
176 * snapshotted so a later
177 * record_reply_decision()
178 * call can re-verify the
179 * slot it claimed is still
180 * this same request's. */
181 struct sockaddr_storage from;
182 socklen_t fromlen;
183 char secret[MAX_SECRET_LENGTH + 1]; /* dac->secret or dae->secret, copied in */
184 radcli_avp_list *attrs;
185 unsigned replied;
186 char *session_id; /* Acct-Session-Id, NUL-terminated; NULL if absent */
187 char *user_name; /* User-Name, NUL-terminated; NULL if absent */
188
189 /* Set when this request represents a retransmission radcli_dae_process()
190 * (L0) already matched to an ANSWERED duplicate-suppression slot: there
191 * is no new decision to make, so radcli_dae_reply()/_reply_error() are
192 * meaningless (and, for an L0-only dae with no socket, would fail
193 * outright), and radcli_dae_reply_to_buffer() reproduces the cached
194 * decision snapshotted here instead of the caller's ack/error_cause
195 * arguments -- a genuine retransmission always gets the same answer
196 * (RFC 5176 SS2.3), never a fresh one. */
197 unsigned is_cached_duplicate;
198 uint8_t cached_reply_code;
199 uint32_t cached_error_cause;
200};
201
202/*- Free a dacs array and each entry's secret.
203 *
204 * @param dacs the array to free; NULL is accepted and ignored.
205 * @param n the number of entries in dacs.
206 -*/
207static void free_dacs(struct radcli_dae_dac *dacs, unsigned n)
208{
209 unsigned i;
210
211 if (dacs == NULL)
212 return;
213 for (i = 0; i < n; i++)
214 free(dacs[i].secret);
215 free(dacs);
216}
217
218/*- Append req to dae's RadSec delivery queue (radcli2_priv_dae_on_radsec_
219 * packet(), radcli_ctx_dispatch()'s RadSec branch). If the queue is
220 * already at RADCLI_DAE_RADSEC_QUEUE_SIZE, the oldest entry is dropped
221 * (freed) and logged first -- see that constant's comment.
222 *
223 * @param dae the listener whose queue to append to.
224 * @param req the request to enqueue.
225 -*/
226static void radsec_queue_push(struct radcli_dae_st *dae, struct radcli_dae_request_st *req)
227{
228 unsigned i;
229
230 if (dae->radsec_queue_len == RADCLI_DAE_RADSEC_QUEUE_SIZE) {
231 rc_log(LOG_WARNING, "radcli_ctx_dispatch: RadSec dynamic-authorization "
232 "queue full (%u), dropping the oldest undelivered request",
233 (unsigned)RADCLI_DAE_RADSEC_QUEUE_SIZE);
234 radcli_dae_request_free((radcli_dae_request *)dae->radsec_queue[0]);
235 for (i = 1; i < dae->radsec_queue_len; i++)
236 dae->radsec_queue[i - 1] = dae->radsec_queue[i];
237 dae->radsec_queue_len--;
238 }
239 dae->radsec_queue[dae->radsec_queue_len++] = req;
240}
241
242/*- Pop and return the oldest queued RadSec request.
243 *
244 * @param dae the listener whose queue to pop from.
245 * @return the oldest queued request, or NULL if the queue is empty.
246 -*/
247static struct radcli_dae_request_st *radsec_queue_pop(struct radcli_dae_st *dae)
248{
249 struct radcli_dae_request_st *req;
250 unsigned i;
251
252 if (dae->radsec_queue_len == 0)
253 return NULL;
254 req = dae->radsec_queue[0];
255 for (i = 1; i < dae->radsec_queue_len; i++)
256 dae->radsec_queue[i - 1] = dae->radsec_queue[i];
257 dae->radsec_queue_len--;
258 return req;
259}
260
261/* Parses one "address_or_hostname[:secret]" dae-server entry. IPv6
262 * literals need bracket notation ("[addr]" or "[addr]:secret") to attach a
263 * secret unambiguously, since a bare IPv6 address itself contains colons;
264 * a bare token with zero or more than one colon is taken whole as the
265 * address, with no secret override in that form. *name and *secret are
266 * malloc()'d (*secret may come back NULL, meaning "no override"); caller
267 * frees both. Returns 0 on success, -1 on a malformed token -- including
268 * one that embeds a network prefix ('/'), which dae-server never accepts
269 * (REQ-DAE-INIT-003), or a ":secret" override longer than
270 * MAX_SECRET_LENGTH: rejected here at construction, the same as an
271 * overlong dae-secret, rather than silently truncated the first time it is
272 * used to verify a packet. */
273/*- Parse one "address_or_hostname[:secret]" dae-server entry -- see the
274 * comment above for the bracket-notation/prefix-rejection details.
275 *
276 * @param token the dae-server entry text to parse.
277 * @param name set to a malloc()'d copy of the address/hostname.
278 * @param secret set to a malloc()'d copy of the secret override, or NULL
279 * if token carries none.
280 * @return 0 on success, -1 on a malformed token.
281 -*/
282static int parse_dae_server_token(const char *token, char **name, char **secret)
283{
284 const char *close, *colon;
285 size_t namelen;
286
287 *name = NULL;
288 *secret = NULL;
289
290 if (token[0] == '\0' || strchr(token, '/') != NULL)
291 return -1;
292
293 if (token[0] == '[') {
294 close = strchr(token, ']');
295 if (close == NULL || close == token + 1)
296 return -1;
297 namelen = (size_t)(close - (token + 1));
298 *name = malloc(namelen + 1);
299 if (*name == NULL)
300 return -1;
301 memcpy(*name, token + 1, namelen);
302 (*name)[namelen] = '\0';
303
304 if (close[1] == ':') {
305 if (close[2] == '\0')
306 goto fail;
307 if (strlen(close + 2) > MAX_SECRET_LENGTH) {
308 rc_log(LOG_ERR, "radcli_dae_new: dae-server: secret override for "
309 "\"%s\" is longer than %d bytes", *name, MAX_SECRET_LENGTH);
310 goto fail;
311 }
312 *secret = strdup(close + 2);
313 if (*secret == NULL)
314 goto fail;
315 } else if (close[1] != '\0') {
316 goto fail;
317 }
318 return 0;
319 }
320
321 colon = strchr(token, ':');
322 if (colon != NULL && strchr(colon + 1, ':') == NULL) {
323 if (colon == token || colon[1] == '\0')
324 return -1;
325 namelen = (size_t)(colon - token);
326 *name = malloc(namelen + 1);
327 if (*name == NULL)
328 return -1;
329 memcpy(*name, token, namelen);
330 (*name)[namelen] = '\0';
331 if (strlen(colon + 1) > MAX_SECRET_LENGTH) {
332 rc_log(LOG_ERR, "radcli_dae_new: dae-server: secret override for "
333 "\"%s\" is longer than %d bytes", *name, MAX_SECRET_LENGTH);
334 goto fail;
335 }
336 *secret = strdup(colon + 1);
337 if (*secret == NULL)
338 goto fail;
339 return 0;
340 }
341
342 *name = strdup(token);
343 if (*name == NULL)
344 return -1;
345 return 0;
346
347fail:
348 free(*name);
349 free(*secret);
350 *name = NULL;
351 *secret = NULL;
352 return -1;
353}
354
355/* Resolves name (already stripped of any ":secret" suffix) and appends one
356 * DAC entry per resulting address, each carrying secret_override (or
357 * NULL, meaning "use dae->secret"). REQ-DAE-INIT-004: every address a
358 * hostname resolves to is authorized. */
359/*- Resolve name (already stripped of any ":secret" suffix) and append one
360 * DAC entry per resulting address -- see the comment above.
361 *
362 * @param dae the listener to append resolved DAC entries to.
363 * @param name the hostname/address to resolve.
364 * @param secret_override the per-entry secret to record, or NULL to fall
365 * back to dae->secret.
366 * @return 0 on success, -1 on failure (resolution error, allocation
367 * failure, or too many resolved addresses).
368 -*/
369static int add_dac_addrs(struct radcli_dae_st *dae, const char *name,
370 const char *secret_override)
371{
372 struct addrinfo hints, *res, *rp;
373 int err;
374 struct radcli_dae_dac *tmp;
375 unsigned added = 0;
376
377 memset(&hints, 0, sizeof(hints));
378 hints.ai_family = AF_UNSPEC;
379 hints.ai_socktype = SOCK_DGRAM;
380
381 err = getaddrinfo(name, NULL, &hints, &res);
382 if (err != 0) {
383 rc_log(LOG_ERR, "radcli_dae_new: dae-server: cannot resolve %s: %s",
384 name, gai_strerror(err));
385 return -1;
386 }
387
388 for (rp = res; rp != NULL; rp = rp->ai_next) {
389 if (dae->n_dacs >= RADCLI_DAE_MAX_DACS) {
390 rc_log(LOG_ERR, "radcli_dae_new: dae-server: too many resolved "
391 "addresses (max %d)", RADCLI_DAE_MAX_DACS);
392 freeaddrinfo(res);
393 return -1;
394 }
395 tmp = realloc(dae->dacs, (dae->n_dacs + 1) * sizeof(*tmp));
396 if (tmp == NULL) {
397 freeaddrinfo(res);
398 return -1;
399 }
400 dae->dacs = tmp;
401 memset(&dae->dacs[dae->n_dacs], 0, sizeof(*tmp));
402 memcpy(&dae->dacs[dae->n_dacs].addr, rp->ai_addr, rp->ai_addrlen);
403 dae->dacs[dae->n_dacs].addrlen = rp->ai_addrlen;
404 if (secret_override != NULL) {
405 dae->dacs[dae->n_dacs].secret = strdup(secret_override);
406 if (dae->dacs[dae->n_dacs].secret == NULL) {
407 freeaddrinfo(res);
408 return -1;
409 }
410 }
411 dae->n_dacs++;
412 added++;
413 }
414 freeaddrinfo(res);
415
416 if (added == 0) {
417 rc_log(LOG_ERR, "radcli_dae_new: dae-server: %s resolved to no addresses", name);
418 return -1;
419 }
420 return 0;
421}
422
423/*- Parse dae-listen ("[host]:port", "host:port", ":port", or an
424 * empty/NULL spec for the default).
425 *
426 * @param spec the dae-listen text to parse.
427 * @param host set to a malloc()'d host string, or NULL for "any address";
428 * caller frees.
429 * @param port set to the parsed port.
430 * @return 0 on success, -1 on a malformed spec.
431 -*/
432static int parse_dae_listen(const char *spec, char **host, int *port)
433{
434 const char *close, *colon;
435 long p;
436 char *end;
437
438 *host = NULL;
439 *port = RADCLI_DAE_DEFAULT_PORT;
440
441 if (spec == NULL || spec[0] == '\0')
442 return 0;
443
444 if (spec[0] == '[') {
445 close = strchr(spec, ']');
446 if (close == NULL || close == spec + 1)
447 return -1;
448 *host = malloc((size_t)(close - (spec + 1)) + 1);
449 if (*host == NULL)
450 return -1;
451 memcpy(*host, spec + 1, (size_t)(close - (spec + 1)));
452 (*host)[close - (spec + 1)] = '\0';
453
454 if (close[1] == ':') {
455 p = strtol(close + 2, &end, 10);
456 if (*end != '\0' || p < 0 || p > 65535)
457 goto fail;
458 *port = (int)p;
459 } else if (close[1] != '\0') {
460 goto fail;
461 }
462 return 0;
463 }
464
465 colon = strrchr(spec, ':');
466 if (colon == NULL) {
467 *host = strdup(spec);
468 if (*host == NULL)
469 return -1;
470 return 0;
471 }
472
473 if (colon != spec) {
474 *host = malloc((size_t)(colon - spec) + 1);
475 if (*host == NULL)
476 return -1;
477 memcpy(*host, spec, (size_t)(colon - spec));
478 (*host)[colon - spec] = '\0';
479 }
480 if (colon[1] != '\0') {
481 p = strtol(colon + 1, &end, 10);
482 if (*end != '\0' || p < 0 || p > 65535)
483 goto fail;
484 *port = (int)p;
485 }
486 return 0;
487
488fail:
489 free(*host);
490 *host = NULL;
491 return -1;
492}
493
513radcli_dae *radcli_dae_new(radcli_ctx *ctx, unsigned flags)
514{
515 rc_handle *rh = (rc_handle *)ctx;
516 struct radcli_dae_st *dae = NULL;
517 const char *accept_str, *secret, *server_str, *require_ma_str, *listen_str;
518 char *server_dup = NULL, *saveptr, *tok;
519 int force_udp, radsec_mode;
520
521 if (rh == NULL)
522 return NULL;
523
524 if (flags & ~(unsigned)RADCLI_DAE_NO_NAS_CHECK)
525 return NULL;
526
527 accept_str = rc_conf_str_id(rh, OPT_DAE_ACCEPT);
528 if (accept_str == NULL || strcasecmp(accept_str, "no") == 0) {
529 /* Not a misconfiguration: dae-accept unset/"no" is the documented
530 * default, and returning NULL here is how a caller learns dynamic
531 * authorization is off (REQ-DAE-INIT-001) -- no error log. */
532 return NULL;
533 }
534 if (strcasecmp(accept_str, "yes") == 0) {
535 force_udp = 0;
536 } else if (strcasecmp(accept_str, "udp") == 0) {
537 force_udp = 1;
538 } else {
539 rc_log(LOG_ERR, "radcli_dae_new: dae-accept: invalid value \"%s\" "
540 "(must be no, yes, or udp)", accept_str);
541 return NULL;
542 }
543
544 /* dae-accept=yes means "follow serv-type": under TLS/DTLS, CoA/
545 * Disconnect flow over the already-established RadSec session
546 * (RFC 6614 SS2.1/SS2.5, RFC 7360 SS3.1: one port, one connection,
547 * every packet type) instead of a separate RFC 5176/UDP listener.
548 * dae-accept=udp always forces the RFC 5176/UDP listener regardless
549 * of serv-type -- kept as a fully supported, documented option (not
550 * a deprecated fallback): the shared-connection RadSec path above is
551 * new and, unlike the UDP listener, not yet validated against
552 * real-world DACs. */
553 radsec_mode = (!force_udp && (rh->so_type == RC_SOCKET_TLS || rh->so_type == RC_SOCKET_DTLS));
554
555 if (rh->active_dae != NULL) {
556 rc_log(LOG_ERR, "radcli_dae_new: a radcli_dae is already active on this context");
557 return NULL;
558 }
559
560 if (radsec_mode) {
561 /* REQ-DAE-INIT-007: under RadSec there is no dae-server source
562 * ACL -- the TLS/DTLS peer's verified identity is the sole
563 * authorization for who may send a CoA/Disconnect-Request, so
564 * construction must refuse if that verification is disabled. */
565 const char *verify_str = rc_conf_str_id(rh, OPT_TLS_VERIFY_HOSTNAME);
566
567 if (verify_str != NULL &&
568 (strcasecmp(verify_str, "false") == 0 || strcasecmp(verify_str, "no") == 0)) {
569 rc_log(LOG_ERR, "radcli_dae_new: dae-accept=yes under serv-type "
570 "tls/dtls needs tls-verify-hostname enabled: RadSec's "
571 "verified peer identity is what authorizes a "
572 "CoA/Disconnect-Request sender, replacing dae-server");
573 return NULL;
574 }
575
576 /* REQ-DAE-INIT-008: inapplicable under RadSec (the secret is the
577 * RFC 6614/7360 fixed string, the authorized sender is the TLS
578 * peer, and there is no dae-owned listener to bind) -- warn, but
579 * do not fail, so switching serv-type to tls/dtls is a config
580 * change an operator can make incrementally. */
581 {
582 static const struct {
583 rc_option_id id;
584 const char *name;
585 } inapplicable[] = {
586 { OPT_DAE_LISTEN, "dae-listen" },
587 { OPT_DAE_SERVER, "dae-server" },
588 { OPT_DAE_SECRET, "dae-secret" },
589 { OPT_DAE_REQUIRE_MESSAGE_AUTHENTICATOR, "dae-require-message-authenticator" }
590 };
591 unsigned i;
592
593 for (i = 0; i < sizeof(inapplicable) / sizeof(inapplicable[0]); i++) {
594 const char *v = rc_conf_str_id(rh, inapplicable[i].id);
595
596 if (v != NULL && v[0] != '\0')
597 rc_log(LOG_WARNING, "radcli_dae_new: %s is set but has no "
598 "effect under serv-type tls/dtls (RadSec replaces "
599 "it)", inapplicable[i].name);
600 }
601 }
602
603 dae = calloc(1, sizeof(*dae));
604 if (dae == NULL)
605 return NULL;
606 dae->rh = rh;
607 dae->fd = -1;
608 dae->radsec = 1;
609 dae->no_nas_check = (flags & RADCLI_DAE_NO_NAS_CHECK) != 0;
610
611 /* REQ-DAE-INIT-005: still needed under RadSec -- Event-Timestamp
612 * freshness and duplicate suppression are replay protections
613 * independent of the transport's source-authorization model. */
614 dae->slots = calloc(RADCLI_DAE_SLOTS, sizeof(*dae->slots));
615 if (dae->slots == NULL)
616 goto fail;
617
618 dae->max_clock_skew = rc_conf_int_id(rh, OPT_DAE_MAX_CLOCK_SKEW);
619 if (dae->max_clock_skew < 0) {
620 rc_log(LOG_ERR, "radcli_dae_new: dae-max-clock-skew must not be negative");
621 goto fail;
622 }
623
624 rh->active_dae = dae;
625 return (radcli_dae *)dae;
626 }
627
628 secret = rc_conf_str_id(rh, OPT_DAE_SECRET);
629 server_str = rc_conf_str_id(rh, OPT_DAE_SERVER);
630 if (secret == NULL || secret[0] == '\0' || server_str == NULL || server_str[0] == '\0') {
631 rc_log(LOG_ERR, "radcli_dae_new: dae-accept is enabled but dae-server "
632 "and/or dae-secret is not set");
633 return NULL;
634 }
635 if (strlen(secret) > MAX_SECRET_LENGTH) {
636 rc_log(LOG_ERR, "radcli_dae_new: dae-secret is longer than %d bytes",
637 MAX_SECRET_LENGTH);
638 return NULL;
639 }
640
641 dae = calloc(1, sizeof(*dae));
642 if (dae == NULL)
643 return NULL;
644 dae->rh = rh;
645 dae->fd = -1;
646 dae->no_nas_check = (flags & RADCLI_DAE_NO_NAS_CHECK) != 0;
647
648 dae->secret = strdup(secret);
649 if (dae->secret == NULL)
650 goto fail;
651
652 server_dup = strdup(server_str);
653 if (server_dup == NULL)
654 goto fail;
655
656 for (tok = strtok_r(server_dup, ",", &saveptr); tok != NULL;
657 tok = strtok_r(NULL, ",", &saveptr)) {
658 char *name = NULL, *secret_override = NULL;
659 int ret;
660
661 while (*tok == ' ' || *tok == '\t')
662 tok++;
663
664 if (parse_dae_server_token(tok, &name, &secret_override) != 0) {
665 rc_log(LOG_ERR, "radcli_dae_new: dae-server: invalid entry \"%s\"", tok);
666 goto fail;
667 }
668
669 ret = add_dac_addrs(dae, name, secret_override);
670 free(name);
671 free(secret_override);
672 if (ret != 0)
673 goto fail;
674 }
675 free(server_dup);
676 server_dup = NULL;
677
678 if (dae->n_dacs == 0) {
679 rc_log(LOG_ERR, "radcli_dae_new: dae-server produced no authorized senders");
680 goto fail;
681 }
682
683 /* REQ-DAE-INIT-005: allocated once, here, at construction -- never
684 * grown, evicted, or resized at run time. Shared across every
685 * configured dae-server entry (RADCLI_DAE_SLOTS's comment explains
686 * why partitioning per entry is the wrong design). */
687 dae->slots = calloc(RADCLI_DAE_SLOTS, sizeof(*dae->slots));
688 if (dae->slots == NULL)
689 goto fail;
690
691 dae->max_clock_skew = rc_conf_int_id(rh, OPT_DAE_MAX_CLOCK_SKEW);
692 if (dae->max_clock_skew < 0) {
693 rc_log(LOG_ERR, "radcli_dae_new: dae-max-clock-skew must not be negative");
694 goto fail;
695 }
696
697 require_ma_str = rc_conf_str_id(rh, OPT_DAE_REQUIRE_MESSAGE_AUTHENTICATOR);
698 dae->require_message_authenticator =
699 (require_ma_str != NULL && strcasecmp(require_ma_str, "yes") == 0);
700
701 listen_str = rc_conf_str_id(rh, OPT_DAE_LISTEN);
702 if (parse_dae_listen(listen_str, &dae->listen_host, &dae->listen_port) != 0) {
703 rc_log(LOG_ERR, "radcli_dae_new: dae-listen: invalid value \"%s\"",
704 listen_str ? listen_str : "");
705 goto fail;
706 }
707
708 rh->active_dae = dae;
709 return (radcli_dae *)dae;
710
711fail:
712 free(server_dup);
714 return NULL;
715}
716
724{
725
726 if (dae == NULL)
727 return;
728 dae->handler = cb;
729 dae->handler_user = user;
730}
731
732/* Sets O_NONBLOCK and FD_CLOEXEC on fd. A datagram discarded by the kernel
733 * between the readiness report and the read -- or a second reader draining
734 * it first -- must not block the application's entire event loop inside a
735 * library that never owns it (REQ-GEN-SEC-003); FD_CLOEXEC keeps a
736 * library-opened descriptor from leaking across exec() in an application
737 * that spawns children (REQ-GEN-SEC-004's ambient-state family). Matches
738 * lib/tls.c's fcntl()-based style rather than the SOCK_NONBLOCK/SOCK_CLOEXEC
739 * socket() flags, for portability. */
740/*- Set O_NONBLOCK and FD_CLOEXEC on fd -- see the comment above for why.
741 * Shared with lib/sendserver.c's persistent UDP request socket
742 * (REQ-NET2-SEND-016), which needs the identical non-blocking-drain
743 * property for the same reason (radcli2_priv_reqreg_drain() loops
744 * recvfrom() until EAGAIN; a blocking socket would hang the caller's
745 * whole event loop on the last, empty call instead).
746 *
747 * @param fd the descriptor to modify.
748 * @return 0 on success, -1 on failure.
749 -*/
750int radcli2_priv_set_nonblock_cloexec(int fd)
751{
752 int flags;
753
754 flags = fcntl(fd, F_GETFL, 0);
755 if (flags == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
756 return -1;
757 flags = fcntl(fd, F_GETFD, 0);
758 if (flags == -1 || fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
759 return -1;
760 return 0;
761}
762
768{
769 struct addrinfo hints, *res, *rp;
770 int err, fd = -1;
771 char portstr[8];
772 char addr_txt[NI_MAXHOST] = "?";
773
774 if (dae == NULL)
775 return -1;
776 if (dae->started) {
777 rc_log(LOG_ERR, "radcli_dae_start: already started");
778 return -1;
779 }
780
781 if (dae->radsec) {
782 /* No dae-owned socket to bind: force rh's own TLS/DTLS handshake
783 * now rather than waiting for the first ordinary rc_auth()/
784 * rc_acct() call, so enabling DAE makes the NAS reachable
785 * immediately -- matching the UDP listener's own immediate
786 * bind() below. */
787 if (radcli2_priv_sess_ensure_connected(dae->rh) != 0) {
788 rc_log(LOG_ERR, "radcli_dae_start: could not establish the "
789 "RadSec (TLS/DTLS) session");
790 return -1;
791 }
792 dae->started = 1;
793 return 0;
794 }
795
796 snprintf(portstr, sizeof(portstr), "%d", dae->listen_port);
797
798 memset(&hints, 0, sizeof(hints));
799 hints.ai_family = AF_UNSPEC;
800 hints.ai_socktype = SOCK_DGRAM;
801 hints.ai_flags = AI_PASSIVE;
802
803 err = getaddrinfo(dae->listen_host, portstr, &hints, &res);
804 if (err != 0) {
805 rc_log(LOG_ERR, "radcli_dae_start: dae-listen: %s", gai_strerror(err));
806 return -1;
807 }
808
809 for (rp = res; rp != NULL; rp = rp->ai_next) {
810 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
811 if (fd == -1)
812 continue;
813 if (radcli2_priv_set_nonblock_cloexec(fd) != 0) {
814 close(fd);
815 fd = -1;
816 continue;
817 }
818 if (bind(fd, rp->ai_addr, rp->ai_addrlen) == 0) {
819 getnameinfo(rp->ai_addr, rp->ai_addrlen, addr_txt, sizeof(addr_txt),
820 NULL, 0, NI_NUMERICHOST);
821 break;
822 }
823 close(fd);
824 fd = -1;
825 }
826 freeaddrinfo(res);
827
828 if (fd == -1) {
829 rc_log(LOG_ERR, "radcli_dae_start: bind: %s", strerror(errno));
830 return -1;
831 }
832
833 /* Diagnostic only: with dae-listen unset, getaddrinfo(AI_PASSIVE)'s
834 * candidate order decides which single address family gets bound
835 * (radcli_dae_start() binds exactly one socket, matching
836 * radcli_ctx_get_poll()'s one-descriptor contract), which is easy to
837 * mistake for "the listener isn't receiving anything" if left silent. */
838 rc_log(LOG_INFO, "radcli_dae_start: listening on %s port %d", addr_txt, dae->listen_port);
839
840 dae->fd = fd;
841 dae->started = 1;
842 return 0;
843}
844
850{
851 unsigned i;
852
853 if (dae == NULL)
854 return;
855 if (dae->rh != NULL && dae->rh->active_dae == dae)
856 dae->rh->active_dae = NULL;
857 /* Under RadSec, dae->fd is always -1: the TLS/DTLS session belongs to
858 * ordinary request handling (rc_init_tls()/lib/tls.c) and outlives
859 * this radcli_dae -- there is nothing dae-owned to close here. */
860 if (dae->fd != -1)
861 close(dae->fd);
862 for (i = 0; i < dae->radsec_queue_len; i++)
863 radcli_dae_request_free((radcli_dae_request *)dae->radsec_queue[i]);
864 free_dacs(dae->dacs, dae->n_dacs);
865 free(dae->slots);
866 free(dae->secret);
867 free(dae->listen_host);
868 free(dae);
869}
870
871/* Milliseconds until watchdog-interval elapses for an established RadSec
872 * ctx (REQ-WATCHDOG-NET-002), or -1 if disabled/not applicable. Shared by
873 * radcli_ctx_get_poll() (below) and radcli_ctx_dispatch() (the actual due
874 * check that triggers radcli2_priv_dae_send_watchdog()), so the two agree
875 * on exactly the same deadline. */
876static int watchdog_deadline_ms(rc_handle *rh, int fd)
877{
878 int interval;
879
880 if (fd == -1)
881 /* An unestablished session (radcli2_priv_sess_last_msg() reports
882 * 0) must not be reported as an overdue watchdog, which would
883 * otherwise busy-loop a caller not yet polling this fd. */
884 return -1;
885
886 interval = rc_conf_int_id(rh, OPT_WATCHDOG_INTERVAL);
887 if (interval > 0) {
888 time_t last = radcli2_priv_sess_last_msg(rh);
889 long elapsed_ms, remaining_ms;
890
891 /* A skipped or still-queued watchdog counts as this round's
892 * attempt, so the caller is not told to dispatch again at once. */
893 if (rh->watchdog_skipped > last)
894 last = rh->watchdog_skipped;
895 elapsed_ms = (long)(time(0) - last) * 1000L;
896 remaining_ms = (long)interval * 1000L - elapsed_ms;
897
898 return (remaining_ms > 0) ? (int)remaining_ms : 0;
899 }
900 return -1;
901}
902
903/* Folds a new candidate deadline into *timeout_ms (the running minimum;
904 * negative candidates -- "no timeout needed" -- are ignored). */
905static void fold_timeout(int *timeout_ms, int candidate)
906{
907 if (candidate < 0)
908 return;
909 if (*timeout_ms < 0 || candidate < *timeout_ms)
910 *timeout_ms = candidate;
911}
912
960int radcli_ctx_get_poll(radcli_ctx *ctx, struct pollfd *pfds, size_t max_pfds,
961 size_t *nfds, int *timeout_ms)
962{
963 rc_handle *rh = (rc_handle *)ctx;
964 size_t n = 0;
965
966 if (rh == NULL || pfds == NULL || nfds == NULL || timeout_ms == NULL)
967 return -1;
968 if (max_pfds < RADCLI_CTX_MAX_POLLFDS)
969 return -1;
970
971 *timeout_ms = -1;
972
973 if (rh->so_type == RC_SOCKET_TLS || rh->so_type == RC_SOCKET_DTLS) {
974 /* Reported for any established RadSec radcli_ctx, whether or not
975 * dynamic authorization is active on it: the watchdog machinery
976 * below (REQ-WATCHDOG-NET-001/002) is a property of the TLS/DTLS
977 * session itself (keeping a NAT/firewall mapping alive, or just
978 * avoiding a rehandshake after an idle period), not of DAE -- an
979 * application using radcli purely as an ordinary rc_auth()/
980 * rc_acct() RadSec client, with no radcli_dae at all, is as
981 * entitled to it as one with dae-accept=yes. */
982 int dae_radsec = (rh->active_dae != NULL && rh->active_dae->radsec);
983 short events;
984 int sess_timeout_ms;
985 int fd = radcli2_priv_sess_poll(rh, &events, &sess_timeout_ms);
986
987 if (fd != -1) {
988 pfds[n].fd = fd;
989 pfds[n].events = events;
990 pfds[n].revents = 0;
991 n++;
992 }
993
994 /* A record already pulled off the wire by an in-flight ordinary
995 * request (radcli2_priv_sess_route()) may be sitting queued
996 * with no further fd activity to prompt a redispatch -- ask the
997 * caller back promptly rather than only on the next POLLIN.
998 * DAE-only, same reason as above. */
999 if (dae_radsec && rh->active_dae->radsec_queue_len > 0)
1000 *timeout_ms = 0;
1001 else
1002 fold_timeout(timeout_ms, watchdog_deadline_ms(rh, radcli2_priv_sess_fd(rh)));
1003
1004 fold_timeout(timeout_ms, radcli2_priv_reqreg_earliest_deadline_ms(rh));
1005 /* A connection attempt's deadline, or a record GnuTLS already
1006 * holds, which raises no POLLIN. */
1007 fold_timeout(timeout_ms, sess_timeout_ms);
1008
1009 *nfds = n;
1010 return 0;
1011 }
1012
1013 /* UDP/TCP: the DAE listener (if active) and the request path -- the
1014 * shared UDP request-registry socket (if any RADCLI_REQUEST_SENDONLY
1015 * exchange has ever used one) or the TCP connection (once established)
1016 * -- are genuinely different local sockets; report both when present. */
1017 if (rh->active_dae != NULL && rh->active_dae->fd != -1) {
1018 pfds[n].fd = rh->active_dae->fd;
1019 pfds[n].events = POLLIN;
1020 pfds[n].revents = 0;
1021 n++;
1022 }
1023 if (rh->so_type == RC_SOCKET_TCP) {
1024 short events;
1025 int sess_timeout_ms;
1026 int fd = radcli2_priv_sess_poll(rh, &events, &sess_timeout_ms);
1027
1028 if (fd != -1) {
1029 pfds[n].fd = fd;
1030 pfds[n].events = events;
1031 pfds[n].revents = 0;
1032 n++;
1033 }
1034 fold_timeout(timeout_ms, sess_timeout_ms);
1035 } else if (rh->req_fd != -1) {
1036 pfds[n].fd = rh->req_fd;
1037 pfds[n].events = POLLIN;
1038 pfds[n].revents = 0;
1039 n++;
1040 }
1041
1042 /* No DAE-proactive timer needed: the duplicate-suppression table
1043 * expires slots lazily, on next access, rather than on a schedule --
1044 * radcli owns no timer (REQ-GEN-SEC-003). Only an in-flight
1045 * RADCLI_REQUEST_SENDONLY exchange contributes a deadline on UDP. */
1046 fold_timeout(timeout_ms, radcli2_priv_reqreg_earliest_deadline_ms(rh));
1047
1048 *nfds = n;
1049 return 0;
1050}
1051
1112int radcli2_priv_dae_send_watchdog(radcli_ctx *ctx)
1113{
1114 rc_handle *rh = (rc_handle *)ctx;
1115 uint8_t send_buffer[RC_BUFFER_LEN];
1116 unsigned char vector[AUTH_VECTOR_LEN];
1117 char secret[MAX_SECRET_LENGTH + 1];
1118 radcli_avp_list *empty;
1119 int total_length;
1120 uint8_t id;
1121 int slot;
1122 int ret;
1123
1124 if (rh == NULL)
1125 return -1;
1126
1127 if (rh->so_type != RC_SOCKET_TLS && rh->so_type != RC_SOCKET_DTLS)
1128 return -1;
1129
1130 if (radcli2_priv_sess_fd(rh) == -1)
1131 return -1; /* not established -- see radcli2_priv_sess_ensure_connected() */
1132
1133 {
1134 int interval = rc_conf_int_id(rh, OPT_WATCHDOG_INTERVAL);
1135
1136 if (interval > 0 &&
1137 (double)(time(0) - radcli2_priv_sess_last_recv(rh)) >= interval * 2.5) {
1138 rc_log(LOG_WARNING, "radcli2_priv_dae_send_watchdog: no record received in "
1139 "%.1fx watchdog-interval -- presuming the peer dead "
1140 "and reconnecting", 2.5);
1141 /* Only begins reconnecting: the watchdog below is queued
1142 * for the new connection (REQ-NET2-NET-001). */
1143 if (radcli2_priv_sess_force_reconnect(rh) < 0)
1144 return -1;
1145 }
1146 }
1147
1148 if (rh->so.static_secret == NULL)
1149 return -1;
1150 strlcpy(secret, rh->so.static_secret, sizeof(secret));
1151
1152 /* radcli_avp_encode() (via radcli_encode_request()) rejects a NULL
1153 * list outright -- RFC 5997 Status-Server needs no attributes but
1154 * Message-Authenticator, but "no attributes" still means an empty
1155 * list, not a NULL one. */
1156 empty = radcli_avp_list_new();
1157 if (empty == NULL)
1158 return -1;
1159
1160 /* A new watchdog supersedes the previous one's Identifier
1161 * (REQ-NET2-SEND-010). */
1162 radcli2_priv_reqreg_release(rh, rh->watchdog_slot);
1163 rh->watchdog_slot = -1;
1164 if (radcli2_priv_reqreg_pick_id(rh, &id, &slot) != 0) {
1165 radcli_avp_list_free(empty);
1166 rh->watchdog_skipped = time(0);
1167 return -1;
1168 }
1169
1170 ret = radcli_encode_request(rh, PW_STATUS_SERVER, empty, secret,
1171 send_buffer, id, vector, &total_length);
1172 radcli_avp_list_free(empty);
1173 if (ret < 0) {
1174 radcli2_priv_reqreg_release(rh, slot);
1175 return -1;
1176 }
1177
1178 ret = radcli2_priv_sess_send_queued(rh, send_buffer, (size_t)total_length,
1179 RADSEC_SEND_WATCHDOG, -1);
1180 if (ret >= 0)
1181 rh->watchdog_slot = slot; /* sent, or queued to go out */
1182 else
1183 radcli2_priv_reqreg_release(rh, slot);
1184 /* A queued watchdog does not advance last_msg until it goes out. */
1185 if (ret == 0 || ret == -2)
1186 rh->watchdog_skipped = time(0);
1187 return ret;
1188}
1189
1190/* If sa is an IPv4-mapped IPv6 address ("::ffff:a.b.c.d"), extracts the
1191 * mapped IPv4 address into *out and returns 1; otherwise returns 0. A
1192 * dual-stack AF_INET6 listening socket (the default unless the platform
1193 * sets IPV6_V6ONLY) delivers an IPv4 sender's packet this way, with
1194 * from->sa_family == AF_INET6 -- see find_dac()'s use of this. */
1195/*- Extract an IPv4-mapped IPv6 address's IPv4 part -- see the comment
1196 * above.
1197 *
1198 * @param sa the address to check.
1199 * @param out set to the mapped IPv4 address, if sa is one.
1200 * @return 1 if sa is an IPv4-mapped IPv6 address (out set), 0 otherwise.
1201 -*/
1202static int get_v4_mapped(const struct sockaddr *sa, struct in_addr *out)
1203{
1204 const struct sockaddr_in6 *sin6;
1205
1206 if (sa->sa_family != AF_INET6)
1207 return 0;
1208 sin6 = (const struct sockaddr_in6 *)sa;
1209 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
1210 return 0;
1211 memcpy(out, &sin6->sin6_addr.s6_addr[12], sizeof(*out));
1212 return 1;
1213}
1214
1215/* Finds the configured DAC matching from's address (port ignored: the
1216 * DAC's source port varies per request, only the address is part of its
1217 * identity -- REQ-DAE-SEC-001). Returns NULL if from is not authorized. */
1218/*- Find the configured DAC matching from's address -- see the comment
1219 * above.
1220 *
1221 * @param dae the listener whose DAC list to search.
1222 * @param from the sender's address to match.
1223 * @return the matching DAC, or NULL if from is not authorized.
1224 -*/
1225static struct radcli_dae_dac *find_dac(struct radcli_dae_st *dae,
1226 const struct sockaddr *from)
1227{
1228 unsigned i;
1229 struct in_addr mapped;
1230 int have_mapped = get_v4_mapped(from, &mapped);
1231
1232 for (i = 0; i < dae->n_dacs; i++) {
1233 const struct sockaddr *caddr = (const struct sockaddr *)&dae->dacs[i].addr;
1234
1235 if (caddr->sa_family == from->sa_family) {
1236 if (memcmp(SA_GET_INADDR(caddr), SA_GET_INADDR(from), SA_GET_INLEN(from)) == 0)
1237 return &dae->dacs[i];
1238 continue;
1239 }
1240 /* from is AF_INET6 but mapped from an IPv4 sender: also try
1241 * it against an AF_INET dae-server entry, or every packet
1242 * from an authorized IPv4 DAC is silently unreachable on a
1243 * dual-stack listener. */
1244 if (have_mapped && caddr->sa_family == AF_INET &&
1245 memcmp(&((const struct sockaddr_in *)caddr)->sin_addr, &mapped,
1246 sizeof(mapped)) == 0)
1247 return &dae->dacs[i];
1248 }
1249 return NULL;
1250}
1251
1252/* Returns a malloc()'d, NUL-terminated copy of attrs' first name attribute's
1253 * value, or NULL if the dictionary lacks name, attrs carries none, or
1254 * allocation failed. Used to populate radcli_dae_request_st's
1255 * session_id/user_name fields once, at receive time, since
1256 * radcli_avp_get_bytes() returns unterminated wire bytes and
1257 * radcli_dae_req_session_id()/_user_name() must return a C string. */
1258/*- Return a malloc()'d, NUL-terminated copy of attrs' first attrid
1259 * attribute's value -- see the comment above for why this exists.
1260 *
1261 * @param rh a handle to parsed configuration.
1262 * @param attrs the attribute list to search.
1263 * @param attrid the attribute ID to look up and copy.
1264 * @return the copied string, or NULL if the dictionary lacks attrid,
1265 * attrs carries none, or allocation failed.
1266 -*/
1267static char *dup_avp_str(rc_handle *rh, const radcli_avp_list *attrs, uint32_t attrid)
1268{
1269 const radcli_attr_def *d = radcli_dict_lookup_num(rh, attrid, 0);
1270 const radcli_avp *a;
1271 const void *val;
1272 size_t len;
1273 char *s;
1274
1275 if (d == NULL)
1276 return NULL;
1277 a = radcli_avp_get(attrs, d, 0);
1278 if (a == NULL || radcli_avp_get_bytes(a, &val, &len) != 0)
1279 return NULL;
1280 s = malloc(len + 1);
1281 if (s == NULL)
1282 return NULL;
1283 memcpy(s, val, len);
1284 s[len] = '\0';
1285 return s;
1286}
1287
1288/* Verifies buf[0..length)'s Request Authenticator (buf[4..20)) per RFC 5176
1289 * SS2.3 (as specified for Accounting-Request, RFC 2866 SS4.1):
1290 * MD5(Code+Identifier+Length+16 zero octets+Attributes+Secret) must equal
1291 * the received field. Constant-time comparison (REQ-DAE-SEC-002). buf must
1292 * be at least length + strlen(secret) bytes writable (the caller's receive
1293 * buffer, per the same convention lib/sendserver.c's request-building uses
1294 * to append the secret before hashing). */
1295/*- Verify buf[0..length)'s Request Authenticator -- see the comment above.
1296 *
1297 * @param buf the received packet; temporarily modified and restored.
1298 * Must be at least length + strlen(secret) bytes writable.
1299 * @param length buf's length in bytes.
1300 * @param secret the shared secret.
1301 * @return 0 if the authenticator is valid, -1 otherwise.
1302 -*/
1303static int verify_request_authenticator(uint8_t *buf, size_t length, const char *secret)
1304{
1305 uint8_t received[AUTH_VECTOR_LEN];
1306 uint8_t calc[AUTH_VECTOR_LEN];
1307 size_t secretlen = rc_secret_len(secret);
1308
1309 if (length < AUTH_HDR_LEN)
1310 return -1;
1311
1312 memcpy(received, buf + 4, AUTH_VECTOR_LEN);
1313 memset(buf + 4, 0, AUTH_VECTOR_LEN);
1314 memcpy(buf + length, secret, secretlen);
1315 rc_md5_calc(calc, buf, length + secretlen);
1316 memcpy(buf + 4, received, AUTH_VECTOR_LEN); /* restore: buf is the caller's receive buffer */
1317
1318 return rc_memcmp(received, calc, AUTH_VECTOR_LEN) == 0 ? 0 : -1;
1319}
1320
1321/* Encodes reply_code (already the concrete 41/42/44/45 code) with
1322 * error_cause as attribute 101 when non-zero, mirroring every Proxy-State
1323 * from the request, Message-Authenticator, and a Response Authenticator
1324 * computed over req's own Request Authenticator (RFC 5176 SS2.3,
1325 * REQ-DAE-SEC-008). Shared by send_reply() (which then sends the bytes
1326 * over req->dae->fd) and radcli_dae_reply_to_buffer() (which hands them
1327 * to the caller instead). */
1328/*- Build req's reply into out_buf.
1329 *
1330 * @param req the request to reply to.
1331 * @param reply_code the concrete RADIUS reply code to send.
1332 * @param error_cause a radcli_error_cause value to encode as attribute
1333 * 101, or 0 for none.
1334 * @param out_buf destination buffer for the encoded reply.
1335 * @param out_cap out_buf's capacity in bytes.
1336 * @param out_len set to the reply's encoded length on success.
1337 * @return 0 on success, -1 on failure (e.g. out_cap too small).
1338 -*/
1339static int build_reply(struct radcli_dae_request_st *req, uint8_t reply_code, uint32_t error_cause,
1340 uint8_t *out_buf, size_t out_cap, int *out_len)
1341{
1342 rc_handle *rh = req->dae->rh;
1343 AUTH_HDR *auth = (AUTH_HDR *)out_buf;
1344 radcli_avp_list *reply_attrs;
1345 const radcli_avp *a;
1346 const radcli_attr_def *d_proxy_state;
1347 int encoded_len, total_length;
1348 size_t secretlen;
1349 uint8_t digest[AUTH_VECTOR_LEN];
1350
1351 /* Header, plus room for the Message-Authenticator add_msg_auth_attr()
1352 * always appends below, must fit before out_cap - AUTH_HDR_LEN -
1353 * (2 + MD5_DIGEST_SIZE) is computed for radcli_avp_encode()'s
1354 * buflen just below: with only the old `out_cap < AUTH_HDR_LEN`
1355 * guard, an out_cap in [AUTH_HDR_LEN, AUTH_HDR_LEN + 2 +
1356 * MD5_DIGEST_SIZE) made that subtraction wrap to a huge size_t
1357 * instead of failing cleanly. */
1358 if (out_cap < (size_t)(AUTH_HDR_LEN + 2 + MD5_DIGEST_SIZE))
1359 return -1;
1360
1361 reply_attrs = radcli_avp_list_new();
1362 if (reply_attrs == NULL)
1363 return -1;
1364
1365 if (error_cause != 0) {
1366 const radcli_attr_def *d_ec = radcli_dict_lookup_num(rh, PW_ERROR_CAUSE, 0);
1367
1368 if (d_ec != NULL)
1369 radcli_avp_add_uint32(reply_attrs, d_ec, error_cause);
1370 }
1371
1372 d_proxy_state = radcli_dict_lookup_num(rh, PW_PROXY_STATE, 0);
1373 if (d_proxy_state != NULL) {
1374 radcli_avp_iter it = radcli_avp_list_iter(req->attrs);
1375
1376 while ((a = radcli_avp_iter_next(&it)) != NULL) {
1377 const void *val;
1378 size_t len;
1379
1380 if (radcli_avp_def(a) != d_proxy_state)
1381 continue;
1382 if (radcli_avp_get_bytes(a, &val, &len) == 0)
1383 radcli_avp_add_bytes(reply_attrs, d_proxy_state, val, len);
1384 }
1385 }
1386
1387 auth->code = reply_code;
1388 auth->id = req->id;
1389 memcpy(auth->vector, req->request_authenticator, AUTH_VECTOR_LEN);
1390
1391 encoded_len = radcli_avp_encode(rh, reply_attrs, req->secret, req->request_authenticator,
1392 auth->data, out_cap - AUTH_HDR_LEN - (2 + MD5_DIGEST_SIZE), NULL);
1393 radcli_avp_list_free(reply_attrs);
1394 if (encoded_len < 0)
1395 return -1;
1396
1397 total_length = AUTH_HDR_LEN + encoded_len;
1398 auth->length = htons((uint16_t)total_length);
1399
1400 if (out_cap < total_length + (2 + MD5_DIGEST_SIZE))
1401 return -1;
1402 total_length = add_msg_auth_attr(rh, req->secret, auth, total_length);
1403
1404 secretlen = rc_secret_len(req->secret);
1405 if ((size_t)(out_cap - total_length) < secretlen)
1406 return -1;
1407 memcpy(out_buf + total_length, req->secret, secretlen);
1408 rc_md5_calc(digest, out_buf, (size_t)total_length + secretlen);
1409 memcpy(auth->vector, digest, AUTH_VECTOR_LEN);
1410
1411 *out_len = total_length;
1412 return 0;
1413}
1414
1415/*- Build req's reply via build_reply() and send it over req->dae->fd.
1416 *
1417 * @param req the request to reply to.
1418 * @param reply_code the concrete RADIUS reply code to send.
1419 * @param error_cause a radcli_error_cause value to encode as attribute
1420 * 101, or 0 for none.
1421 * @return 0 on success, -1 on failure.
1422 -*/
1423static int send_reply(struct radcli_dae_request_st *req, uint8_t reply_code, uint32_t error_cause)
1424{
1425 uint8_t send_buffer[RC_BUFFER_LEN];
1426 int total_length;
1427
1428 if (build_reply(req, reply_code, error_cause, send_buffer, sizeof(send_buffer),
1429 &total_length) != 0)
1430 return -1;
1431
1432 if (req->dae->radsec) {
1433 /* No dae-owned socket/peer address under RadSec: the reply goes
1434 * back over rh's own established TLS/DTLS session, without ever
1435 * waiting for write room (REQ-DAE-SEC-013, REQ-NET2-NET-005). */
1436 if (radcli2_priv_sess_send_queued(req->dae->rh, send_buffer, (size_t)total_length,
1437 RADSEC_SEND_DAE_REPLY, -1) == -1)
1438 return -1;
1439 return 0;
1440 }
1441
1442 if (sendto(req->dae->fd, send_buffer, (size_t)total_length, 0,
1443 (struct sockaddr *)&req->from, req->fromlen) != total_length)
1444 return -1;
1445
1446 return 0;
1447}
1448
1456{
1457
1458 if (req == NULL)
1459 return 0;
1460 return (radcli_code)req->code;
1461}
1462
1470const radcli_avp_list *radcli_dae_req_attrs(const radcli_dae_request *req)
1471{
1472
1473 if (req == NULL)
1474 return NULL;
1475 return req->attrs;
1476}
1477
1484{
1485
1486 if (req == NULL)
1487 return NULL;
1488 return req->session_id;
1489}
1490
1497{
1498
1499 if (req == NULL)
1500 return NULL;
1501 return req->user_name;
1502}
1503
1511int radcli_dae_req_framed_ip(const radcli_dae_request *req, struct sockaddr_storage *out)
1512{
1513 rc_handle *rh;
1514 const radcli_attr_def *d;
1515 const radcli_avp *a;
1516
1517 if (req == NULL || out == NULL)
1518 return -1;
1519 rh = req->dae->rh;
1520
1521 d = radcli_dict_lookup_num(rh, PW_FRAMED_IP_ADDRESS, 0);
1522 a = (d != NULL) ? radcli_avp_get(req->attrs, d, 0) : NULL;
1523 if (a != NULL) {
1524 uint32_t val;
1525
1526 if (radcli_avp_get_uint32(a, &val) == 0) {
1527 struct sockaddr_in sin;
1528
1529 memset(&sin, 0, sizeof(sin));
1530 sin.sin_family = AF_INET;
1531 sin.sin_addr.s_addr = htonl(val);
1532 memset(out, 0, sizeof(*out));
1533 memcpy(out, &sin, sizeof(sin));
1534 return 0;
1535 }
1536 }
1537
1538 d = radcli_dict_lookup_num(rh, PW_FRAMED_IPV6_ADDRESS, 0);
1539 a = (d != NULL) ? radcli_avp_get(req->attrs, d, 0) : NULL;
1540 if (a != NULL) {
1541 struct in6_addr addr;
1542 unsigned prefix;
1543
1544 if (radcli_avp_get_ip6(a, &addr, &prefix) == 0) {
1545 struct sockaddr_in6 sin6;
1546
1547 memset(&sin6, 0, sizeof(sin6));
1548 sin6.sin6_family = AF_INET6;
1549 sin6.sin6_addr = addr;
1550 memset(out, 0, sizeof(*out));
1551 memcpy(out, &sin6, sizeof(sin6));
1552 return 0;
1553 }
1554 }
1555
1556 return -1;
1557}
1558
1566int radcli_dae_req_nas_port(const radcli_dae_request *req, uint32_t *out)
1567{
1568 rc_handle *rh;
1569 const radcli_attr_def *d;
1570 const radcli_avp *a;
1571
1572 if (req == NULL)
1573 return -1;
1574 rh = req->dae->rh;
1575
1576 d = radcli_dict_lookup_num(rh, PW_NAS_PORT, 0);
1577 a = (d != NULL) ? radcli_avp_get(req->attrs, d, 0) : NULL;
1578 if (a == NULL)
1579 return -1;
1580 if (out == NULL)
1581 return 0;
1582 return radcli_avp_get_uint32(a, out);
1583}
1584
1585
1586/* Records reply_code/error_cause as the decision in req's duplicate-
1587 * suppression slot, if it still matches req exactly (dedup_key, REQ-DAE-
1588 * SEC-005) and is still awaiting one -- i.e. transitions it from PENDING to
1589 * ANSWERED.
1590 * Shared by reply_and_record() (after an actual send) and
1591 * radcli_dae_reply_to_buffer() (after producing bytes an L0 caller will send
1592 * itself): either way, a later retransmission must be answered from this
1593 * same decision, not a fresh one (REQ-DAE-SEC-005), even if the reply was
1594 * deferred past the handler's own return. */
1595/*- Record reply_code/error_cause in req's duplicate-suppression slot --
1596 * see the comment above.
1597 *
1598 * @param req the request whose slot to update.
1599 * @param reply_code the reply code that was sent.
1600 * @param error_cause the error cause that was sent, or 0 for none.
1601 -*/
1602static void record_reply_decision(struct radcli_dae_request_st *req, uint8_t reply_code,
1603 uint32_t error_cause)
1604{
1605 struct radcli_dae_slot *slot;
1606
1607 if (req->dae == NULL)
1608 return;
1609 slot = &req->dae->slots[req->id];
1610 if (slot->valid && slot->pending &&
1611 rc_memcmp(slot->dedup_key, req->dedup_key,
1612 RC_SHA256_DIGEST_SIZE) == 0) {
1613 slot->pending = 0;
1614 slot->reply_code = reply_code;
1615 slot->error_cause = error_cause;
1616 }
1617}
1618
1619/*- Send req's reply and record the decision for duplicate suppression.
1620 *
1621 * @param req the request to reply to; must not already be replied to.
1622 * @param reply_code the concrete RADIUS reply code to send.
1623 * @param error_cause a radcli_error_cause value to encode as attribute
1624 * 101, or 0 for none.
1625 * @return 0 on success, -1 if req is NULL, already replied to, or the
1626 * send failed.
1627 -*/
1628static int reply_and_record(struct radcli_dae_request_st *req, uint8_t reply_code, uint32_t error_cause)
1629{
1630 int ret;
1631
1632 if (req == NULL || req->replied)
1633 return -1;
1634 req->replied = 1;
1635
1636 ret = send_reply(req, reply_code, error_cause);
1637 record_reply_decision(req, reply_code, error_cause);
1638
1639 return ret;
1640}
1641
1642/*- Select the concrete ACK/NAK code (41/42/44/45) for req's own code
1643 * (40/43) and the application's accept/reject decision (RFC 5176 SS2.1,
1644 * SS3). Shared by radcli_dae_reply() and radcli_dae_reply_to_buffer().
1645 *
1646 * @param req the request being replied to.
1647 * @param ack nonzero for an ACK, zero for a NAK.
1648 * @return the concrete reply code.
1649 -*/
1650static uint8_t select_reply_code(const struct radcli_dae_request_st *req, int ack)
1651{
1652 return ack
1653 ? (req->code == RADCLI_DISCONNECT_REQUEST ? RADCLI_DISCONNECT_ACK : RADCLI_COA_ACK)
1654 : (req->code == RADCLI_DISCONNECT_REQUEST ? RADCLI_DISCONNECT_NAK : RADCLI_COA_NAK);
1655}
1656
1669{
1670
1671 if (req == NULL)
1672 return -1;
1673 return reply_and_record(req, select_reply_code(req, ack), 0);
1674}
1675
1683int radcli_dae_reply_error(radcli_dae_request *req, uint32_t error_cause)
1684{
1685 uint8_t reply_code;
1686
1687 if (req == NULL)
1688 return -1;
1689 reply_code = (req->code == RADCLI_DISCONNECT_REQUEST) ? RADCLI_DISCONNECT_NAK : RADCLI_COA_NAK;
1690 return reply_and_record(req, reply_code, error_cause);
1691}
1692
1714int radcli_dae_reply_to_buffer(radcli_dae_request *req, int ack, uint32_t error_cause,
1715 void *buf, size_t *len)
1716{
1717 uint8_t reply_code;
1718 int out_len;
1719
1720 if (req == NULL || buf == NULL || len == NULL)
1721 return -1;
1722
1723 if (req->is_cached_duplicate) {
1724 /* A genuine retransmission always gets the same answer
1725 * (RFC 5176 SS2.3): the caller's ack/error_cause are not
1726 * this decision's to make over again. */
1727 reply_code = req->cached_reply_code;
1728 error_cause = req->cached_error_cause;
1729 } else {
1730 if (req->replied)
1731 return -1;
1732 reply_code = select_reply_code(req, ack);
1733 }
1734
1735 if (build_reply(req, reply_code, error_cause, (uint8_t *)buf, *len, &out_len) != 0)
1736 return -1;
1737 *len = (size_t)out_len;
1738
1739 if (!req->is_cached_duplicate) {
1740 req->replied = 1;
1741 record_reply_decision(req, reply_code, error_cause);
1742 }
1743
1744 return 0;
1745}
1746
1753{
1754
1755 if (req == NULL)
1756 return;
1757 radcli_avp_list_free(req->attrs);
1758 free(req->session_id);
1759 free(req->user_name);
1760 free(req);
1761}
1762
1763/* Rebuilds and resends a duplicate's reply from the retransmitted request
1764 * (its Proxy-State attributes, per RFC 5176 SS2.3) plus the cached decision
1765 * -- never from a stored copy of the original reply, which is why a slot
1766 * stays ~32 bytes rather than a full packet buffer. */
1767/* Outcomes of process_packet(), the validation pipeline shared by
1768 * radcli_ctx_dispatch() (socket path) and radcli_dae_process() (L0 buffer
1769 * path) -- REQ-DAE-NET-003 requires the two to be indistinguishable. */
1770enum process_result {
1771 PROCESS_DROP, /* discarded at some check; *out_req left NULL */
1772 PROCESS_NEW, /* a newly validated request; *out_req set, PENDING */
1773 PROCESS_DUP_ANSWERED, /* a retransmission of an ANSWERED request; *out_req
1774 * set, carrying the cached decision */
1775};
1776
1777/* Runs the full RFC 5176 validation pipeline on one packet (REQ-NET2-NET-002):
1778 * source-address authorization (REQ-DAE-SEC-001), packet-code and length
1779 * sanity (REQ-DAE-ERR-001), Request Authenticator (REQ-DAE-SEC-002),
1780 * Message-Authenticator when present or required (REQ-DAE-SEC-003),
1781 * Event-Timestamp freshness (REQ-DAE-SEC-004), then duplicate suppression
1782 * (REQ-DAE-SEC-005/006). buf must have RC_MAX_PACKET_LEN + MAX_SECRET_LENGTH
1783 * bytes of headroom past len (verify_request_authenticator() writes there);
1784 * both callers below satisfy this from a stack buffer sized RC_BUFFER_LEN. */
1785/*- Run the full RFC 5176 validation pipeline on one packet -- see the
1786 * comment above.
1787 *
1788 * @param dae the listener the packet was received on.
1789 * @param buf the received packet; must have RC_MAX_PACKET_LEN +
1790 * MAX_SECRET_LENGTH bytes of headroom past len.
1791 * @param len the received packet's length in bytes.
1792 * @param from the sender's address.
1793 * @param fromlen from's length in bytes.
1794 * @param out_req set on PROCESS_NEW/PROCESS_DUP_ANSWERED; left NULL on
1795 * PROCESS_DROP.
1796 * @return the validation outcome.
1797 -*/
1798static enum process_result process_packet(struct radcli_dae_st *dae, uint8_t *buf, size_t len,
1799 const struct sockaddr *from, socklen_t fromlen,
1800 struct radcli_dae_request_st **out_req)
1801{
1802 rc_handle *rh = dae->rh;
1803 size_t length = len;
1804 struct radcli_dae_dac *dac;
1805 struct radcli_dae_slot *slot;
1806 time_t now;
1807 int retention;
1808 struct radcli_dae_request_st *req;
1809 radcli_avp_list *attrs = NULL;
1810 const radcli_attr_def *d;
1811 const radcli_avp *a;
1812 const char *secret;
1813
1814 *out_req = NULL;
1815
1816 if (dae->radsec) {
1817 /* REQ-DAE-SEC-015: "the source is the session" by construction
1818 * -- the record necessarily arrived on rh's own TLS/DTLS-
1819 * verified connection, so there is no separate source-address
1820 * ACL to check the way find_dac() checks one for UDP; the
1821 * RFC 6614/7360 fixed secret (rh->so.static_secret, set by
1822 * lib/tls.c's rc_init_tls()) replaces dae-secret/dac->secret. */
1823 dac = NULL;
1824 secret = rh->so.static_secret;
1825 } else {
1826 /* REQ-DAE-SEC-001: discarded before parsing attributes or computing
1827 * any MD5/HMAC, and without a reply -- a response would confirm to a
1828 * scanner that a listener is present. */
1829 dac = find_dac(dae, from);
1830 if (dac == NULL)
1831 return PROCESS_DROP;
1832 secret = (dac->secret != NULL) ? dac->secret : dae->secret;
1833 }
1834
1835 /* Header sanity: enough bytes for a header, the wire Length field
1836 * agrees with what was actually received (never trust it beyond
1837 * that) and with RFC 2865's packet-size cap (also what leaves
1838 * verify_request_authenticator() below enough headroom in buf to
1839 * append the secret without overrunning it), and the code is one
1840 * this pipeline handles at all (REQ-DAE-ERR-001). */
1841 if (length < AUTH_HDR_LEN)
1842 return PROCESS_DROP;
1843 {
1844 uint16_t wire_length;
1845
1846 memcpy(&wire_length, buf + 2, sizeof(wire_length));
1847 wire_length = ntohs(wire_length);
1848 if (wire_length < AUTH_HDR_LEN || wire_length > length ||
1849 wire_length > RC_MAX_PACKET_LEN)
1850 return PROCESS_DROP;
1851 length = wire_length; /* never read past the packet's own Length */
1852 }
1853 if (buf[0] != RADCLI_DISCONNECT_REQUEST && buf[0] != RADCLI_COA_REQUEST)
1854 return PROCESS_DROP;
1855
1856 {
1857 if (verify_request_authenticator(buf, length, secret) != 0)
1858 return PROCESS_DROP;
1859
1860 if (radcli_avp_decode(rh, secret, buf + 4, buf + AUTH_HDR_LEN,
1861 length - AUTH_HDR_LEN, 0, &attrs) != 0)
1862 return PROCESS_DROP;
1863
1864 /* Message-Authenticator: verified when present (mismatch is a
1865 * silent discard, same as any other authentication failure);
1866 * required when dae-require-message-authenticator is set
1867 * (RFC 5176 SS3 makes the attribute itself a MAY, so absence
1868 * alone is not a failure otherwise). Disconnect-Request and
1869 * CoA-Request derive their own Request Authenticator from a
1870 * hash of the packet (RFC 5176 SS2.3, the Accounting-Request
1871 * convention), so -- like Accounting-Request -- the sender
1872 * computes this HMAC with the Authenticator field treated as
1873 * sixteen zero octets (RFC 2869 SS5.14), not the packet's
1874 * actual Request Authenticator: only that ordering is
1875 * non-circular, since the real Request Authenticator is
1876 * itself hashed over the attributes including this one. */
1877 d = radcli_dict_lookup_num(rh, PW_MESSAGE_AUTHENTICATOR, 0);
1878 a = (d != NULL) ? radcli_avp_get(attrs, d, 0) : NULL;
1879 if (a != NULL) {
1880 uint8_t zero_vector[AUTH_VECTOR_LEN];
1881
1882 memset(zero_vector, 0, sizeof(zero_vector));
1883 if (validate_message_authenticator(buf, length - AUTH_HDR_LEN, secret,
1884 zero_vector) != 0) {
1885 radcli_avp_list_free(attrs);
1886 return PROCESS_DROP;
1887 }
1888 } else if (dae->require_message_authenticator) {
1889 radcli_avp_list_free(attrs);
1890 return PROCESS_DROP;
1891 }
1892 }
1893
1894 /* Event-Timestamp: two-sided freshness check when present and
1895 * enabled; absence is accepted (RFC 5176 SS6.3 makes it a SHOULD). */
1896 if (dae->max_clock_skew > 0) {
1897 d = radcli_dict_lookup_num(rh, PW_EVENT_TIMESTAMP, 0);
1898 a = (d != NULL) ? radcli_avp_get(attrs, d, 0) : NULL;
1899 if (a != NULL) {
1900 uint32_t ts;
1901 long diff;
1902
1903 if (radcli_avp_get_uint32(a, &ts) != 0) {
1904 radcli_avp_list_free(attrs);
1905 return PROCESS_DROP;
1906 }
1907 now = time(NULL);
1908 diff = (long)now - (long)ts;
1909 if (diff < 0)
1910 diff = -diff;
1911 if (diff > dae->max_clock_skew) {
1912 radcli_avp_list_free(attrs);
1913 return PROCESS_DROP;
1914 }
1915 }
1916 }
1917
1918 /* Duplicate suppression (REQ-DAE-SEC-005/006): a fixed slot per
1919 * Identifier, shared across every configured dae-server entry. The
1920 * match key is an SHA-256 digest process_packet() computes itself
1921 * over the verified packet (buf[0..length)), not the wire's 16-byte
1922 * MD5 Request Authenticator -- REQ-GEN-SEC-008 is why: that field is
1923 * a secret-suffix MD5 MAC, the construction class Blast-RADIUS
1924 * (CVE-2024-3596) broke, so basing "same key implies same content" on
1925 * it would only be as strong as MD5. The packet is already fully
1926 * authenticated by this point (REQ-DAE-SEC-002/003/004 above), so
1927 * hashing it again here with a collision-resistant function makes
1928 * that assumption actually true, independent of MD5's weakness,
1929 * rather than inherited from it -- at the cost of one extra SHA-256
1930 * over an already-small packet. A match (see RADCLI_DAE_SLOTS's
1931 * comment on why neither source address nor source port is part of
1932 * this) is a genuine retransmission -- answered from the cached
1933 * decision if one exists, or silently dropped if the original is
1934 * still PENDING; anything else (including a first-ever arrival)
1935 * claims the slot and produces a new request. */
1936 now = time(NULL);
1937 retention = (dae->max_clock_skew > 0) ? dae->max_clock_skew : 30;
1938 slot = &dae->slots[buf[1]];
1939
1940 req = calloc(1, sizeof(*req));
1941 if (req == NULL) {
1942 radcli_avp_list_free(attrs);
1943 return PROCESS_DROP;
1944 }
1945 req->dae = dae;
1946 req->dac = dac; /* NULL under RadSec -- see above */
1947 req->code = buf[0];
1948 req->id = buf[1];
1949 memcpy(req->request_authenticator, buf + 4, AUTH_VECTOR_LEN);
1950 rc_sha256_calc(req->dedup_key, buf, length);
1951 /* from is NULL exactly when dae->radsec is set (radcli2_priv_dae_on_
1952 * radsec_packet() is process_packet()'s only radsec-mode caller, and
1953 * always passes NULL/0 -- see above); the explicit from != NULL check
1954 * alongside dae->radsec is redundant at runtime but makes that
1955 * invariant provable locally instead of relying on a correlation
1956 * across call sites the compiler's static analyzer cannot see. */
1957 if (!dae->radsec && from != NULL) {
1958 memcpy(&req->from, from, fromlen);
1959 req->fromlen = fromlen;
1960 }
1961 strlcpy(req->secret, secret, sizeof(req->secret));
1962 req->attrs = attrs;
1963 attrs = NULL;
1964 req->session_id = dup_avp_str(rh, req->attrs, PW_ACCT_SESSION_ID);
1965 req->user_name = dup_avp_str(rh, req->attrs, PW_USER_NAME);
1966
1967 if (slot->valid && (now - slot->timestamp) <= retention &&
1968 rc_memcmp(slot->dedup_key, req->dedup_key,
1969 RC_SHA256_DIGEST_SIZE) == 0) {
1970 if (!slot->pending) {
1971 req->is_cached_duplicate = 1;
1972 req->cached_reply_code = slot->reply_code;
1973 req->cached_error_cause = slot->error_cause;
1974 *out_req = req;
1975 return PROCESS_DUP_ANSWERED;
1976 }
1977 /* Original still PENDING an application decision -- discarded
1978 * silently, exactly like any other failed check. */
1980 return PROCESS_DROP;
1981 }
1982
1983 /* REQ-DAE-SEC-018: NAS-Identifier, if both the request and the
1984 * nas-identifier config option carry one, must agree -- RFC 5176 SS3.5
1985 * "NAS Identification Mismatch" (Error-Cause 403). Absence of either
1986 * is not a mismatch -- there is nothing to check it against.
1987 * NAS-IP-Address/NAS-IPv6-Address are deliberately not compared here:
1988 * unlike NAS-Identifier, a DAC-observed address for a NAS routinely
1989 * differs from what the NAS is itself configured with (NAT, containers,
1990 * a proxy/load balancer in front of the NAS), so it is not something
1991 * radcli can check on the application's behalf. */
1992 if (!dae->no_nas_check) {
1993 const char *cfg_id = rc_conf_str_id(rh, OPT_NAS_IDENTIFIER);
1994
1995 if (cfg_id != NULL) {
1996 d = radcli_dict_lookup_num(rh, PW_NAS_IDENTIFIER, 0);
1997 a = (d != NULL) ? radcli_avp_get(req->attrs, d, 0) : NULL;
1998 if (a != NULL) {
1999 const void *val;
2000 size_t vlen;
2001
2002 if (radcli_avp_get_bytes(a, &val, &vlen) == 0 &&
2003 (vlen != strlen(cfg_id) || memcmp(val, cfg_id, vlen) != 0)) {
2004 req->cached_reply_code = (req->code == RADCLI_DISCONNECT_REQUEST)
2005 ? RADCLI_DISCONNECT_NAK : RADCLI_COA_NAK;
2006 req->cached_error_cause = RADCLI_ERROR_NAS_IDENTIFICATION_MISMATCH;
2007 slot->valid = 1;
2008 slot->timestamp = now;
2009 memcpy(slot->dedup_key, req->dedup_key, RC_SHA256_DIGEST_SIZE);
2010 slot->pending = 0;
2011 slot->reply_code = req->cached_reply_code;
2012 slot->error_cause = req->cached_error_cause;
2013 req->is_cached_duplicate = 1;
2014 *out_req = req;
2015 return PROCESS_DUP_ANSWERED;
2016 }
2017 }
2018 }
2019 }
2020
2021 slot->valid = 1;
2022 slot->timestamp = now;
2023 memcpy(slot->dedup_key, req->dedup_key, RC_SHA256_DIGEST_SIZE);
2024 slot->pending = 1;
2025
2026 *out_req = req;
2027 return PROCESS_NEW;
2028}
2029
2030/* Builds and sends a Disconnect-NAK/CoA-NAK with Error-Cause 406
2031 * ("Unsupported Extension") for reqbuf/reqlen, a CoA-Request or
2032 * Disconnect-Request that arrived on rh's RadSec session while dynamic
2033 * authorization is not enabled over it -- REQ-DAE-SEC-016, RFC 6614 SS2.5.
2034 * There is no radcli_dae_st to build this through (dynamic authorization
2035 * is off, or in UDP mode): a standalone builder, using rh->so.static_secret
2036 * directly, matching build_reply()'s wire logic for just this one fixed
2037 * case (no Proxy-State mirroring -- there is no configured dae to have
2038 * asked for it). reqbuf need only be long enough to name a Code and
2039 * Identifier; nothing about it is otherwise trusted or verified before
2040 * replying, since the reply itself carries no secret worth protecting
2041 * (the RFC 6614/7360 secret is a fixed, public string). */
2042/*- Build and send a Disconnect-NAK/CoA-NAK with Error-Cause 406
2043 * ("Unsupported Extension") for reqbuf/reqlen -- see the comment above.
2044 *
2045 * @param rh the handle whose RadSec session the request arrived on.
2046 * @param reqbuf the request; only its Code and Identifier are read.
2047 * @param reqlen reqbuf's length in bytes.
2048 -*/
2049static void send_radsec_unsupported_nak(rc_handle *rh, const uint8_t *reqbuf, size_t reqlen)
2050{
2051 uint8_t out[AUTH_HDR_LEN + 6 + 2 + MD5_DIGEST_SIZE]; /* header + Error-Cause(6) + Message-Authenticator(2+16) */
2052 AUTH_HDR *auth = (AUTH_HDR *)out;
2053 radcli_avp_list *reply_attrs;
2054 const radcli_attr_def *d_ec;
2055 int encoded_len, total_length;
2056 size_t secretlen;
2057 uint8_t digest[AUTH_VECTOR_LEN];
2058 const char *secret = rh->so.static_secret;
2059
2060 if (reqlen < AUTH_HDR_LEN || secret == NULL)
2061 return;
2062
2063 reply_attrs = radcli_avp_list_new();
2064 if (reply_attrs == NULL)
2065 return;
2066
2067 d_ec = radcli_dict_lookup_num(rh, PW_ERROR_CAUSE, 0);
2068 if (d_ec != NULL)
2069 radcli_avp_add_uint32(reply_attrs, d_ec, 406);
2070
2071 auth->code = (reqbuf[0] == RADCLI_DISCONNECT_REQUEST) ? RADCLI_DISCONNECT_NAK : RADCLI_COA_NAK;
2072 auth->id = reqbuf[1];
2073 memcpy(auth->vector, reqbuf + 4, AUTH_VECTOR_LEN);
2074
2075 encoded_len = radcli_avp_encode(rh, reply_attrs, secret, reqbuf + 4,
2076 auth->data, sizeof(out) - AUTH_HDR_LEN - (2 + MD5_DIGEST_SIZE), NULL);
2077 radcli_avp_list_free(reply_attrs);
2078 if (encoded_len < 0)
2079 return;
2080
2081 total_length = AUTH_HDR_LEN + encoded_len;
2082 auth->length = htons((uint16_t)total_length);
2083 total_length = add_msg_auth_attr(rh, (char *)secret, auth, total_length);
2084
2085 secretlen = rc_secret_len(secret);
2086 if ((size_t)(sizeof(out) - total_length) < secretlen)
2087 return;
2088 memcpy(out + total_length, secret, secretlen);
2089 rc_md5_calc(digest, out, (size_t)total_length + secretlen);
2090 memcpy(auth->vector, digest, AUTH_VECTOR_LEN);
2091
2092 /* Never waits for write room, like send_reply() (REQ-NET2-NET-005);
2093 * RFC 6614 SS2.5's 406 signal is best-effort, so a full queue simply
2094 * drops it. */
2095 radcli2_priv_sess_send_queued(rh, out, (size_t)total_length, RADSEC_SEND_DAE_REPLY, -1);
2096}
2097
2098/*- Process one RADIUS/TLS or RADIUS/DTLS record already known to carry
2099 * Code 40 (Disconnect-Request) or 43 (CoA-Request) -- called from lib/
2100 * sendserver.c's radcli2_priv_sess_route(), whichever call read the
2101 * record (a blocking exchange, or radcli_ctx_dispatch()). Never invokes a
2102 * registered radcli_dae_handler directly (that would let it run on
2103 * whatever thread/call stack happens to be inside rc_auth()/rc_acct() at
2104 * the time): a validated request is queued for radcli_ctx_dispatch() to
2105 * deliver, exactly as REQ-DAE-SEC-012's reentrancy guard already assumes.
2106 * If dynamic authorization is not enabled over RadSec at all (no active
2107 * radcli_dae, or one in UDP mode), replies with the RFC 6614 SS2.5-
2108 * mandated CoA-NAK/Disconnect-NAK (Error-Cause 406) instead.
2109 *
2110 * @param rh a handle to parsed configuration.
2111 * @param buf the received packet, header included.
2112 * @param len buf's length in bytes.
2113 -*/
2114void radcli2_priv_dae_on_radsec_packet(rc_handle *rh, const uint8_t *buf, size_t len)
2115{
2116 struct radcli_dae_st *dae = rh->active_dae;
2117 uint8_t local_buf[RC_BUFFER_LEN];
2118 struct radcli_dae_request_st *req = NULL;
2119
2120 if (dae == NULL || !dae->radsec) {
2121 send_radsec_unsupported_nak(rh, buf, len);
2122 return;
2123 }
2124
2125 if (len == 0 || len > sizeof(local_buf) - 1)
2126 return;
2127
2128 /* process_packet() mutates the buffer in place (verify_request_
2129 * authenticator() zeroes and restores the Authenticator field) --
2130 * copy so the caller's (lib/tls.c's) own receive buffer is untouched. */
2131 memcpy(local_buf, buf, len);
2132
2133 switch (process_packet(dae, local_buf, len, NULL, 0, &req)) {
2134 case PROCESS_NEW:
2135 radsec_queue_push(dae, req);
2136 break;
2137 case PROCESS_DUP_ANSWERED:
2138 req->replied = 1; /* answered from the cached decision, not a fresh one */
2139 send_reply(req, req->cached_reply_code, req->cached_error_cause);
2141 break;
2142 case PROCESS_DROP:
2143 break;
2144 }
2145}
2146
2177int radcli_ctx_dispatch(radcli_ctx *ctx)
2178{
2179 rc_handle *rh = (rc_handle *)ctx;
2180 struct radcli_dae_st *dae;
2181 uint8_t buf[RC_BUFFER_LEN];
2182 struct sockaddr_storage from;
2183 socklen_t fromlen;
2184 ssize_t n;
2185 struct radcli_dae_request_st *req = NULL;
2186
2187 if (rh == NULL)
2188 return -1;
2189
2190 if (rh->in_dispatch) {
2191 rc_log(LOG_ERR, "radcli_ctx_dispatch: reentrant call");
2192 return -1;
2193 }
2194
2195 rh->in_dispatch = 1;
2196
2197 /* Unconditional and non-blocking: what is queued to send goes first,
2198 * and everything readable is routed to the request or DAE listener
2199 * it belongs to (REQ-NET2-NET-004/005, REQ-NET2-SEND-013). */
2200 if (RC_USES_SESSION(rh)) {
2201 radcli2_priv_sess_progress(rh);
2202 radcli2_priv_sess_flush(rh);
2203 radcli2_priv_sess_drain(rh);
2204 } else {
2205 radcli2_priv_reqreg_drain(rh);
2206 }
2207 radcli2_priv_reqreg_service_timeouts(rh);
2208
2209 if (rh->so_type == RC_SOCKET_TLS || rh->so_type == RC_SOCKET_DTLS) {
2210 /* REQ-WATCHDOG-NET-001: folded in here rather than left as a
2211 * separate caller-invoked call -- still never radcli calling
2212 * itself unprompted (REQ-GEN-SEC-003): this only ever runs
2213 * inside a radcli_ctx_dispatch() call the application itself
2214 * makes, on its own schedule, driven by radcli_ctx_get_poll()'s
2215 * advisory timeout_ms (watchdog_deadline_ms(), above it in this
2216 * file). */
2217 if (watchdog_deadline_ms(rh, radcli2_priv_sess_fd(rh)) == 0)
2218 radcli2_priv_dae_send_watchdog(ctx);
2219 }
2220
2221 dae = rh->active_dae;
2222 if (dae == NULL) {
2223 rh->in_dispatch = 0;
2224 return 0;
2225 }
2226
2227 if (dae->radsec) {
2228 /* Deliver whatever is queued -- read by the drain above, or by
2229 * an earlier blocking exchange. */
2230 for (;;) {
2231 req = radsec_queue_pop(dae);
2232 if (req == NULL)
2233 break;
2234 if (dae->handler != NULL)
2235 dae->handler((radcli_dae_request *)req, dae->handler_user);
2236 else
2238 }
2239
2240 rh->in_dispatch = 0;
2241 return 0;
2242 }
2243
2244 if (dae->fd == -1) {
2245 /* Constructed but never (successfully) started -- nothing DAE-
2246 * specific to do, but the reqreg/watchdog work above may already
2247 * have done something useful, so this is not itself a failure. */
2248 rh->in_dispatch = 0;
2249 return 0;
2250 }
2251
2252 fromlen = sizeof(from);
2253 n = recvfrom(dae->fd, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&from, &fromlen);
2254 if (n < 0) {
2255 /* EAGAIN/EWOULDBLOCK ("nothing to read after all") and any other
2256 * receive error both simply mean there is nothing to deliver
2257 * this call; a socket-level error is not the caller's to act
2258 * on here. */
2259 rh->in_dispatch = 0;
2260 return 0;
2261 }
2262
2263 switch (process_packet(dae, buf, (size_t)n, (struct sockaddr *)&from, fromlen, &req)) {
2264 case PROCESS_NEW:
2265 if (dae->handler != NULL)
2266 dae->handler((radcli_dae_request *)req, dae->handler_user);
2267 else
2269 break;
2270 case PROCESS_DUP_ANSWERED:
2271 req->replied = 1; /* answered from the cached decision, not a fresh one */
2272 send_reply(req, req->cached_reply_code, req->cached_error_cause);
2274 break;
2275 case PROCESS_DROP:
2276 break;
2277 }
2278
2279 rh->in_dispatch = 0;
2280 return 0;
2281}
2282
2313int radcli_dae_process(radcli_dae *dae, const void *buf, size_t len,
2314 const struct sockaddr *from, socklen_t fromlen,
2315 radcli_dae_request **req)
2316{
2317 struct radcli_dae_request_st *built_req = NULL;
2318 uint8_t local_buf[RC_BUFFER_LEN];
2319 enum process_result result;
2320
2321 if (dae == NULL || buf == NULL || from == NULL || req == NULL ||
2322 len == 0 || len > sizeof(local_buf) - 1)
2323 return -1;
2324 *req = NULL;
2325
2326 /* This L0 entry point has no meaning under RadSec: process_packet()'s
2327 * radsec branch trusts the record's origin entirely to rh's own
2328 * TLS-verified session (REQ-DAE-SEC-015) and does not check a source
2329 * address at all -- accepting an arbitrary caller-supplied buf/from
2330 * pair here would let any caller feed it unauthenticated bytes as if
2331 * they had arrived on that session, with only the RFC 6614/7360 fixed
2332 * (not actually secret) string standing in for authentication. Reject outright rather than accept a
2333 * caller's buffer as a substitute for the real session. */
2334 if (dae->radsec)
2335 return -1;
2336
2337 /* fromlen is caller-supplied, not kernel-supplied (unlike
2338 * radcli_ctx_dispatch()'s recvfrom(), which sets it itself): a caller
2339 * relaying an address from an untrusted producer -- e.g. over IPC
2340 * from a privileged listener, the documented reason this L0 entry
2341 * point exists at all -- could pass a fromlen that does not match
2342 * from's actual family, or one large enough to overflow
2343 * req->from (struct sockaddr_storage) once process_packet() below
2344 * does memcpy(&req->from, from, fromlen). Bound it against both the
2345 * declared family and struct sockaddr_storage before trusting it. */
2346 if (fromlen < sizeof(struct sockaddr_in) || fromlen > sizeof(struct sockaddr_storage))
2347 return -1;
2348 if (from->sa_family == AF_INET6 && fromlen < sizeof(struct sockaddr_in6))
2349 return -1;
2350 if (from->sa_family != AF_INET && from->sa_family != AF_INET6)
2351 return -1;
2352
2353 /* process_packet() mutates the buffer in place (verify_request_
2354 * authenticator() zeroes and restores the Authenticator field) --
2355 * copy so the caller's own buffer is never touched. */
2356 memcpy(local_buf, buf, len);
2357
2358 result = process_packet(dae, local_buf, len, from, fromlen, &built_req);
2359 if (result == PROCESS_DROP)
2360 return -1;
2361
2362 *req = (radcli_dae_request *)built_req;
2363 return (result == PROCESS_DUP_ANSWERED) ? RADCLI_DAE_DUPLICATE : RADCLI_DAE_NEW;
2364}
int radcli_dae_req_nas_port(const radcli_dae_request *req, uint32_t *out)
Return the request's NAS-Port.
Definition dae.c:1566
void radcli_dae_free(radcli_dae *dae)
Release a listener, closing its socket if radcli_dae_start() opened one.
Definition dae.c:849
const char * radcli_dae_req_session_id(const radcli_dae_request *req)
Return the request's Acct-Session-Id, if it carried one.
Definition dae.c:1483
void(* radcli_dae_handler)(radcli_dae_request *req, void *user)
Application callback invoked by radcli_ctx_dispatch() for a validated request.
Definition radcli2.h:724
int radcli_ctx_get_poll(radcli_ctx *ctx, struct pollfd *pfds, size_t max_pfds, size_t *nfds, int *timeout_ms)
Report what to wait for on ctx's behalf, for the caller's own event loop – radcli never calls poll()/...
Definition dae.c:960
void radcli_dae_set_handler(radcli_dae *dae, radcli_dae_handler cb, void *user)
Register the callback radcli_ctx_dispatch() invokes for each validated request. May be called before ...
Definition dae.c:723
#define RADCLI_DAE_NEW
Definition radcli2.h:749
radcli_code radcli_dae_req_code(const radcli_dae_request *req)
Return the received packet's RADIUS code.
Definition dae.c:1455
int radcli_ctx_dispatch(radcli_ctx *ctx)
Read what is ready on ctx's descriptor(s), validate it, and invoke the registered handler for anythin...
Definition dae.c:2177
int radcli_dae_reply(radcli_dae_request *req, int ack)
Answer a request with an ACK or NAK, selecting 41/42 or 44/45 from the request's own code,...
Definition dae.c:1668
struct radcli_dae_st radcli_dae
Definition radcli2.h:699
const char * radcli_dae_req_user_name(const radcli_dae_request *req)
Return the request's User-Name, if it carried one.
Definition dae.c:1496
int radcli_dae_start(radcli_dae *dae)
Start receiving: binds the socket described by dae-listen.
Definition dae.c:767
const radcli_avp_list * radcli_dae_req_attrs(const radcli_dae_request *req)
Return the request's decoded attributes.
Definition dae.c:1470
int radcli_dae_reply_to_buffer(radcli_dae_request *req, int ack, uint32_t error_cause, void *buf, size_t *len)
Produce a reply as bytes instead of sending it – the L0 counterpart of radcli_dae_reply()/radcli_dae_...
Definition dae.c:1714
#define RADCLI_CTX_MAX_POLLFDS
Definition radcli2.h:785
int radcli_dae_process(radcli_dae *dae, const void *buf, size_t len, const struct sockaddr *from, socklen_t fromlen, radcli_dae_request **req)
Validate a caller-supplied packet, without a radcli-owned socket – the L0 counterpart of radcli_ctx_d...
Definition dae.c:2313
#define RADCLI_DAE_DUPLICATE
Definition radcli2.h:754
int radcli_dae_reply_error(radcli_dae_request *req, uint32_t error_cause)
Answer a request with a NAK carrying the given Error-Cause.
Definition dae.c:1683
radcli_dae * radcli_dae_new(radcli_ctx *ctx, unsigned flags)
Validate dae-* configuration and build a dynamic-authorization listener. Opens no socket – see radcli...
Definition dae.c:513
int radcli_dae_req_framed_ip(const radcli_dae_request *req, struct sockaddr_storage *out)
Return the request's Framed-IP-Address or Framed-IPv6-Address.
Definition dae.c:1511
struct radcli_dae_request_st radcli_dae_request
Definition radcli2.h:709
void radcli_dae_request_free(radcli_dae_request *req)
Release a request.
Definition dae.c:1752
@ RADCLI_DAE_NO_NAS_CHECK
Definition radcli2.h:766
void radcli_avp_list_free(radcli_avp_list *list)
Free a list and every attribute it holds.
Definition avp.c:159
radcli_avp_iter radcli_avp_list_iter(const radcli_avp_list *list)
Begin iterating list.
Definition avp.c:666
const radcli_avp * radcli_avp_get(const radcli_avp_list *list, const radcli_attr_def *def, unsigned idx)
Find the idx-th occurrence of an attribute in a list.
Definition avp.c:644
int radcli_avp_get_ip6(const radcli_avp *a, struct in6_addr *out, unsigned *prefix)
Read an attribute's value as an IPv6 address or prefix.
Definition avp.c:769
int radcli_avp_add_bytes(radcli_avp_list *list, const radcli_attr_def *def, const void *value, size_t len)
Append an attribute holding an arbitrary byte string.
Definition avp.c:224
int radcli_avp_get_uint32(const radcli_avp *a, uint32_t *out)
Read an attribute's value as an integer/IPv4-address/date.
Definition avp.c:716
radcli_avp_list * radcli_avp_list_new(void)
Create an empty attribute-value pair list.
Definition avp.c:145
const radcli_attr_def * radcli_avp_def(const radcli_avp *a)
Return the attribute definition of a.
Definition avp.c:703
int radcli_avp_add_uint32(radcli_avp_list *list, const radcli_attr_def *def, uint32_t value)
Append an integer/IPv4-address/date-typed attribute.
Definition avp.c:323
const radcli_avp * radcli_avp_iter_next(radcli_avp_iter *it)
Return the current attribute and advance.
Definition avp.c:680
int radcli_avp_get_bytes(const radcli_avp *a, const void **out, size_t *len)
Read an attribute's value as raw bytes.
Definition avp.c:853
const radcli_attr_def * radcli_dict_lookup_num(const radcli_ctx *ctx, uint32_t attrid, uint32_t vendor)
Look up a dictionary attribute by its legacy numeric ID and vendor.
Definition dict2.c:564
radcli_code
Definition radcli2.h:509