Radcli library 2.0.2
A simple radius library -- legacy API reference
Loading...
Searching...
No Matches
sendserver.c
1/*
2 * Copyright (C) 1995,1996,1997 Lars Fenneberg
3 * Copyright (C) 2015,2016 Nikos Mavrogiannopoulos
4 *
5 * Copyright 1992 Livingston Enterprises, Inc.
6 *
7 * Copyright 1992,1993, 1994,1995 The Regents of the University of Michigan
8 * and Merit Network, Inc. All Rights Reserved
9 *
10 * See the file COPYRIGHT for the respective terms and conditions.
11 *
12 */
13
14#include <includes.h>
15#include <radcli/radcli.h>
16#include <poll.h>
17#include "dict2.h"
18#include "options.h"
19#include "util.h"
20#include "avp.h"
21#include "rc-crypto.h"
22#include "rc-random.h"
23
24#if defined(HAVE_GNUTLS)
25# include <gnutls/gnutls.h>
26# include <gnutls/crypto.h>
27#endif
28
29
30/* Resets fd to -1 after closing so a later unconditional cleanup (e.g. the
31 * shared `cleanup:` label's `if (sockfd >= 0) SCLOSE(sockfd)`) cannot close
32 * the same descriptor a second time. */
33#define SCLOSE(fd) do { if (sfuncs->close_fd) sfuncs->close_fd(fd); (fd) = -1; } while (0)
34
35/* rc_check_reply(), populate_ctx(), add_msg_auth_attr(),
36 * validate_message_authenticator() are declared in include/includes.h (no
37 * longer static): they operate purely on raw bytes/AUTH_HDR/secret/vector,
38 * never on VALUE_PAIR, so radcli_transport_exchange() below reuses them
39 * directly instead of reimplementing the same RFC 2865 SS3 Response
40 * Authenticator and Message-Authenticator/Blast-RADIUS logic a second
41 * time. */
42
43/*- Allocate and fill an RC_AAA_CTX capturing the secret/vector used for a
44 * sent request, if the caller asked for one.
45 *
46 * @param ctx if non-NULL and *ctx is NULL, allocated and filled; a no-op
47 * if ctx is NULL.
48 * @param secret the shared secret used for the request.
49 * @param vector the request authenticator vector used for the request.
50 * @return OK_RC on success (including the ctx == NULL no-op case),
51 * ERROR_RC if *ctx is already non-NULL or allocation failed.
52 -*/
53int populate_ctx(RC_AAA_CTX ** ctx, char secret[MAX_SECRET_LENGTH + 1],
54 uint8_t vector[AUTH_VECTOR_LEN])
55{
56 if (ctx) {
57 if (*ctx != NULL)
58 return ERROR_RC;
59
60 *ctx = malloc(sizeof(RC_AAA_CTX));
61 if (*ctx) {
62 memcpy((*ctx)->secret, secret, sizeof((*ctx)->secret));
63 memcpy((*ctx)->request_vector, vector,
64 sizeof((*ctx)->request_vector));
65 } else {
66 return ERROR_RC;
67 }
68 }
69 return OK_RC;
70}
71/*- Verify a reply packet's length, sequence number, and Response
72 * Authenticator digest.
73 *
74 * @param auth a pointer to AUTH_HDR.
75 * @param bufferlen the available buffer length.
76 * @param secret the secret used by the server.
77 * @param vector a random vector of AUTH_VECTOR_LEN.
78 * @param seq_nbr a unique sequence number.
79 * @return OK_RC upon success, BADRESP_RC if anything looks funny.
80 -*/
81int rc_check_reply(AUTH_HDR * auth, int bufferlen, char const *secret,
82 unsigned char const *vector, uint8_t seq_nbr)
83{
84 int secretlen;
85 int totallen;
86 unsigned char calc_digest[AUTH_VECTOR_LEN];
87 unsigned char reply_digest[AUTH_VECTOR_LEN];
88
89 totallen = ntohs(auth->length);
90 secretlen = (int)strlen(secret);
91
92 /* Do sanity checks on packet length */
93 if ((totallen < 20) || (totallen > 4096)) {
94 rc_log(LOG_ERR,
95 "rc_check_reply: received RADIUS server response with invalid length");
96 return BADRESP_RC;
97 }
98
99 /* Verify buffer space, should never trigger with current buffer size and check above */
100 if ((totallen + secretlen) > bufferlen) {
101 rc_log(LOG_ERR,
102 "rc_check_reply: not enough buffer space to verify RADIUS server response");
103 return BADRESP_RC;
104 }
105
106 /* Verify that id (seq. number) matches what we sent */
107 if (auth->id != seq_nbr) {
108 rc_log(LOG_ERR,
109 "rc_check_reply: received non-matching id in RADIUS server response");
110 return BADRESPID_RC;
111 }
112 /* Verify the reply digest */
113 memcpy((char *)reply_digest, (char *)auth->vector, AUTH_VECTOR_LEN);
114 memcpy((char *)auth->vector, (char *)vector, AUTH_VECTOR_LEN);
115 memcpy((char *)auth + totallen, secret, secretlen);
116 rc_md5_calc(calc_digest, (unsigned char *)auth, totallen + secretlen);
117
118 if (rc_memcmp((char *)reply_digest, (char *)calc_digest,
119 AUTH_VECTOR_LEN) != 0) {
120 rc_log(LOG_ERR,
121 "rc_check_reply: received invalid reply digest from RADIUS server");
122 return BADRESP_RC;
123 }
124
125 return OK_RC;
126
127}
128
129/*- Add a Message-Authenticator attribute to a message. Mandatory, for
130 * example, when sending a message containing an EAP-Message attribute.
131 *
132 * @param rh a handle to parsed configuration.
133 * @param secret the server's secret string.
134 * @param auth pointer to the AUTH_HDR structure.
135 * @param total_length total packet length before Message-Authenticator is
136 * added.
137 * @return total packet length after Message-Authenticator is added.
138 -*/
139int add_msg_auth_attr(rc_handle * rh, char * secret,
140 AUTH_HDR *auth, int total_length)
141{
142 size_t secretlen = rc_secret_len(secret);
143 uint8_t *msg_auth = (uint8_t *)auth + total_length;
144 msg_auth[0] = PW_MESSAGE_AUTHENTICATOR;
145 msg_auth[1] = 18;
146 memset(&msg_auth[2], 0, MD5_DIGEST_SIZE);
147 total_length += 18;
148 auth->length = htons((unsigned short)total_length);
149
150 /* Calculate HMAC-MD5 [RFC2104] hash */
151 uint8_t digest[MD5_DIGEST_SIZE];
152 rc_hmac_md5((uint8_t *)auth, (size_t)total_length, (uint8_t *)secret, secretlen, digest);
153 memcpy(&msg_auth[2], digest, MD5_DIGEST_SIZE);
154
155 return total_length;
156}
157
158/*- Validate a reply's Message-Authenticator attribute (RFC 2869 §5.14,
159 * RFC 3579 §3.2).
160 *
161 * @param recv_buffer the original packet.
162 * @param length the length of the attribute data (packet length minus
163 * AUTH_HDR_LEN).
164 * @param secret the RADIUS secret.
165 * @param req_auth the request authenticator from the Access-Request (RFC
166 * 3579 §3.2 requires MA in responses to be computed over the packet with
167 * the Request Authenticator in the Authenticator field, not the Response
168 * Authenticator).
169 * @return zero on success, other values for failure.
170 -*/
171int validate_message_authenticator(const uint8_t *recv_buffer,
172 size_t length, const char *secret,
173 const unsigned char *req_auth)
174{
175 uint8_t verify_buffer[RC_BUFFER_LEN];
176 pkt_buf vb;
177 uint8_t ma_copy[MD5_DIGEST_SIZE];
178 uint8_t digest[MD5_DIGEST_SIZE];
179 uint8_t attr_type, attr_len;
180 int ma_found = 0;
181
182 if (AUTH_HDR_LEN + length > sizeof(verify_buffer)) {
183 rc_log(LOG_ERR, "%s: packet too large for verification buffer", __func__);
184 return -1;
185 }
186
187 /* Copy the packet, substitute the Request Authenticator per RFC 3579 §3.2,
188 * and zero the Message-Authenticator value before computing HMAC-MD5. */
189 memcpy(verify_buffer, recv_buffer, AUTH_HDR_LEN + length);
190 memcpy(verify_buffer + 4, req_auth, AUTH_VECTOR_LEN);
191 pb_init_read(&vb, verify_buffer + AUTH_HDR_LEN, length, length);
192
193 while (pb_len(&vb) >= 2) {
194 attr_type = vb.data[0];
195 attr_len = vb.data[1];
196 if (attr_len < 2 || (size_t)attr_len > pb_len(&vb))
197 break; /* malformed; already rejected by upstream attr-loop */
198
199 if (attr_type == PW_MESSAGE_AUTHENTICATOR) {
200 if (attr_len != 2 + MD5_DIGEST_SIZE) {
201 rc_log(LOG_ERR, "%s: Message-Authenticator has wrong length %u",
202 __func__, (unsigned)(attr_len - 2));
203 return -1;
204 }
205 /* Save original value before zeroing in the verification copy */
206 memcpy(ma_copy, vb.data + 2, MD5_DIGEST_SIZE);
207 memset(vb.data + 2, '\0', MD5_DIGEST_SIZE);
208 ma_found = 1;
209 break;
210 }
211 assert(pb_pull(&vb, attr_len) == 0);
212 }
213
214 if (!ma_found)
215 return -1;
216
217 rc_hmac_md5(verify_buffer, AUTH_HDR_LEN + length, (uint8_t *)secret, rc_secret_len(secret), digest);
218 return rc_memcmp(ma_copy, digest, MD5_DIGEST_SIZE);
219}
220
221/*- Representation-agnostic RADIUS request/reply exchange.
222 *
223 * Resolves server_name to every A/AAAA address it has and tries each in
224 * turn -- a fresh socket and re-derived source address per attempt, since
225 * a name can resolve to a mix of address families -- retrying up to
226 * `retries` times before moving to the next address. send_buf is a
227 * complete, pre-encoded packet (header included); code, Identifier, and
228 * Request Authenticator are read straight from its header rather than
229 * passed separately. mgmt_secret picks the resolution path: non-zero
230 * resolves server_name to an address only (rc_getaddrinfo()) and uses
231 * secret as given (the "management poll" case); zero resolves both
232 * address and secret via radcli2_priv_find_server_addr(), which overwrites secret
233 * if server_name matches a configured authserver/acctserver entry.
234 * no_wait is fire-and-forget (REQ-NET-NET-017): send once to the first
235 * resolved address and return without waiting for a reply.
236 *
237 * On a reply, validates framing, the Response Authenticator
238 * (rc_check_reply()), and -- for AUTH over UDP/TCP -- the
239 * Message-Authenticator and its Blast-RADIUS first-attribute position
240 * (validate_message_authenticator()). On success the reply's attribute
241 * region (header stripped) is left in recv_buf[0 .. *recv_len); this
242 * function does not encode or decode individual attributes.
243 *
244 * Deliberately does NOT scrub secret before returning: secret is caller
245 * memory (radcli_do_exchange() passes radcli2's own persistent r->secret
246 * through here by reference, not a copy), and this function has no way to
247 * know whether the caller is done with it -- radcli_do_exchange()'s own
248 * caller (radcli_request_perform()) still needs it one call later, to
249 * decode the very reply this function just validated. Wiping it here (as
250 * an earlier version of this function did) zeroed r->secret before that
251 * decode ran, silently corrupting any salt-encrypted reply attribute
252 * (Tunnel-Password, MS-MPPE-*-Key -- RFC 2868 SS3.5). Each caller that
253 * owns a secret buffer is responsible for clearing it once IT is actually
254 * done: rc_send_server_ctx() (lib/legacy/send.c) at its own end of
255 * function, radcli_request_free() (lib/request.c) at r's end of life.
256 *
257 * @param rh a handle to parsed configuration.
258 * @param ctx if non-NULL, receives the context of the sent request; release with rc_aaa_ctx_free().
259 * @param server_name the server to resolve and contact.
260 * @param svc_port overrides the resolved port when non-zero.
261 * @param secret the shared secret; see mgmt_secret for how it is used/resolved.
262 * @param mgmt_secret non-zero for the "management poll" resolution path (see above).
263 * @param timeout per-address, per-attempt reply wait, in seconds.
264 * @param retries additional attempts per address after the first (0 = one attempt per address, no retry).
265 * @param no_wait fire-and-forget; see above.
266 * @param type AUTH or ACCT; selects the Message-Authenticator/Blast-RADIUS check.
267 * @param send_buf the complete, pre-built, pre-encoded packet to send.
268 * @param send_len send_buf's length in bytes.
269 * @param recv_buf destination for the reply's attribute region.
270 * @param recv_buf_cap recv_buf's capacity in bytes.
271 * @param recv_len set to the reply's attribute region length on success.
272 * @param out_code if non-NULL, set to the reply's raw wire Code octet
273 * (e.g. PW_ACCESS_ACCEPT) whenever recv_len is also set, i.e. on
274 * OK_RC/REJECT_RC/CHALLENGE_RC/BADRESP_RC; left untouched otherwise.
275 * @return OK_RC (0) on success, CHALLENGE_RC on Access-Challenge, TIMEOUT_RC
276 * if every address's retries are exhausted, REJECT_RC on reject, or
277 * negative on failure.
278 -*/
279/*- Validate and decode a reply already known to have the right Identifier
280 * and Response Authenticator (rc_check_reply() returned OK_RC) into
281 * recv_buf's attribute region, exactly as radcli_transport_exchange()'s own
282 * `got_reply:` block used to do inline. Factored out so
283 * radcli2_priv_reqreg_drain() below can reuse the identical RFC
284 * 2865/2869/Blast-RADIUS validation instead of a second copy.
285 * secret/vector/type/server_name/svc_port are as radcli_transport_exchange()
286 * received them, and req_code is the request's Code; recv_buf/recv_buf_cap/
287 * recv_len/out_code are as documented on radcli_transport_exchange() itself.
288 *
289 * Despite the above, this function does not simply trust its callers for the
290 * one property that would otherwise abort() the process if violated: whether
291 * recv_auth->length is at least AUTH_HDR_LEN. Both call sites only bound
292 * recv_auth->length against the bytes actually received, not against
293 * AUTH_HDR_LEN itself, and rc_check_reply()'s OK_RC does establish it -- but
294 * this function is static with exactly two callers, and REQ-GEN-STYLE-009
295 * treats a cross-function invariant on wire-controlled data as one reorg
296 * away from silently breaking, not as a fact to assert. Checked explicitly
297 * below instead.
298 *
299 * @return OK_RC/REJECT_RC/CHALLENGE_RC/BADRESP_RC/ERROR_RC -- never
300 * TIMEOUT_RC or BADRESPID_RC, which are decided by the caller before this
301 * is reached. A BADRESP_RC return here is this function's own verdict (an
302 * unrecognized reply code), unrelated to rc_check_reply()'s BADRESP_RC,
303 * which the caller must have already turned away before calling in.
304 -*/
305static int decode_reply(rc_handle *rh, RC_AAA_CTX **ctx, const char *server_name,
306 unsigned short svc_port, rc_type type, uint8_t req_code,
307 char secret[MAX_SECRET_LENGTH + 1], const unsigned char *vector,
308 uint8_t *recv_buf, size_t recv_buf_cap,
309 size_t *recv_len, uint8_t *out_code)
310{
311 AUTH_HDR *recv_auth = (AUTH_HDR *)recv_buf;
312 int length = ntohs(recv_auth->length);
313 pkt_buf rb;
314 uint8_t attr_type, attr_len;
315 int result;
316
317 if ((size_t)length > recv_buf_cap)
318 length = (int)recv_buf_cap;
319
320 /* Verify it's a well-formed RADIUS packet before doing ANYTHING with it. */
321 pb_init_read(&rb, recv_buf, length, recv_buf_cap);
322 if (pb_pull(&rb, AUTH_HDR_LEN) != 0) {
323 rc_log(LOG_ERR, "%s: %s:%d: reply shorter than the RADIUS header",
324 __func__, server_name, svc_port);
325 return ERROR_RC;
326 }
327 while (pb_len(&rb) > 0) {
328 if (pb_peek_byte(&rb, 0, &attr_type) < 0 || pb_peek_byte(&rb, 1, &attr_len) < 0) {
329 rc_log(LOG_ERR, "%s: %s:%d: truncated attribute", __func__, server_name, svc_port);
330 return ERROR_RC;
331 }
332 if (attr_type == 0) {
333 rc_log(LOG_ERR, "%s: %s:%d: attribute zero is invalid", __func__, server_name, svc_port);
334 return ERROR_RC;
335 }
336 if (attr_len < 2) {
337 rc_log(LOG_ERR, "%s: %s:%d: attribute length is too small", __func__, server_name, svc_port);
338 return ERROR_RC;
339 }
340 if (attr_len > pb_len(&rb)) {
341 rc_log(LOG_ERR, "%s: %s:%d: attribute overflows the packet", __func__, server_name, svc_port);
342 return ERROR_RC;
343 }
344 assert(pb_pull(&rb, attr_len) == 0);
345 }
346
347 length = ntohs(recv_auth->length) - AUTH_HDR_LEN;
348 if (length < 0)
349 length = 0;
350
351 result = populate_ctx(ctx, secret, (unsigned char *)vector);
352 if (result != OK_RC)
353 return result;
354
355 /* Per draft-ietf-radext-deprecating-radius, Message-Authenticator MUST
356 * be the first attribute in Access-Request responses (BLAST RADIUS).
357 * Not required for Accounting-Response, including one to an
358 * Accounting-Request sent as AUTH to a TCP authserver. */
359 if (type == AUTH) {
360 pkt_buf mb;
361 uint8_t mtype, mlen;
362 int has_ma = 0;
363
364 pb_init_read(&mb, recv_buf + AUTH_HDR_LEN, (size_t)length, (size_t)length);
365 while (pb_len(&mb) > 0) {
366 assert(pb_peek_byte(&mb, 0, &mtype) == 0);
367 assert(pb_peek_byte(&mb, 1, &mlen) == 0);
368 if (mtype == PW_MESSAGE_AUTHENTICATOR) {
369 has_ma = 1;
370 break;
371 }
372 assert(pb_pull(&mb, mlen) == 0);
373 }
374
375 if (has_ma) {
376 if (validate_message_authenticator(recv_buf, (size_t)length, secret, vector)) {
377 rc_log(LOG_ERR, "%s: %s:%d: received attribute Message-Authenticator is incorrect",
378 __func__, server_name, svc_port);
379 return ERROR_RC;
380 }
381 }
382
383 if (rh->so_type != RC_SOCKET_TLS && rh->so_type != RC_SOCKET_DTLS &&
384 req_code != PW_ACCOUNTING_REQUEST) {
385 if (length == 0 || recv_buf[AUTH_HDR_LEN] != PW_MESSAGE_AUTHENTICATOR) {
386 char *p = rc_conf_str_id(rh, OPT_REQUIRE_MESSAGE_AUTHENTICATOR);
387 if (p == NULL || (strcasecmp(p, "false") != 0 &&
388 strcasecmp(p, "no") != 0)) {
389 rc_log(LOG_ERR, "%s: %s:%d: required attribute Message-Authenticator "
390 "is missing or not first", __func__, server_name, svc_port);
391 return ERROR_RC;
392 }
393 }
394 }
395 }
396
397 {
398 uint8_t code = recv_auth->code; /* memmove() below invalidates recv_auth */
399
400 *recv_len = (size_t)length;
401 if (out_code)
402 *out_code = code;
403 if (recv_buf_cap > (size_t)AUTH_HDR_LEN)
404 memmove(recv_buf, recv_buf + AUTH_HDR_LEN, (size_t)length);
405
406 switch (code) {
407 case PW_ACCESS_ACCEPT:
408 case PW_PASSWORD_ACK:
409 case PW_ACCOUNTING_RESPONSE:
410 return OK_RC;
411 case PW_ACCESS_REJECT:
412 case PW_PASSWORD_REJECT:
413 return REJECT_RC;
414 case PW_ACCESS_CHALLENGE:
415 return CHALLENGE_RC;
416 default:
417 rc_log(LOG_ERR, "%s: received RADIUS server response neither ACCEPT nor "
418 "REJECT, code=%d is invalid", __func__, code);
419 return BADRESP_RC;
420 }
421 }
422}
423
424/*- Representation-agnostic send/retry/receive core, shared by
425 * rc_send_server_ctx() (legacy VALUE_PAIR API) and lib/request.c's
426 * radcli_request_perform() (radcli2 API): resolves server_name (or takes
427 * mgmt_secret's pre-resolved addr_info-only path for a management/CoA
428 * response), holds the configured network namespace switched for the
429 * whole call, sends send_buf once per address/retry, and, for each address
430 * in resolution order, retries up to retries times waiting timeout seconds
431 * per attempt -- moving to the next address only once the current one is
432 * exhausted. On a datagram, validates it via rc_check_reply() (RFC 2865
433 * SS3 Response Authenticator + Identifier match) and, unless rh's
434 * transport is TLS/DTLS, validate_message_authenticator() (RFC 2869
435 * SS5.14), discarding anything that fails either and continuing to wait.
436 *
437 * @param rh a handle to parsed configuration.
438 * @param ctx if non-NULL and *ctx is NULL, filled via populate_ctx() with
439 * the secret/vector actually used.
440 * @param server_name the server to resolve and contact.
441 * @param svc_port overrides the resolved port when non-zero.
442 * @param secret the shared secret; radcli2_priv_find_server_addr() may
443 * overwrite it when mgmt_secret is 0.
444 * @param mgmt_secret nonzero to skip server-name lookup in rh's configured
445 * server list and resolve server_name directly (the CoA/Disconnect reply
446 * path, whose peer is the DAC that sent the request, not a configured
447 * RADIUS server).
448 * @param timeout_ms per-attempt reply wait, in milliseconds.
449 * @param retries additional retransmit attempts after the first, per
450 * address.
451 * @param no_wait nonzero to send once and return without waiting for a
452 * reply (accounting fire-and-forget).
453 * @param type AUTH or ACCT.
454 * @param send_buf the complete, pre-built, pre-encoded packet to send;
455 * its Identifier (send_buf[1]) and Request Authenticator (send_buf+4)
456 * are reused to validate the reply.
457 * @param send_len send_buf's length in bytes.
458 * @param recv_buf filled with the reply's attributes (header stripped) on
459 * a terminal OK_RC/REJECT_RC/CHALLENGE_RC.
460 * @param recv_buf_cap recv_buf's capacity in bytes.
461 * @param recv_len set to the number of attribute bytes written to recv_buf.
462 * @param out_code if non-NULL, set to the reply's RADIUS code on a
463 * terminal result.
464 * @return OK_RC/REJECT_RC/CHALLENGE_RC on a validated reply, TIMEOUT_RC if
465 * every address's retries were exhausted, ERROR_RC on failure.
466 -*/
467int radcli_transport_exchange(rc_handle *rh, RC_AAA_CTX **ctx,
468 char *server_name, unsigned short svc_port,
469 char secret[MAX_SECRET_LENGTH + 1], int mgmt_secret,
470 int timeout_ms, int retries, int no_wait, rc_type type,
471 const uint8_t *send_buf, int send_len,
472 uint8_t *recv_buf, size_t recv_buf_cap, size_t *recv_len,
473 uint8_t *out_code)
474{
475 struct addrinfo *auth_addr = NULL, *cur_addr;
476 const rc_sockets_override *sfuncs;
477 int sockfd = -1;
478 int result = 0;
479 char *ns = NULL;
480 int ns_def_hdl = 0;
481 char *server_type = (type == ACCT) ? "acct" : "auth";
482 const unsigned char *vector = send_buf + 4; /* AUTH_HDR: code(1) id(1) length(2) vector(16) */
483 uint8_t seq_nbr = send_buf[1];
484 int on_session = RC_USES_SESSION(rh);
485
486 if (server_name == NULL || server_name[0] == '\0')
487 return ERROR_RC;
488 if (send_len < AUTH_HDR_LEN)
489 return ERROR_RC;
490
491 ns = rc_conf_str_id(rh, OPT_NAMESPACE);
492 if (ns != NULL) {
493 if (-1 == rc_set_netns(ns, &ns_def_hdl)) {
494 rc_log(LOG_ERR, "radcli_transport_exchange: namespace %s set failed", ns);
495 return ERROR_RC;
496 }
497 }
498
499 if (mgmt_secret) {
500 auth_addr = rc_getaddrinfo(server_name, type == AUTH ? PW_AI_AUTH : PW_AI_ACCT);
501 if (auth_addr == NULL) {
502 result = ERROR_RC;
503 goto exit_error;
504 }
505 } else {
506 if (radcli2_priv_find_server_addr(rh, server_name, &auth_addr, secret, type) != 0) {
507 rc_log(LOG_ERR, "radcli_transport_exchange: unable to find server: %s",
508 server_name);
509 result = ERROR_RC;
510 goto exit_error;
511 }
512 }
513
514 sfuncs = &rh->so;
515
516 if (sfuncs->static_secret) {
517 /* any static secret set in sfuncs overrides the configured/resolved one */
518 strlcpy(secret, sfuncs->static_secret, MAX_SECRET_LENGTH + 1);
519 }
520
521 if (sfuncs->lock) {
522 if (sfuncs->lock(sfuncs->ptr) != 0) {
523 rc_log(LOG_ERR, "%s: lock error", __func__);
524 result = ERROR_RC;
525 goto exit_error;
526 }
527 }
528
529 result = TIMEOUT_RC; /* if every address is unreachable/times out */
530
531 for (cur_addr = auth_addr; cur_addr != NULL; cur_addr = cur_addr->ai_next) {
532 struct sockaddr_storage our_sockaddr;
533 unsigned discover_local_ip;
534 int retry_max = retries;
535 int this_retries = 0;
536 unsigned sent_gen = 0;
537
538 if (svc_port) {
539 if (cur_addr->ai_family == AF_INET)
540 ((struct sockaddr_in *)cur_addr->ai_addr)->sin_port = htons(svc_port);
541 else
542 ((struct sockaddr_in6 *)cur_addr->ai_addr)->sin6_port = htons(svc_port);
543 }
544
545 rc_own_bind_addr(rh, &our_sockaddr);
546 discover_local_ip = 0;
547 if (our_sockaddr.ss_family == AF_INET &&
548 ((struct sockaddr_in *)(&our_sockaddr))->sin_addr.s_addr == INADDR_ANY)
549 discover_local_ip = 1;
550
551 if (discover_local_ip) {
552 result = radcli2_priv_get_srcaddr(SA(&our_sockaddr), cur_addr->ai_addr);
553 if (result != OK_RC) {
554 rc_log(LOG_ERR, "radcli_transport_exchange: cannot figure our own address");
555 continue; /* try the next resolved address, if any */
556 }
557 }
558
559 if (sfuncs->get_fd) {
560 sockfd = sfuncs->get_fd(sfuncs->ptr, SA(&our_sockaddr));
561 if (sockfd < 0) {
562 rc_log(LOG_ERR, "radcli_transport_exchange: socket: %s", strerror(errno));
563 result = ERROR_RC;
564 continue;
565 }
566 }
567
568 if (our_sockaddr.ss_family == AF_INET6 &&
569 radcli2_priv_prefer_public_addr(rh, sockfd) < 0) {
570 result = ERROR_RC;
571 SCLOSE(sockfd);
572 continue;
573 }
574
575 if (rh->debug) {
576 char our_addr_txt[50] = "", addr_txt[50] = "";
577
578 getnameinfo(SA(&our_sockaddr), SS_LEN(&our_sockaddr), NULL, 0,
579 our_addr_txt, sizeof(our_addr_txt), NI_NUMERICHOST);
580 getnameinfo(cur_addr->ai_addr, cur_addr->ai_addrlen, NULL, 0,
581 addr_txt, sizeof(addr_txt), NI_NUMERICHOST);
582 DEBUG(rh, LOG_ERR,
583 "DEBUG: radcli_transport_exchange: timeout=%dms retries=%d local %s : 0, "
584 "remote %s : %u\n", timeout_ms, retry_max, our_addr_txt, addr_txt, svc_port);
585 }
586
587 for (;;) {
588 socklen_t salen;
589 int recv_length;
590 struct pollfd pfd;
591 int64_t deadline_ms;
592
593 /* A retry waits again without resending over the stream
594 * connection the request already went out on
595 * (REQ-NET-NET-022). */
596 if (!radcli2_priv_sess_holds(rh, sent_gen)) {
597 do {
598 result = sfuncs->sendto(sfuncs->ptr, sockfd, (const char *)send_buf,
599 (unsigned int)send_len, 0,
600 SA(cur_addr->ai_addr), cur_addr->ai_addrlen);
601 } while (result == -1 && errno == EINTR);
602 if (result == -1) {
603 result = errno == ENETUNREACH ? NETUNREACH_RC : ERROR_RC;
604 rc_log(LOG_ERR, "%s: socket: %s", __FUNCTION__, strerror(errno));
605 break; /* try the next address */
606 }
607 sent_gen = radcli2_priv_sess_gen(rh);
608 }
609
610 if (no_wait) {
611 SCLOSE(sockfd);
612 result = populate_ctx(ctx, secret, (unsigned char *)vector);
613 goto cleanup; /* first address only -- no reply to judge a retry by */
614 }
615
616 if (sfuncs->get_active_fd) {
617 int new_fd = sfuncs->get_active_fd(sfuncs->ptr);
618 if (new_fd >= 0)
619 sockfd = new_fd;
620 }
621
622 /* Wait out this attempt's whole timeout for our own reply:
623 * a reply that is not ours only continues the wait, it does
624 * not end the attempt (REQ-NET-NET-010). */
625 deadline_ms = rc_getmtime_ms() + timeout_ms;
626 for (;;) {
627 int remaining_ms = rc_ms_until(deadline_ms);
628
629 if (remaining_ms == 0)
630 break;
631 /* A record GnuTLS already holds raises no POLLIN. */
632 if (!(on_session && radcli2_priv_sess_pending(rh))) {
633 pfd.fd = sockfd;
634 pfd.events = POLLIN;
635 pfd.revents = 0;
636 do {
637 result = poll(&pfd, 1, remaining_ms);
638 } while (result == -1 && errno == EINTR);
639
640 if (result == -1) {
641 rc_log(LOG_ERR, "radcli_transport_exchange: poll: %s",
642 strerror(errno));
643 SCLOSE(sockfd);
644 result = ERROR_RC;
645 goto cleanup;
646 }
647 if (result == 0 || (pfd.revents & POLLIN) == 0)
648 break;
649 }
650
651 salen = cur_addr->ai_addrlen;
652 do {
653 recv_length = sfuncs->recvfrom(sfuncs->ptr, sockfd,
654 (char *)recv_buf,
655 (int)recv_buf_cap, 0,
656 SA(cur_addr->ai_addr), &salen);
657 } while (recv_length == -1 && errno == EINTR);
658
659 if (recv_length <= 0) {
660 int e = errno;
661
662 if (recv_length == -1 && e == EAGAIN)
663 continue;
664 rc_log(LOG_ERR, "radcli_transport_exchange: recvfrom: %s:%d: %s",
665 server_name, svc_port, strerror(e));
666 SCLOSE(sockfd);
667 result = ERROR_RC;
668 goto cleanup;
669 }
670
671 {
672 AUTH_HDR *recv_auth = (AUTH_HDR *)recv_buf;
673
674 /* RFC 6614 SS2.1/SS2.5, RFC 7360 SS2.2: the session
675 * carries every packet type; what is not this
676 * exchange's reply goes where it belongs
677 * (REQ-NET2-NET-004). */
678 if (on_session && (recv_buf[0] == RADCLI_DISCONNECT_REQUEST ||
679 recv_buf[0] == RADCLI_COA_REQUEST)) {
680 radcli2_priv_sess_route(rh, recv_buf, recv_buf_cap,
681 recv_length);
682 continue;
683 }
684
685 if (recv_length < AUTH_HDR_LEN ||
686 recv_length < ntohs(recv_auth->length)) {
687 rc_log(LOG_ERR, "radcli_transport_exchange: recvfrom: "
688 "%s:%d: reply is too short", server_name, svc_port);
689 SCLOSE(sockfd);
690 result = ERROR_RC;
691 goto cleanup;
692 }
693
694 if (on_session && recv_auth->id != seq_nbr) {
695 radcli2_priv_sess_route(rh, recv_buf, recv_buf_cap,
696 recv_length);
697 continue;
698 }
699
700 result = rc_check_reply(recv_auth, (int)recv_buf_cap, secret,
701 vector, seq_nbr);
702 if (result == OK_RC)
703 goto got_reply; /* out of every loop */
704 /* BADRESPID_RC (some other packet arrived, e.g. a stale
705 * retransmit's answer) and BADRESP_RC (bad length or
706 * Response Authenticator -- possibly spoofed) are both
707 * treated as "not our reply yet": keep waiting rather
708 * than handing an unverified packet to decode_reply(),
709 * which trusts its caller to have already validated it
710 * (REQ-GEN-STYLE-009). */
711 }
712 }
713
714 if (this_retries++ >= retry_max) {
715 char server_ip[128];
716 struct sockaddr_in *si = (struct sockaddr_in *)cur_addr->ai_addr;
717
718 inet_ntop(cur_addr->ai_family, &si->sin_addr, server_ip, sizeof(server_ip));
719 rc_log(LOG_ERR, "radcli_transport_exchange: no reply from RADIUS "
720 "%s server %s:%u", server_type, server_ip, svc_port);
721 result = TIMEOUT_RC;
722 break; /* try the next address */
723 }
724 }
725
726 SCLOSE(sockfd);
727 }
728
729 /* Every resolved address was tried without a valid reply. */
730 goto cleanup_nosock;
731
732 got_reply:
733 result = decode_reply(rh, ctx, server_name, svc_port, type, send_buf[0], secret, vector,
734 recv_buf, recv_buf_cap, recv_len, out_code);
735
736 cleanup:
737 if (sockfd >= 0)
738 SCLOSE(sockfd);
739 cleanup_nosock:
740 if (auth_addr)
741 freeaddrinfo(auth_addr);
742 if (sfuncs->unlock) {
743 if (sfuncs->unlock(sfuncs->ptr) != 0)
744 rc_log(LOG_ERR, "%s: unlock error", __func__);
745 }
746 exit_error:
747 if (ns != NULL) {
748 if (-1 == rc_reset_netns(&ns_def_hdl)) {
749 rc_log(LOG_ERR, "radcli_transport_exchange: namespace %s reset failed", ns);
750 result = ERROR_RC;
751 }
752 }
753
754 return result;
755}
756
757/* Compares two sockaddrs' family+address+port -- REQ-NET2-SEND-016's
758 * explicit reply-source check on the shared, unconnected UDP request
759 * socket (replacing the kernel-level filtering a connect()ed per-request
760 * socket used to give for free). */
761static int reqreg_peer_matches(const struct sockaddr *from, const struct sockaddr *expected)
762{
763 if (from->sa_family != expected->sa_family)
764 return 0;
765 if (from->sa_family == AF_INET) {
766 const struct sockaddr_in *a = (const struct sockaddr_in *)from;
767 const struct sockaddr_in *b = (const struct sockaddr_in *)expected;
768 return a->sin_port == b->sin_port &&
769 memcmp(&a->sin_addr, &b->sin_addr, sizeof(a->sin_addr)) == 0;
770 }
771 {
772 const struct sockaddr_in6 *a = (const struct sockaddr_in6 *)from;
773 const struct sockaddr_in6 *b = (const struct sockaddr_in6 *)expected;
774 return a->sin6_port == b->sin6_port &&
775 memcmp(&a->sin6_addr, &b->sin6_addr, sizeof(a->sin6_addr)) == 0;
776 }
777}
778
779/* Lazily allocates rh->reqreg (REQ-NET2-SEND-016). */
780static int reqreg_ensure(rc_handle *rh)
781{
782 if (rh->reqreg != NULL)
783 return 0;
784
785 rh->reqreg = calloc(1, sizeof(*rh->reqreg));
786 return rh->reqreg != NULL ? 0 : -1;
787}
788
789/*- Mark reg's least-recently-used free slot in use (RFC 5080 SS2.1.1),
790 * not yet armed, and return its index -- the Identifier.
791 *
792 * @param reg the registry to take a slot from.
793 * @param owner stored on the slot; NULL for a blocking request or watchdog,
794 * whose reply is never delivered through the registry.
795 * @return the slot index, or -1 (logged) if every slot is in use.
796 -*/
797static int reqreg_take_lru(struct radcli_reqreg *reg, struct radcli_async_send_st *owner)
798{
799 int best = -1;
800 uint64_t best_seq = 0;
801 int i;
802
803 for (i = 0; i < RADCLI_CTX_MAX_INFLIGHT; i++) {
804 if (reg->slots[i].valid)
805 continue;
806 /* LRU: the slot free the longest wins; free_seq == 0 (never
807 * used yet) sorts first automatically. */
808 if (best == -1 || reg->slots[i].free_seq < best_seq) {
809 best = i;
810 best_seq = reg->slots[i].free_seq;
811 }
812 }
813 if (best == -1) {
814 rc_log(LOG_ERR, "%s: no free Identifier (%d requests already in flight)",
815 __func__, RADCLI_CTX_MAX_INFLIGHT);
816 return -1;
817 }
818 reg->slots[best].valid = 1;
819 reg->slots[best].armed = 0;
820 reg->slots[best].owner = owner;
821 return best;
822}
823
824/*- Reserve a slot in rh's in-flight registry (REQ-NET2-SEND-016),
825 * allocating the registry itself on first use. The Identifier is chosen by
826 * least-recently-used selection among currently-free slots (RFC 5080
827 * SS2.1.1), never randomly and never a fixed counter -- see
828 * REQ-NET2-SEND-010/016. The slot is marked valid (excluded from future
829 * reservation) but not yet armed: radcli_transport_send_async() arms it
830 * once the packet -- built using the returned id, per
831 * radcli_encode_request()'s forced_id parameter -- has actually been sent.
832 *
833 * @param rh a handle to parsed configuration.
834 * @param owner stored on the slot; written to directly by drain()/
835 * service_timeouts() on delivery.
836 * @param out_id set to the reserved Identifier (== the slot index) on success.
837 * @return the reserved slot index (0..RADCLI_CTX_MAX_INFLIGHT-1) on success,
838 * -1 if the registry is full or allocation failed.
839 -*/
840int radcli2_priv_reqreg_reserve(rc_handle *rh, struct radcli_async_send_st *owner, uint8_t *out_id)
841{
842 int best;
843
844 if (rh == NULL || owner == NULL || out_id == NULL)
845 return -1;
846 if (reqreg_ensure(rh) != 0)
847 return -1;
848
849 best = reqreg_take_lru(rh->reqreg, owner);
850 if (best == -1)
851 return -1;
852
853 *out_id = (uint8_t)best;
854 return best;
855}
856
857/*- Choose the Identifier for a blocking request or watchdog
858 * (REQ-NET2-SEND-010): reserved from the in-flight registry when one exists
859 * on a TCP/TLS/DTLS session, shared with RADCLI_REQUEST_SENDONLY requests;
860 * drawn at random otherwise.
861 *
862 * @param rh a handle to parsed configuration.
863 * @param out_id set to the Identifier to use.
864 * @param out_slot set to the reserved slot, to release once the exchange
865 * ends, or to -1 when nothing was reserved.
866 * @return 0 on success, -1 if every Identifier is in flight.
867 -*/
868int radcli2_priv_reqreg_pick_id(rc_handle *rh, uint8_t *out_id, int *out_slot)
869{
870 *out_slot = -1;
871 if (RC_USES_SESSION(rh) && rh->reqreg != NULL) {
872 int slot = reqreg_take_lru(rh->reqreg, NULL);
873
874 if (slot == -1)
875 return -1;
876 *out_id = (uint8_t)slot;
877 *out_slot = slot;
878 return 0;
879 }
880 *out_id = rc_get_random_byte();
881 return 0;
882}
883
884/*- Unconditionally vacate slot (valid=0, armed=0, owner=NULL, secret
885 * scrubbed, LRU-stamped free per REQ-NET2-SEND-016), making its Identifier
886 * available for reuse, and take its packet off the session's send queue
887 * (REQ-NET2-NET-005). Used to undo a reservation
888 * radcli_transport_send_async() failed to arm, by
889 * radcli_transport_async_abort() for a still-active, undelivered exchange,
890 * and once a reply or timeout resolves the exchange. -*/
891void radcli2_priv_reqreg_release(rc_handle *rh, int slot)
892{
893 struct radcli_reqreg *reg;
894
895 if (rh == NULL || rh->reqreg == NULL || slot < 0 || slot >= RADCLI_CTX_MAX_INFLIGHT)
896 return;
897 reg = rh->reqreg;
898
899 if (RC_USES_SESSION(rh))
900 radcli2_priv_sess_unqueue(rh, slot);
901
902 reg->slots[slot].valid = 0;
903 reg->slots[slot].armed = 0;
904 reg->slots[slot].owner = NULL;
905 memset(reg->slots[slot].secret, 0, sizeof(reg->slots[slot].secret));
906 reg->slots[slot].free_seq = ++reg->free_seq_ctr;
907}
908
909/*- Milliseconds remaining until the *earliest* deadline among every
910 * currently armed slot on rh (0 if one is already due), or -1 if rh has no
911 * registry yet or nothing is in flight. Used by lib/dae.c's
912 * radcli_ctx_get_poll() to fold RADCLI_REQUEST_SENDONLY's retransmit/
913 * timeout deadlines into its own timeout_ms, alongside DAE/watchdog
914 * deadlines (REQ-NET2-NET-001). -*/
915int radcli2_priv_reqreg_earliest_deadline_ms(rc_handle *rh)
916{
917 struct radcli_reqreg *reg;
918 int64_t earliest_ms = 0;
919 int have_one = 0;
920 int i;
921
922 if (rh == NULL || rh->reqreg == NULL)
923 return -1;
924 reg = rh->reqreg;
925
926 for (i = 0; i < RADCLI_CTX_MAX_INFLIGHT; i++) {
927 if (!reg->slots[i].valid || !reg->slots[i].armed)
928 continue;
929 if (!have_one || reg->slots[i].deadline_ms < earliest_ms) {
930 earliest_ms = reg->slots[i].deadline_ms;
931 have_one = 1;
932 }
933 }
934
935 if (!have_one)
936 return -1;
937
938 return rc_ms_until(earliest_ms);
939}
940
941/*- Hand one received reply to the in-flight registry slot it answers,
942 * validating it (REQ-NET2-SEND-016/017) and writing the outcome onto the
943 * slot's owner (struct radcli_async_send_st).
944 *
945 * @param rh a handle to parsed configuration.
946 * @param recv_buf the reply; modified in place (rc_check_reply()/
947 * decode_reply()).
948 * @param recv_buf_cap recv_buf's capacity in bytes.
949 * @param recv_length the number of bytes received into recv_buf.
950 * @param from the datagram's source for the UDP source check, or NULL on a
951 * session, whose socket is connected to the server.
952 * @return 1 if the reply resolved a slot, 0 if it was discarded.
953 -*/
954static int reqreg_deliver(rc_handle *rh, uint8_t *recv_buf, size_t recv_buf_cap,
955 int recv_length, const struct sockaddr *from)
956{
957 struct radcli_reqreg *reg = rh->reqreg;
958 AUTH_HDR *recv_auth = (AUTH_HDR *)recv_buf;
959 struct radcli_reqreg_slot *rslot;
960 uint8_t id;
961
962 if (reg == NULL)
963 return 0;
964 /* The caller's buffer is reused across reads: bytes past a short
965 * read belong to an earlier datagram (REQ-NET2-SEND-017). */
966 if ((size_t)recv_length < AUTH_HDR_LEN || recv_length < ntohs(recv_auth->length))
967 return 0;
968 id = recv_auth->id;
969
970 rslot = &reg->slots[id];
971 if (rslot->valid && !rslot->armed && id == rh->watchdog_slot) {
972 /* The watchdog's reply only frees its Identifier (REQ-NET2-SEND-010). */
973 radcli2_priv_reqreg_release(rh, id);
974 rh->watchdog_slot = -1;
975 return 1;
976 }
977 if (!rslot->valid || !rslot->armed)
978 return 0; /* no in-flight exchange for this Identifier */
979 if (from != NULL && !reqreg_peer_matches(from, SA(&rslot->peer)))
980 return 0;
981
982 if (rc_check_reply(recv_auth, (int)recv_buf_cap, rslot->secret,
983 rslot->vector, id) != OK_RC) {
984 /* BADRESPID_RC (unreachable: id already matched above)
985 * or BADRESP_RC (bad length or Response Authenticator --
986 * possibly spoofed) -- keep the slot waiting rather than
987 * handing an unverified packet to decode_reply(),
988 * matching the pre-registry single-exchange semantics
989 * (REQ-GEN-STYLE-009). */
990 return 0;
991 }
992
993 {
994 struct radcli_async_send_st *owner = rslot->owner;
995 char secret_copy[MAX_SECRET_LENGTH + 1];
996 unsigned char vector_copy[AUTH_VECTOR_LEN];
997 char server_name_copy[128];
998 unsigned short svc_port_copy;
999 rc_type type_copy;
1000 uint8_t req_code_copy;
1001 size_t recv_len = 0;
1002 uint8_t reply_code = 0;
1003 int decode_result;
1004 radcli_avp_list *attrs = NULL;
1005
1006 memcpy(secret_copy, rslot->secret, sizeof(secret_copy));
1007 memcpy(vector_copy, rslot->vector, sizeof(vector_copy));
1008 memcpy(server_name_copy, rslot->server_name, sizeof(server_name_copy));
1009 svc_port_copy = rslot->svc_port;
1010 type_copy = rslot->type;
1011 req_code_copy = rslot->send_buf[0];
1012
1013 /* Vacate now, before decode_reply()/radcli_avp_decode()
1014 * run: RFC 5080 SS2.1.1 permits reuse as soon as a valid
1015 * response is received, not once the application
1016 * collects it (REQ-NET2-SEND-016). */
1017 radcli2_priv_reqreg_release(rh, id);
1018
1019 decode_result = decode_reply(rh, NULL, server_name_copy, svc_port_copy,
1020 type_copy, req_code_copy, secret_copy, vector_copy,
1021 recv_buf, recv_buf_cap, &recv_len, &reply_code);
1022 if (decode_result == OK_RC || decode_result == REJECT_RC ||
1023 decode_result == CHALLENGE_RC) {
1024 if (recv_len > 0 &&
1025 radcli_avp_decode(rh, secret_copy, vector_copy, recv_buf, recv_len, 0,
1026 &attrs) != 0)
1027 decode_result = ERROR_RC;
1028 }
1029 memset(secret_copy, 0, sizeof(secret_copy));
1030
1031 owner->result = decode_result;
1032 owner->reply_code = reply_code;
1033 owner->reply_attrs = attrs;
1034 owner->delivered = 1;
1035 }
1036 return 1;
1037}
1038
1039/*- Route one packet read from rh's session to what it belongs to -- the
1040 * single routing point for every reader of the session (REQ-NET2-NET-004):
1041 * on a RadSec session, a Disconnect-/CoA-Request to the DAE pipeline; a
1042 * reply to the in-flight registry slot it answers; anything else is
1043 * dropped.
1044 *
1045 * @param rh a handle to parsed configuration.
1046 * @param buf the record; modified in place.
1047 * @param cap buf's capacity in bytes.
1048 * @param len the record's length in bytes.
1049 * @return RADSEC_ROUTE_DAE, RADSEC_ROUTE_REPLY, or RADSEC_ROUTE_DROPPED.
1050 -*/
1051int radcli2_priv_sess_route(rc_handle *rh, uint8_t *buf, size_t cap, int len)
1052{
1053 /* Only RadSec carries server-initiated requests back to the client
1054 * (REQ-DAE-INIT-010); over plain TCP they match nothing. */
1055 if ((rh->so_type == RC_SOCKET_TLS || rh->so_type == RC_SOCKET_DTLS) &&
1056 len >= 1 && (buf[0] == RADCLI_DISCONNECT_REQUEST || buf[0] == RADCLI_COA_REQUEST)) {
1057 radcli2_priv_dae_on_radsec_packet(rh, buf, (size_t)len);
1058 return RADSEC_ROUTE_DAE;
1059 }
1060 if (reqreg_deliver(rh, buf, cap, len, NULL))
1061 return RADSEC_ROUTE_REPLY;
1062 rc_log(LOG_INFO, "%s: packet with code %u matches nothing in flight on the "
1063 "session, ignored", __func__, len >= 1 ? (unsigned)buf[0] : 0U);
1064 return RADSEC_ROUTE_DROPPED;
1065}
1066
1067/*- Drain every ready datagram on ctx's shared UDP request socket
1068 * (rh->req_fd) into the in-flight registry, with explicit source-address
1069 * validation since the socket is shared and unconnected
1070 * (REQ-NET2-SEND-016). A no-op if no RADCLI_REQUEST_SENDONLY exchange
1071 * ever opened the socket. Never blocks. -*/
1072void radcli2_priv_reqreg_drain(rc_handle *rh)
1073{
1074 const rc_sockets_override *sfuncs;
1075 char *ns;
1076
1077 if (rh == NULL || rh->reqreg == NULL || rh->req_fd == -1)
1078 return;
1079 sfuncs = &rh->so;
1080 ns = rc_conf_str_id(rh, OPT_NAMESPACE);
1081
1082 for (;;) {
1083 uint8_t recv_buf[RC_BUFFER_LEN];
1084 struct sockaddr_storage from;
1085 socklen_t fromlen = sizeof(from);
1086 int recv_length;
1087 int ns_def_hdl = 0;
1088
1089 if (ns != NULL && -1 == rc_set_netns(ns, &ns_def_hdl)) {
1090 rc_log(LOG_ERR, "%s: namespace %s set failed", __func__, ns);
1091 return;
1092 }
1093 do {
1094 recv_length = sfuncs->recvfrom(sfuncs->ptr, rh->req_fd, (char *)recv_buf,
1095 sizeof(recv_buf), 0, SA(&from), &fromlen);
1096 } while (recv_length == -1 && errno == EINTR);
1097 if (ns != NULL)
1098 rc_reset_netns(&ns_def_hdl);
1099
1100 if (recv_length <= 0)
1101 return; /* nothing more ready, or a socket error no slot can act on */
1102
1103 reqreg_deliver(rh, recv_buf, sizeof(recv_buf), recv_length, SA(&from));
1104 }
1105}
1106
1107/*- Read every packet already available on rh's session and route
1108 * each (radcli2_priv_sess_route()), stopping after a DAE request so that
1109 * a burst of them re-arms the caller's loop one per call. Never blocks. -*/
1110void radcli2_priv_sess_drain(rc_handle *rh)
1111{
1112 for (;;) {
1113 uint8_t recv_buf[RC_BUFFER_LEN];
1114 int recv_length;
1115
1116 recv_length = radcli2_priv_sess_try_recv(rh, recv_buf, sizeof(recv_buf));
1117 if (recv_length <= 0)
1118 return;
1119 if (radcli2_priv_sess_route(rh, recv_buf, sizeof(recv_buf), recv_length) ==
1120 RADSEC_ROUTE_DAE)
1121 return;
1122 }
1123}
1124
1125/*- Service every registry slot whose retransmit/timeout deadline has
1126 * passed: retransmit (if retries remain) or resolve as TIMEOUT_RC
1127 * (vacating the slot), writing the outcome directly onto the owning struct
1128 * radcli_async_send_st. A no-op if rh->reqreg is NULL. Never blocks. -*/
1129void radcli2_priv_reqreg_service_timeouts(rc_handle *rh)
1130{
1131 struct radcli_reqreg *reg;
1132 const rc_sockets_override *sfuncs;
1133 int on_session;
1134 char *ns;
1135 int i;
1136
1137 if (rh == NULL || rh->reqreg == NULL)
1138 return;
1139 reg = rh->reqreg;
1140 sfuncs = &rh->so;
1141 on_session = RC_USES_SESSION(rh);
1142 ns = rc_conf_str_id(rh, OPT_NAMESPACE);
1143
1144 for (i = 0; i < RADCLI_CTX_MAX_INFLIGHT; i++) {
1145 struct radcli_reqreg_slot *rslot = &reg->slots[i];
1146
1147 if (!rslot->valid || !rslot->armed || rc_getmtime_ms() < rslot->deadline_ms)
1148 continue;
1149
1150 if (rslot->retries_left-- <= 0) {
1151 struct radcli_async_send_st *owner = rslot->owner;
1152 char server_name_copy[128];
1153 unsigned short svc_port_copy = rslot->svc_port;
1154
1155 memcpy(server_name_copy, rslot->server_name, sizeof(server_name_copy));
1156 radcli2_priv_reqreg_release(rh, i);
1157
1158 rc_log(LOG_ERR, "%s: no reply from RADIUS server %s:%u",
1159 __func__, server_name_copy, svc_port_copy);
1160 owner->result = TIMEOUT_RC;
1161 owner->reply_code = 0;
1162 owner->reply_attrs = NULL;
1163 owner->delivered = 1;
1164 continue;
1165 }
1166
1167 if (on_session) {
1168 /* RFC 6613 SS2.6.1: never resent over the stream connection
1169 * it already went out on; it keeps waiting there instead
1170 * (REQ-NET-NET-022). A packet still queued has not gone
1171 * out at all yet. Otherwise never waits, not even to
1172 * reconnect: a retransmit the session cannot take now is
1173 * queued (REQ-NET2-NET-001/005); either way its timeout
1174 * runs on. */
1175 if (!radcli2_priv_sess_queued(rh, i) &&
1176 !radcli2_priv_sess_holds(rh, rslot->conn_gen)) {
1177 radcli2_priv_sess_send_queued(rh, rslot->send_buf,
1178 (size_t)rslot->send_len,
1179 RADSEC_SEND_RETRANSMIT, i);
1180 rslot->conn_gen = radcli2_priv_sess_gen(rh);
1181 }
1182 rslot->deadline_ms = rc_getmtime_ms() + rslot->timeout_ms;
1183 continue;
1184 }
1185
1186 {
1187 int ns_def_hdl = 0;
1188 int sresult;
1189
1190 if (rh->req_fd == -1)
1191 continue;
1192
1193 if (ns != NULL && -1 == rc_set_netns(ns, &ns_def_hdl)) {
1194 rc_log(LOG_ERR, "%s: namespace %s set failed", __func__, ns);
1195 continue;
1196 }
1197
1198 do {
1199 sresult = sfuncs->sendto(sfuncs->ptr, rh->req_fd, (const char *)rslot->send_buf,
1200 (unsigned int)rslot->send_len, 0,
1201 SA(&rslot->peer), rslot->peer_len);
1202 } while (sresult == -1 && errno == EINTR);
1203
1204 if (ns != NULL)
1205 rc_reset_netns(&ns_def_hdl);
1206
1207 if (sresult == -1) {
1208 rc_log(LOG_ERR, "%s: sendto: %s", __func__, strerror(errno));
1209 continue; /* leave deadline as-is; retried again next call */
1210 }
1211
1212 rslot->deadline_ms = rc_getmtime_ms() + rslot->timeout_ms;
1213 }
1214 }
1215}
1216
1217/*- Begin an async (poll-driven) send: reserve slot in rh's in-flight
1218 * registry, resolve server_name to its first address only (no DNS
1219 * fail-over, matching radcli_transport_exchange()'s own no_wait
1220 * simplification), send send_buf once over ctx's shared, persistent
1221 * request socket (UDP, opened lazily here if not already; TCP/TLS/DTLS
1222 * reuse the session, establishing it if needed), and arm the slot for
1223 * radcli_ctx_dispatch() to drive to completion -- REQ-NET2-SEND-016.
1224 *
1225 * Unlike radcli_transport_exchange(), does not itself hold the configured
1226 * network namespace (lib/util.c's rc_set_netns()) switched for its whole
1227 * duration: namespace membership is per-thread, and this call, unlike a
1228 * blocking exchange, returns to a caller's event loop that may run other
1229 * socket I/O on the same thread before radcli_ctx_dispatch() is next
1230 * called -- switching once and resetting only at the very end would leak
1231 * the RADIUS server's namespace into that other I/O. Instead, each of this
1232 * function and the registry's drain/retransmit helpers brackets only its
1233 * own, brief syscall(s) with a set/reset pair.
1234 *
1235 * @param rh a handle to parsed configuration.
1236 * @param slot the registry slot radcli2_priv_reqreg_reserve() already
1237 * reserved for this exchange -- its Identifier MUST already be baked into
1238 * send_buf (radcli_encode_request()'s forced_id), not patched in here.
1239 * @param server_name the server to resolve and contact.
1240 * @param svc_port overrides the resolved port when non-zero.
1241 * @param secret the shared secret; radcli2_priv_find_server_addr() may
1242 * overwrite it, exactly as radcli_transport_exchange() does.
1243 * @param type AUTH or ACCT.
1244 * @param send_buf the complete, pre-built, pre-encoded packet to send.
1245 * @param send_len send_buf's length in bytes; must fit RC_BUFFER_LEN.
1246 * @param timeout_ms per-attempt reply wait, in milliseconds.
1247 * @param retries additional retransmit attempts after the first.
1248 * @param nonblock nonzero to never wait for the network: what cannot go
1249 * out at once is queued on a session, or lost on UDP (REQ-NET2-SEND-018).
1250 * @param out zeroed, then filled in on success; left inactive (out->active
1251 * == 0) on failure -- the caller MUST then release slot itself
1252 * (radcli2_priv_reqreg_release()), since this function does not on failure
1253 * (the reservation is the caller's, made before encoding).
1254 * @return OK_RC once the first packet is on the wire (or, with nonblock,
1255 * queued or lost), ERROR_RC on failure.
1256 -*/
1257int radcli_transport_send_async(rc_handle *rh, int slot, char *server_name, unsigned short svc_port,
1258 char secret[MAX_SECRET_LENGTH + 1], rc_type type,
1259 const uint8_t *send_buf, int send_len,
1260 int timeout_ms, int retries, unsigned nonblock,
1261 struct radcli_async_send_st *out)
1262{
1263 struct addrinfo *auth_addr = NULL;
1264 const rc_sockets_override *sfuncs;
1265 struct sockaddr_storage our_sockaddr;
1266 unsigned discover_local_ip;
1267 struct radcli_reqreg *reg;
1268 struct radcli_reqreg_slot *rslot;
1269 char *ns = NULL;
1270 int ns_def_hdl = 0;
1271 int sockfd = -1;
1272 int on_session;
1273 int result;
1274
1275 memset(out, 0, sizeof(*out));
1276
1277 if (rh == NULL || rh->reqreg == NULL || slot < 0 || slot >= RADCLI_CTX_MAX_INFLIGHT)
1278 return ERROR_RC;
1279 reg = rh->reqreg;
1280 rslot = &reg->slots[slot];
1281 on_session = RC_USES_SESSION(rh);
1282
1283 if (server_name == NULL || server_name[0] == '\0')
1284 return ERROR_RC;
1285 if (send_len < AUTH_HDR_LEN || (size_t)send_len > sizeof(rslot->send_buf))
1286 return ERROR_RC;
1287
1288 ns = rc_conf_str_id(rh, OPT_NAMESPACE);
1289 if (ns != NULL) {
1290 if (-1 == rc_set_netns(ns, &ns_def_hdl)) {
1291 rc_log(LOG_ERR, "%s: namespace %s set failed", __func__, ns);
1292 return ERROR_RC;
1293 }
1294 }
1295
1296 if (radcli2_priv_find_server_addr(rh, server_name, &auth_addr, secret, type) != 0) {
1297 rc_log(LOG_ERR, "%s: unable to find server: %s", __func__, server_name);
1298 result = ERROR_RC;
1299 goto exit_error;
1300 }
1301
1302 sfuncs = &rh->so;
1303
1304 if (sfuncs->static_secret)
1305 strlcpy(secret, sfuncs->static_secret, MAX_SECRET_LENGTH + 1);
1306
1307 if (svc_port) {
1308 if (auth_addr->ai_family == AF_INET)
1309 ((struct sockaddr_in *)auth_addr->ai_addr)->sin_port = htons(svc_port);
1310 else
1311 ((struct sockaddr_in6 *)auth_addr->ai_addr)->sin6_port = htons(svc_port);
1312 }
1313
1314 if (on_session && nonblock) {
1315 /* Sending, below, begins connecting instead (REQ-NET2-SEND-018). */
1316 } else if (on_session) {
1317 /* get_fd(), not get_active_fd(): establishes the session if it
1318 * is not up yet (REQ-NET2-SEND-012, REQ-NET-NET-019). */
1319 sockfd = sfuncs->get_fd(sfuncs->ptr, NULL);
1320 if (sockfd < 0) {
1321 rc_log(LOG_ERR, "%s: cannot connect to the server", __func__);
1322 result = ERROR_RC;
1323 goto fail;
1324 }
1325 } else if (rh->req_fd != -1) {
1326 sockfd = rh->req_fd;
1327 } else {
1328 rc_own_bind_addr(rh, &our_sockaddr);
1329 discover_local_ip = 0;
1330 if (our_sockaddr.ss_family == AF_INET &&
1331 ((struct sockaddr_in *)(&our_sockaddr))->sin_addr.s_addr == INADDR_ANY)
1332 discover_local_ip = 1;
1333
1334 if (discover_local_ip) {
1335 /* REQ-NET2-SEND-016: this fixes the source address at
1336 * first use (from whichever destination happens to
1337 * trigger it), unlike the old per-request socket,
1338 * which rediscovered it per destination -- acceptable
1339 * on a single-homed host; a multi-homed one with no
1340 * explicit bindaddr may get a suboptimal source
1341 * address for a later request to a different
1342 * destination (e.g. acctserver after authserver).
1343 * Configure bindaddr explicitly to avoid this. */
1344 result = radcli2_priv_get_srcaddr(SA(&our_sockaddr), auth_addr->ai_addr);
1345 if (result != OK_RC) {
1346 rc_log(LOG_ERR, "%s: cannot figure our own address", __func__);
1347 result = ERROR_RC;
1348 goto fail;
1349 }
1350 }
1351
1352 if (sfuncs->get_fd) {
1353 sockfd = sfuncs->get_fd(sfuncs->ptr, SA(&our_sockaddr));
1354 if (sockfd < 0) {
1355 rc_log(LOG_ERR, "%s: socket: %s", __func__, strerror(errno));
1356 result = ERROR_RC;
1357 goto fail;
1358 }
1359 /* REQ-NET2-SEND-016: radcli2_priv_reqreg_drain() loops
1360 * recvfrom() on this socket until EAGAIN -- a blocking
1361 * socket would hang the caller's entire event loop on
1362 * the last, empty call instead of returning promptly. */
1363 if (radcli2_priv_set_nonblock_cloexec(sockfd) != 0) {
1364 rc_log(LOG_ERR, "%s: fcntl: %s", __func__, strerror(errno));
1365 result = ERROR_RC;
1366 if (sfuncs->close_fd)
1367 sfuncs->close_fd(sockfd);
1368 goto fail;
1369 }
1370 /* Commit immediately, not at the end of this branch: any
1371 * later step failing (the IPv6 setsockopt below) must
1372 * still leave a good, already-nonblocking socket in
1373 * rh->req_fd for the next call to reuse, rather than
1374 * leaking a freshly opened one that fail: below
1375 * deliberately never closes (it may be an *already*
1376 * persistent rh->req_fd from a previous call, which
1377 * must never be closed just because this one send
1378 * failed). */
1379 rh->req_fd = sockfd;
1380 }
1381
1382 if (sockfd >= 0 && our_sockaddr.ss_family == AF_INET6 &&
1383 radcli2_priv_prefer_public_addr(rh, sockfd) < 0) {
1384 result = ERROR_RC;
1385 goto fail;
1386 }
1387 }
1388
1389 /* Filled in before sending: a queued packet stays in the slot. */
1390 memcpy(&rslot->peer, auth_addr->ai_addr, auth_addr->ai_addrlen);
1391 rslot->peer_len = auth_addr->ai_addrlen;
1392 memcpy(rslot->send_buf, send_buf, (size_t)send_len);
1393 rslot->send_len = send_len;
1394
1395 if (on_session && nonblock) {
1396 result = radcli2_priv_sess_send_queued(rh, rslot->send_buf, (size_t)send_len,
1397 RADSEC_SEND_REQUEST, slot);
1398 if (result == -1) {
1399 rc_log(LOG_ERR, "%s: cannot send to the server", __func__);
1400 result = ERROR_RC;
1401 goto fail;
1402 }
1403 } else {
1404 do {
1405 result = sfuncs->sendto(sfuncs->ptr, sockfd, (const char *)send_buf,
1406 (unsigned int)send_len, 0,
1407 SA(auth_addr->ai_addr), auth_addr->ai_addrlen);
1408 } while (result == -1 && errno == EINTR);
1409 /* A datagram the socket has no room for is lost; its
1410 * retransmission follows (REQ-NET2-SEND-018). */
1411 if (result == -1 && nonblock && (errno == EAGAIN || errno == EWOULDBLOCK))
1412 result = 0;
1413 if (result == -1) {
1414 rc_log(LOG_ERR, "%s: sendto: %s", __func__, strerror(errno));
1415 result = ERROR_RC;
1416 goto fail;
1417 }
1418 }
1419
1420 rslot->conn_gen = radcli2_priv_sess_gen(rh);
1421 memcpy(rslot->vector, send_buf + 4, AUTH_VECTOR_LEN); /* AUTH_HDR: code(1) id(1) length(2) vector(16) */
1422 strlcpy(rslot->secret, secret, sizeof(rslot->secret));
1423 strlcpy(rslot->server_name, server_name, sizeof(rslot->server_name));
1424 rslot->svc_port = svc_port;
1425 rslot->type = type;
1426 rslot->timeout_ms = (timeout_ms > 0) ? timeout_ms : 1000;
1427 rslot->retries_left = retries;
1428 rslot->deadline_ms = rc_getmtime_ms() + rslot->timeout_ms;
1429 rslot->armed = 1;
1430
1431 out->rh = rh;
1432 out->active = 1;
1433 out->slot = slot;
1434 out->delivered = 0;
1435
1436 result = OK_RC;
1437 goto exit_ok;
1438
1439 fail:
1440 memset(secret, '\0', MAX_SECRET_LENGTH + 1);
1441 exit_ok:
1442 if (auth_addr)
1443 freeaddrinfo(auth_addr);
1444 exit_error:
1445 if (ns != NULL) {
1446 if (-1 == rc_reset_netns(&ns_def_hdl))
1447 rc_log(LOG_ERR, "%s: namespace %s reset failed", __func__, ns);
1448 }
1449 return result;
1450}
1451
1452/*- Release st's registry slot without waiting for a terminal result. A
1453 * no-op if st is not active (never sent, or already terminal/delivered).
1454 * Used by lib/request.c's radcli_request_free() for the fire-and-forget
1455 * case: a RADCLI_REQUEST_SENDONLY request whose caller never drove it to a
1456 * terminal result via radcli_ctx_dispatch()/radcli_request_done(). If st
1457 * was already delivered but never read via radcli_request_done(), frees
1458 * st->reply_attrs instead (the slot is already vacated by then --
1459 * REQ-NET2-SEND-016 vacates on delivery, not on collection). -*/
1460void radcli_transport_async_abort(struct radcli_async_send_st *st)
1461{
1462 if (st == NULL || !st->active)
1463 return;
1464
1465 if (!st->delivered)
1466 radcli2_priv_reqreg_release(st->rh, st->slot);
1467 else
1468 radcli_avp_list_free(st->reply_attrs);
1469 st->active = 0;
1470}
1471
rc_type
Definition radcli.h:81
struct rc_aaa_ctx_st RC_AAA_CTX
Definition radcli.h:295
@ ACCT
Request for accounting server.
Definition radcli.h:83
@ AUTH
Request for authentication server.
Definition radcli.h:82
@ RC_SOCKET_DTLS
DTLS socket.
Definition radcli.h:115
@ RC_SOCKET_TLS
TLS socket.
Definition radcli.h:114