The FreeRADIUS server $Id: 15bac2a4c627c01d1aa2047687b3418955ac7f00 $
Loading...
Searching...
No Matches
radsniff.c
Go to the documentation of this file.
1/*
2 * This program is is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or (at
5 * your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17/**
18 * $Id: 73344aa0c2d37c5c1dc43ad69d57031f9714cc4f $
19 * @file radsniff.c
20 * @brief Capture, filter, and generate statistics for RADIUS traffic
21 *
22 * @copyright 2013 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
23 * @copyright 2006 The FreeRADIUS server project
24 * @copyright 2006 Nicolas Baradakis (nicolas.baradakis@cegetel.net)
25 */
26
27RCSID("$Id: 73344aa0c2d37c5c1dc43ad69d57031f9714cc4f $")
28
29#include <fcntl.h>
30#include <time.h>
31#include <math.h>
32
33#include <freeradius-devel/autoconf.h>
34#include <freeradius-devel/radius/list.h>
35#include <freeradius-devel/util/conf.h>
36#include <freeradius-devel/util/event.h>
37#include <freeradius-devel/util/file.h>
38#include <freeradius-devel/util/syserror.h>
39#include <freeradius-devel/util/atexit.h>
40#include <freeradius-devel/util/pair_legacy.h>
41#include <freeradius-devel/util/base16.h>
42#include <freeradius-devel/util/pcap.h>
43#include <freeradius-devel/util/timeval.h>
44
45#ifdef HAVE_COLLECTDC_H
46# include <collectd/client.h>
47#endif
48
49#include "radsniff.h"
50
51#define RS_ASSERT(_x) if (!(_x) && !fr_cond_assert(_x)) exit(1)
52
53static rs_t *conf;
54static struct timeval start_pcap = {0, 0};
55static char timestr[50];
56
58static fr_rb_tree_t *link_tree = NULL;
60static bool cleanup;
61static int packets_count = 1; // Used in '$PATH/${packet}.txt.${count}'
62
63static int self_pipe[2] = {-1, -1}; //!< Signals from sig handlers
64
65static char const *radsniff_version = RADIUSD_VERSION_BUILD("radsniff");
66
67static int rs_useful_codes[] = {
68 FR_RADIUS_CODE_ACCESS_REQUEST, //!< RFC2865 - Authentication request
69 FR_RADIUS_CODE_ACCESS_ACCEPT, //!< RFC2865 - Access-Accept
70 FR_RADIUS_CODE_ACCESS_REJECT, //!< RFC2865 - Access-Reject
71 FR_RADIUS_CODE_ACCOUNTING_REQUEST, //!< RFC2866 - Accounting-Request
72 FR_RADIUS_CODE_ACCOUNTING_RESPONSE, //!< RFC2866 - Accounting-Response
73 FR_RADIUS_CODE_ACCESS_CHALLENGE, //!< RFC2865 - Access-Challenge
74 FR_RADIUS_CODE_STATUS_SERVER, //!< RFC2865/RFC5997 - Status Server (request)
75 FR_RADIUS_CODE_DISCONNECT_REQUEST, //!< RFC3575/RFC5176 - Disconnect-Request
76 FR_RADIUS_CODE_DISCONNECT_ACK, //!< RFC3575/RFC5176 - Disconnect-Ack (positive)
77 FR_RADIUS_CODE_DISCONNECT_NAK, //!< RFC3575/RFC5176 - Disconnect-Nak (not willing to perform)
78 FR_RADIUS_CODE_COA_REQUEST, //!< RFC3575/RFC5176 - CoA-Request
79 FR_RADIUS_CODE_COA_ACK, //!< RFC3575/RFC5176 - CoA-Ack (positive)
80 FR_RADIUS_CODE_COA_NAK, //!< RFC3575/RFC5176 - CoA-Nak (not willing to perform)
81};
82
84 { L("error"), RS_ERROR },
85 { L("noreq"), RS_UNLINKED },
86 { L("norsp"), RS_LOST },
87 { L("received"), RS_NORMAL },
88 { L("reused"), RS_REUSED },
89 { L("rtx"), RS_RTX }
90};
92
94static fr_dict_t const *dict_radius;
95
98 { .out = &dict_freeradius, .proto = "freeradius" },
99 { .out = &dict_radius, .proto = "radius" },
100 { NULL }
101};
102
104
107 { .out = &attr_packet_type, .name = "Packet-Type", .type = FR_TYPE_UINT32, .dict = &dict_radius },
108 { NULL }
109};
110
111static NEVER_RETURNS void usage(int status);
112
113/** Fork and kill the parent process, writing out our PID
114 *
115 * @param pidfile the PID file to write our PID to
116 */
117static void rs_daemonize(char const *pidfile)
118{
119 FILE *fp;
120 pid_t pid, sid;
121
122 pid = fork();
123 if (pid < 0) {
124 fr_exit_now(EXIT_FAILURE);
125 }
126
127 /*
128 * Kill the parent...
129 */
130 if (pid > 0) {
131 close(self_pipe[0]);
132 close(self_pipe[1]);
133 fr_exit_now(EXIT_SUCCESS);
134 }
135
136 /*
137 * Continue as the child.
138 */
139
140 /* Create a new SID for the child process */
141 sid = setsid();
142 if (sid < 0) {
143 fr_exit_now(EXIT_FAILURE);
144 }
145
146 /*
147 * Change the current working directory. This prevents the current
148 * directory from being locked; hence not being able to remove it.
149 */
150 if ((chdir("/")) < 0) {
151 fr_exit_now(EXIT_FAILURE);
152 }
153
154 /*
155 * And write it AFTER we've forked, so that we write the
156 * correct PID.
157 */
158 fp = fopen(pidfile, "w");
159 if (fp != NULL) {
160 fprintf(fp, "%d\n", (int) sid);
161 fclose(fp);
162 } else {
163 ERROR("Failed creating PID file %s: %s", pidfile, fr_syserror(errno));
164 fr_exit_now(EXIT_FAILURE);
165 }
166
167 /*
168 * Close stdout and stderr if they've not been redirected.
169 */
170 if (isatty(fileno(stdout))) {
171 if (!freopen("/dev/null", "w", stdout)) {
172 fr_exit_now(EXIT_FAILURE);
173 }
174 }
175
176 if (isatty(fileno(stderr))) {
177 if (!freopen("/dev/null", "w", stderr)) {
178 fr_exit_now(EXIT_FAILURE);
179 }
180 }
181}
182
183static void rs_tv_add_ms(struct timeval const *start, unsigned long interval, struct timeval *result) {
184 result->tv_sec = start->tv_sec + (interval / 1000);
185 result->tv_usec = start->tv_usec + ((interval % 1000) * 1000);
186
187 if (result->tv_usec > USEC) {
188 result->tv_usec -= USEC;
189 result->tv_sec++;
190 }
191}
192
193static void rs_time_print(char *out, size_t len, struct timeval const *t)
194{
195 size_t ret;
196 struct timeval now;
197 uint32_t usec;
198 struct tm result;
199
200 if (!t) {
202 t = &now;
203 }
204
205 ret = strftime(out, len, "%Y-%m-%d %H:%M:%S", localtime_r(&t->tv_sec, &result));
206 if (ret >= len) {
207 return;
208 }
209
210 usec = t->tv_usec;
211
212 if (usec) {
213 while (usec < 100000) usec *= 10;
214 snprintf(out + ret, len - ret, ".%u", usec);
215 } else {
216 snprintf(out + ret, len - ret, ".000000");
217 }
218}
219
220static size_t rs_snprint_csv(char *out, size_t outlen, char const *in, size_t inlen)
221{
222 char const *start = out;
223 uint8_t const *str = (uint8_t const *) in;
224
225 if (!in) {
226 if (outlen) {
227 *out = '\0';
228 }
229
230 return 0;
231 }
232
233 if (inlen == 0) {
234 inlen = strlen(in);
235 }
236
237 while ((inlen > 0) && (outlen > 2)) {
238 /*
239 * Escape double quotes with... MORE DOUBLE QUOTES!
240 */
241 if (*str == '"') {
242 *out++ = '"';
243 outlen--;
244 }
245
246 /*
247 * Safe chars which require no escaping
248 */
249 if ((*str == '\r') || (*str == '\n') || ((*str >= '\x20') && (*str <= '\x7E'))) {
250 *out++ = *str++;
251 outlen--;
252 inlen--;
253
254 continue;
255 }
256
257 /*
258 * Everything else is dropped
259 */
260 str++;
261 inlen--;
262 }
263 *out = '\0';
264
265 return out - start;
266}
267
269{
270 char buffer[2048];
271 char *p = buffer;
272 int i;
273
274 ssize_t len, s = sizeof(buffer);
275
276 len = strlcpy(p, "\"Status\",\"Count\",\"Time\",\"Latency\",\"Type\",\"Interface\","
277 "\"Src IP\",\"Src Port\",\"Dst IP\",\"Dst Port\",\"ID\",", s);
278 p += len;
279 s -= len;
280
281 if (s <= 0) return;
282
283 for (i = 0; i < conf->list_da_num; i++) {
284 char const *in;
285
286 *p++ = '"';
287 s -= 1;
288 if (s <= 0) return;
289
290 for (in = conf->list_da[i]->name; *in; in++) {
291 *p++ = *in;
292 s -= len;
293 if (s <= 0) return;
294 }
295
296 *p++ = '"';
297 s -= 1;
298 if (s <= 0) return;
299 *p++ = ',';
300 s -= 1;
301 if (s <= 0) return;
302 }
303
304 *--p = '\0';
305
306 fprintf(stdout , "%s\n", buffer);
307}
308
309static void rs_packet_print_csv(uint64_t count, rs_status_t status, fr_pcap_t *handle,
310 fr_packet_t *packet, fr_pair_list_t *list,
311 UNUSED struct timeval *elapsed, struct timeval *latency, UNUSED bool response,
312 bool body)
313{
314 char const *status_str;
315 char buffer[1024];
316 fr_sbuff_t sbuff = FR_SBUFF_OUT(buffer, sizeof(buffer));
317
318 char src[INET6_ADDRSTRLEN];
319 char dst[INET6_ADDRSTRLEN];
320
321 inet_ntop(packet->socket.inet.src_ipaddr.af, &packet->socket.inet.src_ipaddr.addr, src, sizeof(src));
322 inet_ntop(packet->socket.inet.dst_ipaddr.af, &packet->socket.inet.dst_ipaddr.addr, dst, sizeof(dst));
323
324 status_str = fr_table_str_by_value(rs_events, status, NULL);
325 RS_ASSERT(status_str);
326
327 if (fr_sbuff_in_sprintf(&sbuff, "%s,%" PRIu64 ",%s,", status_str, count, timestr) < 0) return;
328
329 if (latency) {
330 if (fr_sbuff_in_sprintf(&sbuff, "%u.%03u,",
331 (unsigned int) latency->tv_sec,
332 ((unsigned int) latency->tv_usec / 1000)) < 0) return;
333 } else {
334 if (fr_sbuff_in_char(&sbuff, ',') < 0) return;
335 }
336
337 /* Status, Type, Interface, Src, Src port, Dst, Dst port, ID */
338 if (FR_RADIUS_PACKET_CODE_VALID(packet->code)) {
339 if (fr_sbuff_in_sprintf(&sbuff, "%s,%s,%s,%i,%s,%i,%i,",
340 fr_radius_packet_name[packet->code], handle->name,
341 src, packet->socket.inet.src_port, dst, packet->socket.inet.dst_port, packet->id) < 0) return;
342 } else {
343 if (fr_sbuff_in_sprintf(&sbuff, "%u,%s,%s,%i,%s,%i,%i,", packet->code, handle->name,
344 src, packet->socket.inet.src_port, dst, packet->socket.inet.dst_port, packet->id) < 0) return;
345 }
346
347 if (body) {
348 int i;
349 fr_pair_t *vp;
350
351 for (i = 0; i < conf->list_da_num; i++) {
352 vp = fr_pair_find_by_da(list, NULL, conf->list_da[i]);
353 if (vp && (vp->vp_length > 0)) {
354 if (conf->list_da[i]->type == FR_TYPE_STRING) {
355 ssize_t slen;
356
357 if (fr_sbuff_in_char(&sbuff, '"') < 0) return;
358
359 slen = rs_snprint_csv(fr_sbuff_current(&sbuff), fr_sbuff_remaining(&sbuff),
360 vp->vp_strvalue, vp->vp_length);
361 if (slen < 0) return;
362 fr_sbuff_advance(&sbuff, (size_t)slen);
363
364 if (fr_sbuff_in_char(&sbuff, '"') < 0) return;
365 } else {
366 if (fr_pair_print_value_quoted(&sbuff, vp, T_BARE_WORD) < 0) return;
367 }
368 }
369
370 if (fr_sbuff_in_char(&sbuff, ',') < 0) return;
371 }
372 } else {
373 if (fr_sbuff_remaining(&sbuff) < (size_t)conf->list_da_num) return;
374
375 memset(fr_sbuff_current(&sbuff), ',', conf->list_da_num);
377 fr_sbuff_terminate(&sbuff);
378 }
379
380 fprintf(stdout , "%s\n", buffer);
381}
382
383static void rs_packet_print_fancy(uint64_t count, rs_status_t status, fr_pcap_t *handle,
384 fr_packet_t *packet, fr_pair_list_t *list,
385 struct timeval *elapsed, struct timeval *latency, bool response, bool body)
386{
387 char buffer[2048];
388 char *p = buffer;
389
390 char src[INET6_ADDRSTRLEN];
391 char dst[INET6_ADDRSTRLEN];
392
393 ssize_t len, s = sizeof(buffer);
394
395 inet_ntop(packet->socket.inet.src_ipaddr.af, &packet->socket.inet.src_ipaddr.addr, src, sizeof(src));
396 inet_ntop(packet->socket.inet.dst_ipaddr.af, &packet->socket.inet.dst_ipaddr.addr, dst, sizeof(dst));
397
398 /* Only print out status str if something's not right */
399 if (status != RS_NORMAL) {
400 char const *status_str;
401
402 status_str = fr_table_str_by_value(rs_events, status, NULL);
403 RS_ASSERT(status_str);
404
405 len = snprintf(p, s, "** %s ** ", status_str);
406 p += len;
407 s -= len;
408 if (s <= 0) return;
409 }
410
411 if (FR_RADIUS_PACKET_CODE_VALID(packet->code)) {
412 len = snprintf(p, s, "%s Id %i %s:%s:%d %s %s:%i ",
414 packet->id,
415 handle->name,
416 response ? dst : src,
417 response ? packet->socket.inet.dst_port : packet->socket.inet.src_port,
418 response ? "<-" : "->",
419 response ? src : dst ,
420 response ? packet->socket.inet.src_port : packet->socket.inet.dst_port);
421 } else {
422 len = snprintf(p, s, "%u Id %i %s:%s:%i %s %s:%i ",
423 packet->code,
424 packet->id,
425 handle->name,
426 response ? dst : src,
427 response ? packet->socket.inet.dst_port : packet->socket.inet.src_port,
428 response ? "<-" : "->",
429 response ? src : dst ,
430 response ? packet->socket.inet.src_port : packet->socket.inet.dst_port);
431 }
432 p += len;
433 s -= len;
434 if (s <= 0) return;
435
436 if (elapsed) {
437 len = snprintf(p, s, "+%u.%03u ",
438 (unsigned int) elapsed->tv_sec, ((unsigned int) elapsed->tv_usec / 1000));
439 p += len;
440 s -= len;
441 if (s <= 0) return;
442 }
443
444 if (latency) {
445 len = snprintf(p, s, "+%u.%03u ",
446 (unsigned int) latency->tv_sec, ((unsigned int) latency->tv_usec / 1000));
447 p += len;
448 s -= len;
449 if (s <= 0) return;
450 }
451
452 *--p = '\0';
453
454 RIDEBUG("%s", buffer);
455
456 if (body) {
457 /*
458 * Print out verbose HEX output
459 */
462 }
463
465 char vector[(RADIUS_AUTH_VECTOR_LENGTH * 2) + 1];
466 fr_sbuff_t vector_sbuff = FR_SBUFF_OUT(vector, sizeof(vector));
467
469 fr_pair_list_log(&default_log, 4, list);
470
471 fr_base16_encode(&vector_sbuff,
473 INFO("\tAuthenticator-Field = 0x%s", fr_sbuff_start(&vector_sbuff));
474 }
475 }
476}
477
478static void rs_packet_save_in_output_dir(uint64_t count, UNUSED rs_status_t status, UNUSED fr_pcap_t *handle,
479 fr_packet_t *packet, fr_pair_list_t *list,
480 UNUSED struct timeval *elapsed, UNUSED struct timeval *latency, bool response, bool body)
481{
482 fr_log_t output_file;
483 char vector[(RADIUS_AUTH_VECTOR_LENGTH * 2) + 1];
484 fr_sbuff_t vector_sbuff = FR_SBUFF_OUT(vector, sizeof(vector));
485 char const *packet_type = response ? "reply" : "request";
486 char filename[2048];
487
488 if (!body) return;
489
490 snprintf(filename, sizeof(filename), "%s/%s.%d.txt", conf->output_dir, packet_type, packets_count);
491
492 if (fr_debug_lvl > 0) {
493 DEBUG2("Saving %s in %s", packet_type, filename);
494 }
495
496 /* ensure to remove existing file */
497 if (fr_unlink(filename) < 0) usage(64);
498
499 if (fr_log_init_file(&output_file, filename) < 0) {
500 ERROR("Failed opening %s output file.", filename);
501 usage(64);
502 }
503
504 output_file.print_level = false;
505 output_file.timestamp = L_TIMESTAMP_OFF;
506
507 /* dump the packet into filesystem */
509 fr_pair_list_log(&output_file, 0, list);
510
511 /* then append the Authenticator-Field */
512 fr_base16_encode(&vector_sbuff,
514
515 fprintf(output_file.handle, "Authenticator-Field = 0x%s\n", fr_sbuff_start(&vector_sbuff));
516
517 if (fr_log_close(&output_file) < 0) {
518 ERROR("Failed closing %s output file.", filename);
519 usage(64);
520 }
521
522 /*
523 * We need to have $PATH/{request,reply}.txt with the same ID
524 * to be possible cross the packets.
525 */
526 if ((count % 2) == 0) packets_count++;
527}
528
529static inline void rs_packet_print(rs_request_t *request, uint64_t count, rs_status_t status, fr_pcap_t *handle,
530 fr_packet_t *packet, fr_pair_list_t *list,
531 struct timeval *elapsed, struct timeval *latency,
532 bool response, bool body)
533{
534 if (!conf->logger) return;
535
536 if (request) request->logged = true;
537 conf->logger(count, status, handle, packet, list, elapsed, latency, response, body);
538}
539
540/** Query libpcap to see if it dropped any packets
541 *
542 * We need to check to see if libpcap dropped any packets and if it did, we need to stop stats output for long
543 * enough for inaccurate statistics to be cleared out.
544 *
545 * @param in pcap handle to check.
546 * @return
547 * - 0 No drops.
548 * - -1 We couldn't check.
549 * - -2 Dropped because of buffer exhaustion.
550 * - -3 Dropped because of NIC.
551 */
552static int rs_check_pcap_drop(fr_pcap_t *in)
553{
554 int ret = 0;
555 struct pcap_stat pstats;
556
557 if (pcap_stats(in->handle, &pstats) != 0) {
558 ERROR("%s failed retrieving pcap stats: %s", in->name, pcap_geterr(in->handle));
559 return -1;
560 }
561
562 if (pstats.ps_drop - in->pstats.ps_drop > 0) {
563 ERROR("%s dropped %i packets: Buffer exhaustion", in->name, pstats.ps_drop - in->pstats.ps_drop);
564 ret = -2;
565 }
566
567 if (pstats.ps_ifdrop - in->pstats.ps_ifdrop > 0) {
568 ERROR("%s dropped %i packets: Interface", in->name, pstats.ps_ifdrop - in->pstats.ps_ifdrop);
569 ret = -3;
570 }
571
572 in->pstats = pstats;
573
574 return ret;
575}
576
577/** Update smoothed average
578 *
579 */
581{
582 /*
583 * If we didn't link any packets during this interval, we don't have a value to return.
584 * returning 0 is misleading as it would be like saying the latency had dropped to 0.
585 * We instead set NaN which libcollectd converts to a 'U' or unknown value.
586 *
587 * This will cause gaps in graphs, but is completely legitimate as we are missing data.
588 * This is unfortunately an effect of being just a passive observer.
589 */
590 if (stats->interval.linked_total == 0) {
591 double unk = strtod("NAN()", (char **) NULL);
592
593 stats->interval.latency_average = unk;
594 stats->interval.latency_high = unk;
595 stats->interval.latency_low = unk;
596
597 /*
598 * We've not yet been able to determine latency, so latency_smoothed is also NaN
599 */
600 if (stats->latency_smoothed_count == 0) {
601 stats->latency_smoothed = unk;
602 }
603 return;
604 }
605
606 if (stats->interval.linked_total && stats->interval.latency_total) {
607 stats->interval.latency_average = (stats->interval.latency_total / stats->interval.linked_total);
608 }
609
610 if (isnan((long double)stats->latency_smoothed)) {
611 stats->latency_smoothed = 0;
612 }
613 if (stats->interval.latency_average > 0) {
614 stats->latency_smoothed_count++;
615 stats->latency_smoothed += ((stats->interval.latency_average - stats->latency_smoothed) /
616 ((stats->latency_smoothed_count < 100) ? stats->latency_smoothed_count : 100));
617 }
618}
619
621{
622 int i;
623
624 stats->interval.received = ((long double) stats->interval.received_total) / conf->stats.interval;
625 stats->interval.linked = ((long double) stats->interval.linked_total) / conf->stats.interval;
626 stats->interval.unlinked = ((long double) stats->interval.unlinked_total) / conf->stats.interval;
627 stats->interval.reused = ((long double) stats->interval.reused_total) / conf->stats.interval;
628 stats->interval.lost = ((long double) stats->interval.lost_total) / conf->stats.interval;
629
630 for (i = 1; i < RS_RETRANSMIT_MAX; i++) {
631 stats->interval.rt[i] = ((long double) stats->interval.rt_total[i]) / conf->stats.interval;
632 }
633}
634
636{
637 int i;
638 bool have_rt = false;
639
640 for (i = 1; i <= RS_RETRANSMIT_MAX; i++) if (stats->interval.rt[i]) have_rt = true;
641
642 if (!stats->interval.received && !have_rt && !stats->interval.reused) return;
643
644 if (stats->interval.received || stats->interval.linked) {
645 INFO("%s counters:", fr_radius_packet_name[code]);
646 if (stats->interval.received > 0) {
647 INFO("\tTotal : %.3lf/s" , stats->interval.received);
648 }
649 }
650
651 if (stats->interval.linked > 0) {
652 INFO("\tLinked : %.3lf/s", stats->interval.linked);
653 INFO("\tUnlinked : %.3lf/s", stats->interval.unlinked);
654 INFO("%s latency:", fr_radius_packet_name[code]);
655 INFO("\tHigh : %.3lfms", stats->interval.latency_high);
656 INFO("\tLow : %.3lfms", stats->interval.latency_low);
657 INFO("\tAverage : %.3lfms", stats->interval.latency_average);
658 INFO("\tMA : %.3lfms", stats->latency_smoothed);
659 }
660
661 if (have_rt || stats->interval.lost || stats->interval.reused) {
662 INFO("%s retransmits & loss:", fr_radius_packet_name[code]);
663
664 if (stats->interval.lost) INFO("\tLost : %.3lf/s", stats->interval.lost);
665 if (stats->interval.reused) INFO("\tID Reused : %.3lf/s", stats->interval.reused);
666
667 for (i = 1; i <= RS_RETRANSMIT_MAX; i++) {
668 if (!stats->interval.rt[i]) continue;
669
670 if (i != RS_RETRANSMIT_MAX) {
671 INFO("\tRT (%i) : %.3lf/s", i, stats->interval.rt[i]);
672 } else {
673 INFO("\tRT (%i+) : %.3lf/s", i, stats->interval.rt[i]);
674 }
675 }
676 }
677}
678
679static void rs_stats_print_fancy(rs_update_t *this, rs_stats_t *stats, struct timeval *now)
680{
681 fr_pcap_t *in_p;
682 size_t i;
683 size_t rs_codes_len = (NUM_ELEMENTS(rs_useful_codes));
684
685 /*
686 * Clear and reset the screen
687 */
688 INFO("\x1b[0;0f");
689 INFO("\x1b[2J");
690
691 if ((stats->quiet.tv_sec + (stats->quiet.tv_usec / 1000000.0)) -
692 (now->tv_sec + (now->tv_usec / 1000000.0)) > 0) {
693 INFO("Stats muted because of warmup, or previous error");
694 return;
695 }
696
697 INFO("######### Stats Iteration %i #########", stats->intervals);
698
699 if (this->in) INFO("Interface capture rate:");
700 for (in_p = this->in;
701 in_p;
702 in_p = in_p->next) {
703 struct pcap_stat pstats;
704
705 if (pcap_stats(in_p->handle, &pstats) != 0) {
706 ERROR("%s failed retrieving pcap stats: %s", in_p->name, pcap_geterr(in_p->handle));
707 return;
708 }
709
710 INFO("\t%s%*s: %.3lf/s", in_p->name, (int) (10 - strlen(in_p->name)), "",
711 ((double) (pstats.ps_recv - in_p->pstats.ps_recv)) / conf->stats.interval);
712 }
713
714 /*
715 * Latency stats need a bit more work to calculate the SMA.
716 *
717 * No further work is required for codes.
718 */
719 for (i = 0; i < rs_codes_len; i++) {
720 if (fr_debug_lvl > 0) {
722 }
723 }
724}
725
727{
728 fr_pcap_t *in_p;
729 size_t rs_codes_len = (NUM_ELEMENTS(rs_useful_codes));
730 size_t i;
731 int j;
732
733 fprintf(stdout, "\"Iteration\"");
734
735 for (in_p = this->in; in_p; in_p = in_p->next) {
736 fprintf(stdout, ",\"%s PPS\"", in_p->name);
737 }
738
739 for (i = 0; i < rs_codes_len; i++) {
741
742 fprintf(stdout,
743 ",\"%s received/s\""
744 ",\"%s linked/s\""
745 ",\"%s unlinked/s\""
746 ",\"%s lat high (ms)\""
747 ",\"%s lat low (ms)\""
748 ",\"%s lat avg (ms)\""
749 ",\"%s lat ma (ms)\""
750 ",\"%s lost/s\""
751 ",\"%s reused/s\"",
752 name,
753 name,
754 name,
755 name,
756 name,
757 name,
758 name,
759 name,
760 name);
761
762 for (j = 1; j <= RS_RETRANSMIT_MAX; j++) {
763 if (j != RS_RETRANSMIT_MAX) {
764 fprintf(stdout, ",\"%s rtx (%i)\"", name, j);
765 } else {
766 fprintf(stdout, ",\"%s rtx (%i+)\"", name, j);
767 }
768 }
769 }
770
771 fprintf(stdout , "\n");
772}
773
774static ssize_t rs_stats_print_code_csv(char *out, size_t outlen, rs_latency_t *stats)
775{
776 size_t i;
777 char *p = out, *end = out + outlen;
778
779 p += snprintf(out, outlen, ",%.3lf,%.3lf,%.3lf,%.3lf,%.3lf,%.3lf,%.3lf,%.3lf,%.3lf",
780 stats->interval.received,
781 stats->interval.linked,
782 stats->interval.unlinked,
783 stats->interval.latency_high,
784 stats->interval.latency_low,
785 stats->interval.latency_average,
786 stats->latency_smoothed,
787 stats->interval.lost,
788 stats->interval.reused);
789 if (p >= end) return -1;
790
791 for (i = 1; i <= RS_RETRANSMIT_MAX; i++) {
792 p += snprintf(p, outlen - (p - out), ",%.3lf", stats->interval.rt[i]);
793 if (p >= end) return -1;
794 }
795
796 return p - out;
797}
798
799static void rs_stats_print_csv(rs_update_t *this, rs_stats_t *stats, UNUSED struct timeval *now)
800{
801 char buffer[2048], *p = buffer, *end = buffer + sizeof(buffer);
802 fr_pcap_t *in_p;
803 size_t i;
804 size_t rs_codes_len = (NUM_ELEMENTS(rs_useful_codes));
805
806 p += snprintf(buffer, sizeof(buffer) - (p - buffer), "%i", stats->intervals);
807 if (p >= end) {
808 oob:
809 ERROR("Exceeded line buffer size");
810 return;
811 }
812
813 for (in_p = this->in;
814 in_p;
815 in_p = in_p->next) {
816 struct pcap_stat pstats;
817
818 if (pcap_stats(in_p->handle, &pstats) != 0) {
819 ERROR("%s failed retrieving pcap stats: %s", in_p->name, pcap_geterr(in_p->handle));
820 return;
821 }
822
823 p += snprintf(p, sizeof(buffer) - (p - buffer), ",%.3lf",
824 ((double) (pstats.ps_recv - in_p->pstats.ps_recv)) / conf->stats.interval);
825 if (p >= end) goto oob;
826 }
827
828 for (i = 0; i < rs_codes_len; i++) {
829 ssize_t slen;
830
831 slen = rs_stats_print_code_csv(p, sizeof(buffer) - (p - buffer), &stats->exchange[rs_useful_codes[i]]);
832 if (slen < 0) goto oob;
833
834 p += (size_t)slen;
835 if (p >= end) goto oob;
836 }
837
838 fprintf(stdout , "%s\n", buffer);
839}
840
841/** Process stats for a single interval
842 *
843 */
844static void rs_stats_process(fr_event_list_t *el, fr_time_t now_t, void *ctx)
845{
846 size_t i;
847 size_t rs_codes_len = (NUM_ELEMENTS(rs_useful_codes));
848 fr_pcap_t *in_p;
849 rs_update_t *this = ctx;
850 rs_stats_t *stats = this->stats;
851 struct timeval now;
852
853 now = fr_time_to_timeval(now_t);
854
855 if (!this->done_header) {
856 if (this->head) this->head(this);
857 this->done_header = true;
858 }
859
860 stats->intervals++;
861
862 for (in_p = this->in;
863 in_p;
864 in_p = in_p->next) {
865 if (rs_check_pcap_drop(in_p) < 0) {
866 ERROR("Muting stats for the next %i milliseconds", conf->stats.timeout);
867
868 rs_tv_add_ms(&now, conf->stats.timeout, &stats->quiet);
869 goto clear;
870 }
871 }
872
873 /*
874 * Stats temporarily muted
875 */
876 if ((stats->quiet.tv_sec + (stats->quiet.tv_usec / 1000000.0)) -
877 (now.tv_sec + (now.tv_usec / 1000000.0)) > 0) goto clear;
878
879 for (i = 0; i < rs_codes_len; i++) {
882 }
883
884 if (this->body) this->body(this, stats, &now);
885
886#ifdef HAVE_COLLECTDC_H
887 /*
888 * Update stats in collectd using the complex structures we
889 * initialised earlier.
890 */
891 if ((conf->stats.out == RS_STATS_OUT_COLLECTD) && conf->stats.handle) {
892 rs_stats_collectd_do_stats(conf, conf->stats.tmpl, &now);
893 }
894#endif
895
896clear:
897 /*
898 * Rinse and repeat...
899 */
900 for (i = 0; i < rs_codes_len; i++) {
901 memset(&stats->exchange[rs_useful_codes[i]].interval, 0,
902 sizeof(stats->exchange[rs_useful_codes[i]].interval));
903 }
904
905 {
906 static fr_event_timer_t const *event;
907
908 now.tv_sec += conf->stats.interval;
909 now.tv_usec = 0;
910
911 if (fr_event_timer_at(NULL, el, &event,
912 fr_time_from_timeval(&now), rs_stats_process, ctx) < 0) {
913 ERROR("Failed inserting stats interval event");
914 }
915 }
916}
917
918
919/** Update latency statistics for request/response and forwarded packets
920 *
921 */
922static void rs_stats_update_latency(rs_latency_t *stats, struct timeval *latency)
923{
924 double lint;
925
926 stats->interval.linked_total++;
927 /* More useful is this in milliseconds */
928 lint = (latency->tv_sec + (latency->tv_usec / 1000000.0)) * 1000;
929 if (lint > stats->interval.latency_high) {
930 stats->interval.latency_high = lint;
931 }
932 if (!stats->interval.latency_low || (lint < stats->interval.latency_low)) {
933 stats->interval.latency_low = lint;
934 }
935 stats->interval.latency_total += (long double) lint;
936
937}
938
940 fr_pcap_t *in, struct timeval *now, bool live)
941{
942 static fr_event_timer_t const *event;
943 static rs_update_t update;
944
945 memset(&update, 0, sizeof(update));
946
947 update.list = el;
948 update.stats = stats;
949 update.in = in;
950
951 switch (conf->stats.out) {
952 default:
954 update.head = NULL;
955 update.body = rs_stats_print_fancy;
956 break;
957
960 update.body = rs_stats_print_csv;
961 break;
962
963#ifdef HAVE_COLLECTDC_H
964 case RS_STATS_OUT_COLLECTD:
965 update.head = NULL;
966 update.body = NULL;
967 break;
968#endif
969 }
970 /*
971 * Set the first time we print stats
972 */
973 now->tv_sec += conf->stats.interval;
974 now->tv_usec = 0;
975
976 if (live) {
977 INFO("Muting stats for the next %i milliseconds (warmup)", conf->stats.timeout);
978 rs_tv_add_ms(now, conf->stats.timeout, &(stats->quiet));
979 }
980
981 if (fr_event_timer_at(NULL, events, (void *) &event,
982 fr_time_from_timeval(now), rs_stats_process, &update) < 0) {
983 ERROR("Failed inserting stats event");
984 return -1;
985 }
986
987 return 0;
988}
989
990/** Copy a subset of attributes from one list into the other
991 *
992 * Should be O(n) if all the attributes exist. List must be pre-sorted.
993 */
994static int rs_get_pairs(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_pair_list_t *vps, fr_dict_attr_t const *da[], int num)
995{
996 fr_dcursor_t list_cursor;
997 fr_pair_t *match, *copy;
998 fr_pair_t *last_match = NULL;
999 uint64_t count = 0;
1000 int i;
1001
1002 last_match = fr_pair_list_head(vps);
1003
1004 fr_pair_dcursor_init(&list_cursor, vps);
1005 for (i = 0; i < num; i++) {
1006 match = fr_dcursor_filter_next(&list_cursor, fr_pair_matches_da, da[i]);
1007 if (!match) {
1008 fr_dcursor_set_current(&list_cursor, last_match);
1009 continue;
1010 }
1011
1012 do {
1013 copy = fr_pair_copy(ctx, match);
1014 if (!copy) {
1016 return -1;
1017 }
1018 fr_pair_append(out, copy);
1019 last_match = match;
1020
1021 count++;
1022 } while ((match = fr_dcursor_filter_next(&list_cursor, fr_pair_matches_da, da[i])));
1023 }
1024
1025 return count;
1026}
1027
1028static int _request_free(rs_request_t *request)
1029{
1030 int ret;
1031
1032 /*
1033 * If we're attempting to cleanup the request, and it's no longer in the request_tree
1034 * something has gone very badly wrong.
1035 */
1036 if (request->in_request_tree) {
1037 ret = fr_rb_delete(request_tree, request);
1038 RS_ASSERT(ret);
1039 }
1040
1041 if (request->in_link_tree) {
1042 ret = fr_rb_delete(link_tree, request);
1043 RS_ASSERT(ret);
1044 }
1045
1046 if (request->event) {
1047 ret = fr_event_timer_delete(&request->event);
1048 if (ret < 0) {
1049 fr_perror("Failed deleting timer");
1050 RS_ASSERT(0 == 1);
1051 }
1052 }
1053
1054 fr_packet_free(&request->packet);
1055 fr_packet_free(&request->expect);
1056 fr_packet_free(&request->linked);
1057
1058 return 0;
1059}
1060
1061static void rs_packet_cleanup(rs_request_t *request)
1062{
1063
1064 uint64_t count = request->id;
1065
1066 RS_ASSERT(request->stats_req);
1067 RS_ASSERT(!request->rt_rsp || request->stats_rsp);
1068 RS_ASSERT(request->packet);
1069
1070 /*
1071 * Don't pollute stats or print spurious messages as radsniff closes.
1072 */
1073 if (cleanup) {
1074 talloc_free(request);
1075 return;
1076 }
1077
1078 if (RIDEBUG_ENABLED()) {
1079 rs_time_print(timestr, sizeof(timestr), &request->when);
1080 }
1081
1082 /*
1083 * We're at packet cleanup time which is when the packet was received + timeout
1084 * and it's not been linked with a forwarded packet or a response.
1085 *
1086 * We now count it as lost.
1087 */
1088 if (!request->silent_cleanup) {
1089 if (!request->linked) {
1090 if (!request->stats_req) return;
1091
1092 request->stats_req->interval.lost_total++;
1093
1094 if (conf->event_flags & RS_LOST) {
1095 /* @fixme We should use flags in the request to indicate whether it's been dumped
1096 * to a PCAP file or logged yet, this simplifies the body logging logic */
1097 rs_packet_print(request, request->id, RS_LOST, request->in,
1098 request->packet, &request->packet_vps,
1099 NULL, NULL, false,
1101 !(conf->event_flags & RS_NORMAL));
1102 }
1103 }
1104
1105 if ((request->in->type == PCAP_INTERFACE_IN) && request->logged) {
1106 RDEBUG("Cleaning up request packet ID %i", request->expect->id);
1107 }
1108 }
1109
1110 /*
1111 * Now the request is done, we can update the retransmission stats
1112 */
1113 if (request->rt_req) {
1114 if (request->rt_req > RS_RETRANSMIT_MAX) {
1115 request->stats_req->interval.rt_total[RS_RETRANSMIT_MAX]++;
1116 } else {
1117 request->stats_req->interval.rt_total[request->rt_req]++;
1118 }
1119 }
1120
1121 if (request->rt_rsp) {
1122 if (request->rt_rsp > RS_RETRANSMIT_MAX) {
1123 request->stats_rsp->interval.rt_total[RS_RETRANSMIT_MAX]++;
1124 } else {
1125 request->stats_rsp->interval.rt_total[request->rt_rsp]++;
1126 }
1127 }
1128
1129 talloc_free(request);
1130}
1131
1132static void _rs_event(UNUSED fr_event_list_t *el, UNUSED fr_time_t now, void *ctx)
1133{
1134 rs_request_t *request = talloc_get_type_abort(ctx, rs_request_t);
1135
1136 request->event = NULL;
1137 rs_packet_cleanup(request);
1138}
1139
1140/** Wrapper around fr_packet_cmp to strip off the outer request struct
1141 *
1142 */
1143static int8_t rs_packet_cmp(void const *one, void const *two)
1144{
1145 rs_request_t const *a = one;
1146 rs_request_t const *b = two;
1147
1148 return fr_packet_cmp(a->expect, b->expect);
1149}
1150
1151static inline int rs_response_to_pcap(rs_event_t *event, rs_request_t *request, struct pcap_pkthdr const *header,
1152 uint8_t const *data)
1153{
1154 if (!event->out) return 0;
1155
1156 /*
1157 * If we're filtering by response then the requests then the capture buffer
1158 * associated with the request should contain buffered request packets.
1159 */
1160 if (conf->filter_response && request) {
1161 rs_capture_t *start;
1162
1163 /*
1164 * Record the current position in the header
1165 */
1166 start = request->capture_p;
1167
1168 /*
1169 * Buffer hasn't looped set capture_p to the start of the buffer
1170 */
1171 if (!start->header) request->capture_p = request->capture;
1172
1173 /*
1174 * If where capture_p points to, has a header set, write out the
1175 * packet to the PCAP file, looping over the buffer until we
1176 * hit our start point.
1177 */
1178 if (request->capture_p->header) do {
1179 pcap_dump((void *)event->out->dumper, request->capture_p->header,
1180 request->capture_p->data);
1181 TALLOC_FREE(request->capture_p->header);
1182 TALLOC_FREE(request->capture_p->data);
1183
1184 /* Reset the pointer to the start of the circular buffer */
1185 if (request->capture_p++ >=
1186 (request->capture +
1187 NUM_ELEMENTS(request->capture))) {
1188 request->capture_p = request->capture;
1189 }
1190 } while (request->capture_p != start);
1191 }
1192
1193 /*
1194 * Now log the response
1195 */
1196 pcap_dump((void *)event->out->dumper, header, data);
1197
1198 return 0;
1199}
1200
1201static inline int rs_request_to_pcap(rs_event_t *event, rs_request_t *request, struct pcap_pkthdr const *header,
1202 uint8_t const *data)
1203{
1204 if (!event->out) return 0;
1205
1206 /*
1207 * If we're filtering by response, then we need to wait to write out the requests
1208 */
1209 if (conf->filter_response) {
1210 /* Free the old capture */
1211 if (request->capture_p->header) {
1212 talloc_free(request->capture_p->header);
1213 TALLOC_FREE(request->capture_p->data);
1214 }
1215
1216 if (!(request->capture_p->header = talloc(request, struct pcap_pkthdr))) return -1;
1217 if (!(request->capture_p->data = talloc_array(request, uint8_t, header->caplen))) {
1218 TALLOC_FREE(request->capture_p->header);
1219 return -1;
1220 }
1221 memcpy(request->capture_p->header, header, sizeof(struct pcap_pkthdr));
1222 memcpy(request->capture_p->data, data, header->caplen);
1223
1224 /* Reset the pointer to the start of the circular buffer */
1225 if (++request->capture_p >=
1226 (request->capture +
1227 NUM_ELEMENTS(request->capture))) {
1228 request->capture_p = request->capture;
1229 }
1230 return 0;
1231 }
1232
1233 pcap_dump((void *)event->out->dumper, header, data);
1234
1235 return 0;
1236}
1237
1238/* This is the same as immediately scheduling the cleanup event */
1239#define RS_CLEANUP_NOW(_x, _s)\
1240 {\
1241 _x->silent_cleanup = _s;\
1242 _x->when = header->ts;\
1243 rs_packet_cleanup(_x);\
1244 _x = NULL;\
1245 } while (0)
1246
1247static rs_request_t *rs_request_alloc(TALLOC_CTX *ctx)
1248{
1249 rs_request_t *original;
1250
1251 original = talloc_zero(ctx, rs_request_t);
1252 talloc_set_destructor(original, _request_free);
1253
1254 fr_pair_list_init(&original->packet_vps);
1255 fr_pair_list_init(&original->expect_vps);
1256 fr_pair_list_init(&original->link_vps);
1257
1258 return original;
1259}
1260
1262
1263static void rs_packet_process(uint64_t count, rs_event_t *event, struct pcap_pkthdr const *header, uint8_t const *data)
1264{
1265 rs_stats_t *stats = event->stats;
1266 struct timeval elapsed = {0, 0};
1267 struct timeval latency;
1268
1269 /*
1270 * Pointers into the packet data we just received
1271 */
1272 ssize_t len;
1273 uint8_t const *p = data;
1274
1275 ip_header_t const *ip = NULL; /* The IP header */
1276 ip_header6_t const *ip6 = NULL; /* The IPv6 header */
1277 udp_header_t const *udp; /* The UDP header */
1278 uint8_t version; /* IP header version */
1279 bool response; /* Was it a response code */
1280
1281 fr_radius_decode_fail_t reason; /* Why we failed decoding the packet */
1282 static uint64_t captured = 0;
1283
1284 rs_status_t status = RS_NORMAL; /* Any special conditions (RTX, Unlinked, ID-Reused) */
1285 fr_packet_t *packet; /* Current packet were processing */
1286 rs_request_t *original = NULL;
1287 fr_pair_list_t decoded;
1288
1289 rs_request_t search;
1290
1291 fr_pair_list_init(&decoded);
1292
1293 memset(&search, 0, sizeof(search));
1296 fr_pair_list_init(&search.link_vps);
1297
1298 if (!start_pcap.tv_sec) {
1299 start_pcap = header->ts;
1300 }
1301
1302 if (RIDEBUG_ENABLED()) {
1303 rs_time_print(timestr, sizeof(timestr), &header->ts);
1304 }
1305
1306 len = fr_pcap_link_layer_offset(data, header->caplen, event->in->link_layer);
1307 if (len < 0) {
1308 REDEBUG("Failed determining link layer header offset");
1309 return;
1310 }
1311 p += len;
1312
1313 version = (p[0] & 0xf0) >> 4;
1314 switch (version) {
1315 case 4:
1316 ip = (ip_header_t const *)p;
1317 len = (0x0f & ip->ip_vhl) * 4; /* ip_hl specifies length in 32bit words */
1318 p += len;
1319 break;
1320
1321 case 6:
1322 ip6 = (ip_header6_t const *)p;
1323 p += sizeof(ip_header6_t);
1324
1325 break;
1326
1327 default:
1328 REDEBUG("IP version invalid %i", version);
1329 return;
1330 }
1331
1332 /*
1333 * End of variable length bits, do basic check now to see if packet looks long enough
1334 */
1335 len = (p - data) + sizeof(udp_header_t) + sizeof(radius_packet_t); /* length value */
1336 if ((size_t) len > header->caplen) {
1337 REDEBUG("Packet too small, we require at least %zu bytes, captured %i bytes",
1338 (size_t) len, header->caplen);
1339 return;
1340 }
1341
1342 /*
1343 * UDP header validation.
1344 */
1345 udp = (udp_header_t const *)p;
1346 {
1347 uint16_t udp_len;
1348 ssize_t actual_len;
1349
1350 udp_len = ntohs(udp->len);
1351 actual_len = header->caplen - (p - data);
1352 /* Truncated data */
1353 if (udp_len > actual_len) {
1354 REDEBUG("Packet too small by %zi bytes, UDP header + Payload should be %hu bytes",
1355 udp_len - actual_len, udp_len);
1356 return;
1357 }
1358
1359#if 0
1360 /*
1361 * It seems many probes add trailing garbage to the end
1362 * of each capture frame. This has been observed with
1363 * F5 load balancers and Netscout.
1364 *
1365 * Leaving the code here in case it's ever needed for
1366 * debugging.
1367 */
1368 else if (udp_len < actual_len) {
1369 REDEBUG("Packet too big by %zi bytes, UDP header + Payload should be %hu bytes",
1370 actual_len - udp_len, udp_len);
1371 return;
1372 }
1373#endif
1374 if ((version == 4) && conf->verify_udp_checksum) {
1375 uint16_t expected;
1376
1377 expected = fr_udp_checksum((uint8_t const *) udp, udp_len, udp->checksum,
1378 ip->ip_src, ip->ip_dst);
1379 if (udp->checksum != expected) {
1380 REDEBUG("UDP checksum invalid, packet: 0x%04hx calculated: 0x%04hx",
1381 ntohs(udp->checksum), ntohs(expected));
1382 /* Not a fatal error */
1383 }
1384 }
1385 }
1386 p += sizeof(udp_header_t);
1387
1388 /*
1389 * With artificial talloc memory limits there's a good chance we can
1390 * recover once some requests timeout, so make an effort to deal
1391 * with allocation failures gracefully.
1392 */
1393 packet = fr_packet_alloc(conf, false);
1394 if (!packet) {
1395 REDEBUG("Failed allocating memory to hold decoded packet");
1396 rs_tv_add_ms(&header->ts, conf->stats.timeout, &stats->quiet);
1397 return;
1398 }
1399
1400 packet->timestamp = fr_time_from_timeval(&header->ts);
1401 packet->data_len = header->caplen - (p - data);
1402 memcpy(&packet->data, &p, sizeof(packet->data));
1403
1404 packet->socket.type = SOCK_DGRAM;
1405
1406 /*
1407 * Populate IP/UDP fields from PCAP data
1408 */
1409 if (ip) {
1410 packet->socket.inet.src_ipaddr.af = AF_INET;
1411 packet->socket.inet.src_ipaddr.addr.v4.s_addr = ip->ip_src.s_addr;
1412
1413 packet->socket.inet.dst_ipaddr.af = AF_INET;
1414 packet->socket.inet.dst_ipaddr.addr.v4.s_addr = ip->ip_dst.s_addr;
1415 } else {
1416 packet->socket.inet.src_ipaddr.af = AF_INET6;
1417 memcpy(packet->socket.inet.src_ipaddr.addr.v6.s6_addr, ip6->ip_src.s6_addr,
1418 sizeof(packet->socket.inet.src_ipaddr.addr.v6.s6_addr));
1419
1420 packet->socket.inet.dst_ipaddr.af = AF_INET6;
1421 memcpy(packet->socket.inet.dst_ipaddr.addr.v6.s6_addr, ip6->ip_dst.s6_addr,
1422 sizeof(packet->socket.inet.dst_ipaddr.addr.v6.s6_addr));
1423 }
1424
1425 packet->socket.inet.src_port = ntohs(udp->src);
1426 packet->socket.inet.dst_port = ntohs(udp->dst);
1427
1428 if (!fr_packet_ok(packet, RADIUS_MAX_ATTRIBUTES, false, &reason)) {
1429 fr_perror("radsniff");
1430 if (conf->event_flags & RS_ERROR) {
1431 rs_packet_print(NULL, count, RS_ERROR, event->in,
1432 packet, &decoded, &elapsed, NULL, false, false);
1433 }
1434 fr_packet_free(&packet);
1435
1436 return;
1437 }
1438
1439 switch (packet->code) {
1448 {
1449 /* look for a matching request and use it for decoding */
1450 search.expect = packet;
1451 original = fr_rb_find(request_tree, &search);
1452
1453 /*
1454 * Verify this code is allowed
1455 */
1456 if (conf->filter_response_code && (conf->filter_response_code != packet->code)) {
1457 drop_response:
1458 RDEBUG2("Response dropped by filter");
1459 fr_packet_free(&packet);
1460
1461 /* We now need to cleanup the original request too */
1462 if (original) {
1463 RS_CLEANUP_NOW(original, true);
1464 }
1465 return;
1466 }
1467
1468 if (conf->verify_radius_authenticator && original) {
1469 int ret;
1470 FILE *log_fp = fr_log_fp;
1471
1472 fr_log_fp = NULL;
1473 ret = fr_packet_verify(packet, original->expect, conf->radius_secret);
1474 fr_log_fp = log_fp;
1475 if (ret != 0) {
1476 fr_perror("Failed verifying packet ID %d", packet->id);
1477 fr_packet_free(&packet);
1478 return;
1479 }
1480 }
1481
1482 /*
1483 * Only decode attributes if we want to print them or filter on them
1484 * fr_packet_ok( does checks to verify the packet is actually valid.
1485 */
1486 if (conf->decode_attrs) {
1487 int ret;
1488
1489#ifndef NDEBUG
1491#endif
1492
1493 ret = fr_radius_decode_simple(packet, &decoded,
1494 packet->data, packet->data_len,
1495 (original && original->expect && original->expect->data) ?
1496 original->expect->data + 4 : zeros,
1498 if (ret < 0) {
1499 fr_packet_free(&packet); /* Also frees vps */
1500 REDEBUG("Failed decoding");
1501 return;
1502 }
1503 }
1504
1505 /*
1506 * Check if we've managed to link it to a request
1507 */
1508 if (original) {
1509 /*
1510 * Now verify the packet passes the attribute filter
1511 */
1514 if (!fr_pair_validate_relaxed(NULL, &conf->filter_response_vps, &decoded)) {
1515 goto drop_response;
1516 }
1517 }
1518
1519 /*
1520 * Is this a retransmission?
1521 */
1522 if (original->linked) {
1523 status = RS_RTX;
1524 original->rt_rsp++;
1525
1526 /*
1527 * Explicitly free VPs first so list maintains integrity - it is reused below
1528 */
1529 fr_pair_list_free(&original->link_vps);
1530 fr_packet_free(&original->linked);
1531 fr_event_timer_delete(&original->event);
1532 /*
1533 * ...nope it's the first response to a request.
1534 */
1535 } else {
1536 original->stats_rsp = &stats->exchange[packet->code];
1537 }
1538
1539 /*
1540 * Insert a callback to remove the request and response
1541 * from the tree after the timeout period.
1542 * The delay is so we can detect retransmissions.
1543 */
1544 original->linked = talloc_steal(original, packet);
1545 fr_pair_list_append(&original->link_vps, &decoded); /* Move the vps over */
1546 rs_tv_add_ms(&header->ts, conf->stats.timeout, &original->when);
1547 if (fr_event_timer_at(NULL, event->list, &original->event,
1548 fr_time_from_timeval(&original->when), _rs_event, original) < 0) {
1549 REDEBUG("Failed inserting new event");
1550 /*
1551 * Delete the original request/event, it's no longer valid
1552 * for statistics.
1553 */
1554 talloc_free(original);
1555 return;
1556 }
1557 /*
1558 * No request seen, or request was dropped by attribute filter
1559 */
1560 } else {
1561 /*
1562 * If conf->filter_request_vps are set assume the original request was dropped,
1563 * the alternative is maintaining another 'filter', but that adds
1564 * complexity, reduces max capture rate, and is generally a PITA.
1565 */
1566 if (conf->filter_request) {
1567 fr_packet_free(&packet);
1568 RDEBUG2("Original request dropped by filter");
1569 return;
1570 }
1571
1572 status = RS_UNLINKED;
1573 stats->exchange[packet->code].interval.unlinked_total++;
1574 }
1575
1576 rs_response_to_pcap(event, original, header, data);
1577 response = true;
1578 break;
1579 }
1580
1586 {
1587 /*
1588 * Verify this code is allowed
1589 */
1590 if (conf->filter_request_code && (conf->filter_request_code != packet->code)) {
1591 drop_request:
1592
1593 RDEBUG2("Request dropped by filter");
1594 fr_packet_free(&packet);
1595
1596 return;
1597 }
1598
1600 switch (packet->code) {
1601 case FR_RADIUS_CODE_ACCESS_REQUEST: /* Even though this is just random bytes, we still might need to check Message-Authenticator */
1605 {
1606 int ret;
1607 FILE *log_fp = fr_log_fp;
1608
1609 fr_log_fp = NULL;
1610 ret = fr_packet_verify(packet, NULL, conf->radius_secret);
1611 fr_log_fp = log_fp;
1612 if (ret != 0) {
1613 fr_perror("Failed verifying packet ID %d", packet->id);
1614 fr_packet_free(&packet);
1615 return;
1616 }
1617 }
1618 break;
1619
1620 default:
1621 break;
1622 }
1623 }
1624
1625 /*
1626 * Only decode attributes if we want to print them or filter on them
1627 * fr_packet_ok( does checks to verify the packet is actually valid.
1628 */
1629 if (conf->decode_attrs) {
1630 int ret;
1631 FILE *log_fp = fr_log_fp;
1632
1633 fr_log_fp = NULL;
1634 ret = fr_radius_decode_simple(packet, &decoded,
1635 packet->data, packet->data_len, NULL,
1637 fr_log_fp = log_fp;
1638
1639 if (ret < 0) {
1640 fr_packet_free(&packet); /* Also frees vps */
1641
1642 REDEBUG("Failed decoding");
1643 return;
1644 }
1645
1647 }
1648
1649 /*
1650 * Save the request for later matching
1651 */
1652 search.expect = fr_packet_alloc_reply(packet, packet);
1653 if (!search.expect) {
1654 REDEBUG("Failed allocating memory to hold expected reply");
1655 rs_tv_add_ms(&header->ts, conf->stats.timeout, &stats->quiet);
1656 fr_packet_free(&packet);
1657
1658 return;
1659 }
1660 search.expect->code = packet->code;
1661 memcpy(search.expect->vector, packet->vector, sizeof(search.expect->vector));
1662
1663 if ((conf->link_da_num > 0) && (!fr_pair_list_empty(&decoded))) {
1664 int ret;
1665 ret = rs_get_pairs(packet, &search.link_vps, &decoded, conf->link_da,
1666 conf->link_da_num);
1667 if (ret < 0) {
1668 ERROR("Failed extracting RTX linking pairs from request");
1669 fr_packet_free(&packet);
1670 return;
1671 }
1672 }
1673
1674 /*
1675 * If we have linking attributes set, attempt to find a request in the linking tree.
1676 */
1677 if (!fr_pair_list_empty(&search.link_vps)) {
1678 rs_request_t *tuple;
1679
1680 original = fr_rb_find(link_tree, &search);
1681 tuple = fr_rb_find(request_tree, &search);
1682
1683 /*
1684 * If the packet we matched using attributes is not the same
1685 * as the packet in the request tree, then we need to clean up
1686 * the packet in the request tree.
1687 */
1688 if (tuple && (original != tuple)) {
1689 RS_CLEANUP_NOW(tuple, true);
1690 }
1691 /*
1692 * Detect duplicates using the normal 5-tuple of src/dst ips/ports id
1693 */
1694 } else {
1695 original = fr_rb_find(request_tree, &search);
1696 if (original && (memcmp(original->expect->vector, packet->vector,
1697 sizeof(original->expect->vector)) != 0)) {
1698 /*
1699 * ID reused before the request timed out (which may be an issue)...
1700 */
1701 if (!original->linked) {
1702 status = RS_REUSED;
1703 stats->exchange[packet->code].interval.reused_total++;
1704 /* Occurs regularly downstream of proxy servers (so don't complain) */
1705 RS_CLEANUP_NOW(original, true);
1706 /*
1707 * ...and before we saw a response (which may be a bigger issue).
1708 */
1709 } else {
1710 RS_CLEANUP_NOW(original, false);
1711 }
1712 /* else it's a proper RTX with the same src/dst id authenticator/nonce */
1713 }
1714 }
1715
1716 /*
1717 * Now verify the packet passes the attribute filter
1718 */
1720 if (!fr_pair_validate_relaxed(NULL, &conf->filter_request_vps, &decoded)) {
1721 goto drop_request;
1722 }
1723 }
1724
1725 /*
1726 * Is this a retransmission?
1727 */
1728 if (original) {
1729 status = RS_RTX;
1730 original->rt_req++;
1731
1732
1733 /* We may of seen the response, but it may of been lost upstream */
1734 fr_pair_list_free(&original->link_vps);
1735 fr_packet_free(&original->linked);
1736
1737 /* replace packet and vps */
1738 fr_pair_list_free(&original->packet_vps);
1739 fr_packet_free(&original->packet);
1740 original->packet = talloc_steal(original, packet);
1741 fr_pair_list_append(&original->packet_vps, &decoded);
1742
1743 /* Request may need to be reinserted as the 5 tuple of the response may of changed */
1744 if (rs_packet_cmp(original, &search) != 0) {
1745 fr_rb_delete(request_tree, original);
1746 }
1747
1748 /* replace expected packets and vps */
1749 fr_pair_list_free(&original->expect_vps);
1750 fr_packet_free(&original->expect);
1751 original->expect = talloc_steal(original, search.expect);
1752 fr_pair_list_append(&original->expect_vps, &search.expect_vps);
1753
1754 /* Disarm the timer for the cleanup event for the original request */
1755 fr_event_timer_delete(&original->event);
1756 /*
1757 * ...nope it's a new request.
1758 */
1759 } else {
1760 original = rs_request_alloc(conf);
1761 original->id = count;
1762 original->in = event->in;
1763 original->stats_req = &stats->exchange[packet->code];
1764
1765 /* Set the packet pointer to the start of the buffer*/
1766 original->capture_p = original->capture;
1767
1768 original->packet = talloc_steal(original, packet);
1769 fr_pair_list_append(&original->packet_vps, &decoded);
1770
1771 original->expect = talloc_steal(original, search.expect);
1772 fr_pair_list_append(&original->expect_vps, &search.expect_vps);
1773
1774 if (!fr_pair_list_empty(&search.link_vps)) {
1775 bool ret;
1776 fr_pair_t *vp;
1777
1778 for (vp = fr_pair_list_head(&search.link_vps);
1779 vp;
1780 vp = fr_pair_list_next(&search.link_vps, vp)) {
1781 fr_pair_steal(original, vp);
1782 }
1783 fr_pair_list_append(&original->link_vps, &search.link_vps);
1784
1785 /* We should never have conflicts */
1786 ret = fr_rb_insert(link_tree, original);
1787 RS_ASSERT(ret);
1788 original->in_link_tree = true;
1789 }
1790
1791 /*
1792 * Special case for when were filtering by response,
1793 * we never count any requests as lost, because we
1794 * don't know what the response to that request would
1795 * of been.
1796 */
1798 original->silent_cleanup = true;
1799 }
1800 }
1801
1802 if (!original->in_request_tree) {
1803 bool ret;
1804
1805 /* We should never have conflicts */
1806 ret = fr_rb_insert(request_tree, original);
1807 RS_ASSERT(ret);
1808 original->in_request_tree = true;
1809 }
1810
1811 /*
1812 * Insert a callback to remove the request from the tree
1813 */
1814 original->packet->timestamp = fr_time_from_timeval(&header->ts);
1815 rs_tv_add_ms(&header->ts, conf->stats.timeout, &original->when);
1816 if (fr_event_timer_at(NULL, event->list, &original->event,
1817 fr_time_from_timeval(&original->when), _rs_event, original) < 0) {
1818 REDEBUG("Failed inserting new event");
1819
1820 talloc_free(original);
1821 return;
1822 }
1823 rs_request_to_pcap(event, original, header, data);
1824 response = false;
1825 break;
1826 }
1827
1828 default:
1829 REDEBUG("Unsupported code %i", packet->code);
1830 fr_packet_free(&packet);
1831
1832 return;
1833 }
1834
1835 fr_timeval_subtract(&elapsed, &header->ts, &start_pcap);
1836
1837 /*
1838 * Increase received count
1839 */
1840 stats->exchange[packet->code].interval.received_total++;
1841
1842 /*
1843 * It's a linked response
1844 */
1845 if (original && original->linked) {
1846 latency = fr_time_delta_to_timeval(fr_time_sub(packet->timestamp, original->packet->timestamp));
1847
1848 /*
1849 * Update stats for both the request and response types.
1850 *
1851 * This isn't useful for things like Access-Requests, but will be useful for
1852 * CoA and Disconnect Messages, as we get the average latency across both
1853 * response types.
1854 *
1855 * It also justifies allocating FR_RADIUS_CODE_MAXinstances of rs_latency_t.
1856 */
1857 rs_stats_update_latency(&stats->exchange[packet->code], &latency);
1858 if (original->expect) rs_stats_update_latency(&stats->exchange[original->expect->code], &latency);
1859
1860 /*
1861 * We're filtering on response, now print out the full data from the request
1862 */
1864 struct timeval ts_tv;
1865
1866 ts_tv = fr_time_to_timeval(original->packet->timestamp);
1867
1868 rs_time_print(timestr, sizeof(timestr), &ts_tv);
1869 fr_timeval_subtract(&elapsed, &ts_tv, &start_pcap);
1870 rs_packet_print(original, original->id, RS_NORMAL, original->in,
1871 original->packet, &original->packet_vps, &elapsed, NULL, false, true);
1872 fr_timeval_subtract(&elapsed, &header->ts, &start_pcap);
1873 rs_time_print(timestr, sizeof(timestr), &header->ts);
1874 }
1875
1876 if (conf->event_flags & status) {
1877 rs_packet_print(original, count, status, event->in,
1878 original->linked, &original->link_vps,
1879 &elapsed, &latency, response, true);
1880 }
1881 /*
1882 * It's the original request
1883 *
1884 * If we're filtering on responses we can only indicate we received it on response, or timeout.
1885 */
1886 } else if (!conf->filter_response && (conf->event_flags & status)) {
1887 uint64_t print_id;
1889 fr_pair_list_t *print_pair_list;
1890
1891 if (original) {
1892 print_id = original->id;
1893 print_packet = original->packet;
1894 print_pair_list = &original->packet_vps;
1895 } else {
1896 print_id = count;
1897 print_packet = packet;
1898 print_pair_list = &decoded;
1899 }
1900
1901 rs_packet_print(original, print_id, status, event->in,
1902 print_packet, print_pair_list,
1903 &elapsed, NULL, response, true);
1904 }
1905
1906 fflush(fr_log_fp);
1907
1908 /*
1909 * If it's an unlinked response, we need to free it explicitly, as it will
1910 * not be done by the event queue.
1911 */
1912 if (response && !original) {
1913 fr_packet_free(&packet); /* Also frees decoded */
1914 }
1915
1916 captured++;
1917 /*
1918 * We've hit our capture limit, break out of the event loop
1919 */
1920 if ((conf->limit > 0) && (captured >= conf->limit)) {
1921 INFO("Captured %" PRIu64 " packets, exiting...", captured);
1923 }
1924}
1925
1926static void rs_got_packet(fr_event_list_t *el, int fd, UNUSED int flags, void *ctx)
1927{
1928 static uint64_t count = 0; /* Packets seen */
1929 static fr_time_t last_sync = fr_time_wrap(0);
1930 fr_time_t now_real;
1931 rs_event_t *event = talloc_get_type(ctx, rs_event_t);
1932 pcap_t *handle = event->in->handle;
1933
1934 int i;
1935 int ret;
1936 const uint8_t *data;
1937 struct pcap_pkthdr *header;
1938
1939 /*
1940 * Because the event loop might be running on synthetic
1941 * pcap file time, we need to implement our own time
1942 * tracking here, and run the monotonic/wallclock sync
1943 * event ourselves.
1944 */
1945 now_real = fr_time();
1946 if (fr_time_delta_gt(fr_time_sub(now_real, last_sync), fr_time_delta_from_sec(1))) {
1947 fr_time_sync();
1948 last_sync = now_real;
1949 }
1950
1951 /*
1952 * Consume entire capture, interleaving not currently possible
1953 */
1954 if ((event->in->type == PCAP_FILE_IN) || (event->in->type == PCAP_STDIO_IN)) {
1955 bool stats_started = false;
1956
1957 while (!fr_event_loop_exiting(el)) {
1958 fr_time_t now;
1959
1960 ret = pcap_next_ex(handle, &header, &data);
1961 if (ret == 0) {
1962 /* No more packets available at this time */
1963 return;
1964 }
1965 if (ret == -2) {
1966 DEBUG("Done reading packets (%s)", event->in->name);
1967 done_file:
1969
1970 /* Signal pipe takes one slot which is why this is == 1 */
1972
1973 return;
1974 }
1975 if (ret < 0) {
1976 ERROR("Error requesting next packet, got (%i): %s", ret, pcap_geterr(handle));
1977 goto done_file;
1978 }
1979
1980 /*
1981 * Insert the stats processor with the timestamp
1982 * of the first packet in the trace.
1983 */
1984 if (conf->stats.interval && !stats_started) {
1985 rs_install_stats_processor(event->stats, el, NULL, &header->ts, false);
1986 stats_started = true;
1987 }
1988
1989 do {
1990 now = fr_time_from_timeval(&header->ts);
1991 } while (fr_event_timer_run(el, &now) == 1);
1992 count++;
1993
1994 rs_packet_process(count, event, header, data);
1995 }
1996 return;
1997 }
1998
1999 /*
2000 * Consume multiple packets from the capture buffer.
2001 * We occasionally need to yield to allow events to run.
2002 */
2003 for (i = 0; i < RS_FORCE_YIELD; i++) {
2004 ret = pcap_next_ex(handle, &header, &data);
2005 if (ret == 0) {
2006 /* No more packets available at this time */
2007 return;
2008 }
2009 if (ret < 0) {
2010 ERROR("Error requesting next packet, got (%i): %s", ret, pcap_geterr(handle));
2011 return;
2012 }
2013
2014 count++;
2015 rs_packet_process(count, event, header, data);
2016 }
2017}
2018
2019static int _rs_event_status(UNUSED fr_time_t now, fr_time_delta_t wake_t, UNUSED void *uctx)
2020{
2021 struct timeval wake;
2022
2023 wake = fr_time_delta_to_timeval(wake_t);
2024
2025 if ((wake.tv_sec != 0) || (wake.tv_usec >= 100000)) {
2026 DEBUG2("Waking up in %d.%01u seconds", (int) wake.tv_sec, (unsigned int) wake.tv_usec / 100000);
2027
2028 if (RIDEBUG_ENABLED()) {
2029 rs_time_print(timestr, sizeof(timestr), &wake);
2030 }
2031 }
2032
2033 return 0;
2034}
2035
2036/** Compare requests using packet info and lists of attributes
2037 *
2038 */
2039static int8_t rs_rtx_cmp(void const *one, void const *two)
2040{
2041 rs_request_t const *a = one;
2042 rs_request_t const *b = two;
2043 int ret;
2044
2047
2048 CMP_RETURN(a, b, expect->code);
2049 CMP_RETURN(a, b, expect->socket.fd);
2050
2051 ret = fr_ipaddr_cmp(&a->expect->socket.inet.src_ipaddr, &b->expect->socket.inet.src_ipaddr);
2052 if (ret != 0) return ret;
2053
2054 ret = fr_ipaddr_cmp(&a->expect->socket.inet.dst_ipaddr, &b->expect->socket.inet.dst_ipaddr);
2055 if (ret != 0) return ret;
2056
2057 ret = fr_pair_list_cmp(&a->link_vps, &b->link_vps);
2058 return CMP(ret, 0);
2059}
2060
2061static int rs_build_dict_list(fr_dict_attr_t const **out, size_t len, char *list)
2062{
2063 size_t i = 0;
2064 char *p, *tok;
2065
2066 p = list;
2067 while ((tok = strsep(&p, "\t ,")) != NULL) {
2068 fr_dict_attr_t const *da;
2069 if ((*tok == '\t') || (*tok == ' ') || (*tok == '\0')) {
2070 continue;
2071 }
2072
2073 if (i == len) {
2074 ERROR("Too many attributes, maximum allowed is %zu", len);
2075 return -1;
2076 }
2077
2079 if (!da) da = fr_dict_attr_by_name(NULL, fr_dict_root(dict_freeradius), tok);
2080 if (!da) {
2081 ERROR("Error parsing attribute name \"%s\"", tok);
2082 return -1;
2083 }
2084
2085 out[i] = da;
2086 i++;
2087 }
2088
2089 /*
2090 * This allows efficient list comparisons later
2091 */
2092 if (i > 1) fr_quick_sort((void const **)out, 0, i, fr_pointer_cmp);
2093
2094 return i;
2095}
2096
2097static int rs_build_filter(fr_pair_list_t *out, char const *filter)
2098{
2099 fr_pair_parse_t root, relative;
2100
2101 root = (fr_pair_parse_t) {
2102 .ctx = conf,
2104 .list = out,
2105 .allow_compare = true,
2106 };
2107 relative = (fr_pair_parse_t) { };
2108
2109 if (fr_pair_list_afrom_substr(&root, &relative, &FR_SBUFF_IN(filter, strlen(filter))) <= 0) {
2110 fr_perror("Invalid RADIUS filter \"%s\"", filter);
2111 return -1;
2112 }
2113
2114 if (fr_pair_list_empty(out)) {
2115 ERROR("Empty RADIUS filter '%s'", filter);
2116 return -1;
2117 }
2118
2119 /*
2120 * This allows efficient list comparisons later
2121 */
2123
2124 return 0;
2125}
2126
2127static int rs_build_event_flags(int *flags, fr_table_num_sorted_t const *map, size_t map_len, char *list)
2128{
2129 size_t i = 0;
2130 char *p, *tok;
2131
2132 p = list;
2133 while ((tok = strsep(&p, "\t ,")) != NULL) {
2134 int flag;
2135
2136 if ((*tok == '\t') || (*tok == ' ') || (*tok == '\0')) {
2137 continue;
2138 }
2139
2140 *flags |= flag = fr_table_value_by_str(map, tok, -1);
2141 if (flag < 0) {
2142 ERROR("Invalid flag \"%s\"", tok);
2143 return -1;
2144 }
2145
2146 i++;
2147 }
2148
2149 return i;
2150}
2151
2152/** Callback for when the request is removed from the request tree
2153 *
2154 * @param request being removed.
2155 */
2156static void _unmark_request(void *request)
2157{
2158 rs_request_t *this = request;
2159 this->in_request_tree = false;
2160}
2161
2162/** Callback for when the request is removed from the link tree
2163 *
2164 * @param request being removed.
2165 */
2166static void _unmark_link(void *request)
2167{
2168 rs_request_t *this = request;
2169 this->in_link_tree = false;
2170}
2171
2172/** Exit the event loop after a given timeout.
2173 *
2174 */
2176{
2178}
2179
2180
2181#ifdef HAVE_COLLECTDC_H
2182/** Re-open the collectd socket
2183 *
2184 */
2185static void rs_collectd_reopen(fr_event_list_t *el, fr_time_t now, UNUSED void *ctx)
2186{
2187 static fr_event_timer_t const *event;
2188
2189 if (rs_stats_collectd_open(conf) == 0) {
2190 DEBUG2("Stats output socket (re)opened");
2191 return;
2192 }
2193
2194 ERROR("Will attempt to re-establish connection in %i ms", RS_SOCKET_REOPEN_DELAY);
2195
2196 if (fr_event_timer_at(NULL, el, &event,
2198 rs_collectd_reopen, el) < 0) {
2199 ERROR("Failed inserting re-open event");
2200 RS_ASSERT(0);
2201 }
2202}
2203#endif
2204
2205/** Write the last signal to the signal pipe
2206 *
2207 * @param sig raised
2208 */
2209static void rs_signal_self(int sig)
2210{
2211 if (write(self_pipe[1], &sig, sizeof(sig)) < 0) {
2212 ERROR("Failed writing signal %s to pipe: %s", strsignal(sig), fr_syserror(errno));
2213 fr_exit_now(EXIT_FAILURE);
2214 }
2215}
2216
2217/** Read the last signal from the signal pipe
2218 *
2219 */
2221#ifndef HAVE_COLLECTDC_H
2222UNUSED
2223#endif
2224fr_event_list_t *list, int fd, int UNUSED flags, UNUSED void *ctx)
2225{
2226 int sig;
2227 ssize_t ret;
2228
2229 ret = read(fd, &sig, sizeof(sig));
2230 if (ret < 0) {
2231 ERROR("Failed reading signal from pipe: %s", fr_syserror(errno));
2232 fr_exit_now(EXIT_FAILURE);
2233 }
2234
2235 if (ret != sizeof(sig)) {
2236 ERROR("Failed reading signal from pipe: "
2237 "Expected signal to be %zu bytes but only read %zu byes", sizeof(sig), ret);
2238 fr_exit_now(EXIT_FAILURE);
2239 }
2240
2241 switch (sig) {
2242#ifdef HAVE_COLLECTDC_H
2243 case SIGPIPE:
2244 rs_collectd_reopen(list, fr_time(), list);
2245 break;
2246#else
2247 case SIGPIPE:
2248#endif
2249
2250 case SIGINT:
2251 case SIGTERM:
2252 case SIGQUIT:
2253 DEBUG2("Signalling event loop to exit");
2255 break;
2256
2257 default:
2258 ERROR("Unhandled signal %s", strsignal(sig));
2259 fr_exit_now(EXIT_FAILURE);
2260 }
2261}
2262
2263static NEVER_RETURNS void usage(int status)
2264{
2265 FILE *output = status ? stderr : stdout;
2266 fprintf(output, "Usage: radsniff [options][stats options] -- [pcap files]\n");
2267 fprintf(output, "options:\n");
2268 fprintf(output, " -a List all interfaces available for capture.\n");
2269 fprintf(output, " -c <count> Number of packets to capture.\n");
2270 fprintf(output, " -C <checksum_type> Enable checksum validation. (Specify 'udp' or 'radius')\n");
2271 fprintf(output, " -d <raddb> Set configuration directory (defaults to " RADDBDIR ").\n");
2272 fprintf(output, " -D <dictdir> Set main dictionary directory (defaults to " DICTDIR ").\n");
2273 fprintf(output, " -e <event>[,<event>] Only log requests with these event flags.\n");
2274 fprintf(output, " Event may be one of the following:\n");
2275 fprintf(output, " - received - a request or response.\n");
2276 fprintf(output, " - norsp - seen for a request.\n");
2277 fprintf(output, " - rtx - of a request that we've seen before.\n");
2278 fprintf(output, " - noreq - could be matched with the response.\n");
2279 fprintf(output, " - reused - ID too soon.\n");
2280 fprintf(output, " - error - decoding the packet.\n");
2281 fprintf(output, " -f <filter> PCAP filter (default is 'udp port <port> or <port + 1> or %i'\n",
2283 fprintf(output, " with extra rules to allow .1Q tagged packets)\n");
2284 fprintf(output, " -h This help message.\n");
2285 fprintf(output, " -i <interface> Capture packets from interface (defaults to all if supported).\n");
2286 fprintf(output, " -I <file> Read packets from <file>\n");
2287 fprintf(output, " -l <attr>[,<attr>] Output packet sig and a list of attributes.\n");
2288 fprintf(output, " -L <attr>[,<attr>] Detect retransmissions using these attributes to link requests.\n");
2289 fprintf(output, " -m Don't put interface(s) into promiscuous mode.\n");
2290 fprintf(output, " -p <port> Filter packets by port (default is %i).\n", FR_AUTH_UDP_PORT);
2291 fprintf(output, " -P <pidfile> Daemonize and write out <pidfile>.\n");
2292 fprintf(output, " -q Print less debugging information.\n");
2293 fprintf(output, " -r <filter> RADIUS attribute request filter.\n");
2294 fprintf(output, " -R <filter> RADIUS attribute response filter.\n");
2295 fprintf(output, " -s <secret> RADIUS secret.\n");
2296 fprintf(output, " -S Write PCAP data to stdout.\n");
2297 fprintf(output, " -t <timeout> Stop after <timeout> seconds.\n");
2298 fprintf(output, " -v Show program version information and exit.\n");
2299 fprintf(output, " -w <file> Write output packets to file.\n");
2300 fprintf(output, " -x Print more debugging information.\n");
2301 fprintf(output, "stats options:\n");
2302 fprintf(output, " -W <interval> Periodically write out statistics every <interval> seconds.\n");
2303 fprintf(output, " -E Print stats in CSV format.\n");
2304 fprintf(output, " -T <timeout> How many milliseconds before the request is counted as lost "
2305 "(defaults to %i).\n", RS_DEFAULT_TIMEOUT);
2306#ifdef HAVE_COLLECTDC_H
2307 fprintf(output, " -N <prefix> The instance name passed to the collectd plugin.\n");
2308 fprintf(output, " -O <server> Write statistics to this collectd server.\n");
2309#endif
2310 fprintf(output, " -Z <output_dir> Dump the packets in <output_dir>/{requests,reply}.${count}.txt\n");
2311 fr_exit_now(status);
2312}
2313
2314/**
2315 *
2316 * @hidecallgraph
2317 */
2318int main(int argc, char *argv[])
2319{
2320 fr_pcap_t *in = NULL, *in_p;
2321 fr_pcap_t **in_head = &in;
2322 fr_pcap_t *out = NULL;
2323
2324 int ret = EXIT_SUCCESS; /* Exit status */
2325
2326 char errbuf[PCAP_ERRBUF_SIZE]; /* Error buffer */
2327 int port = FR_AUTH_UDP_PORT;
2328
2329 int c;
2330 unsigned int timeout = 0;
2331 fr_event_timer_t const *timeout_ev = NULL;
2332 char const *raddb_dir = RADDBDIR;
2333 char const *dict_dir = DICTDIR;
2334 TALLOC_CTX *autofree;
2335
2336 rs_stats_t *stats;
2337
2338 fr_debug_lvl = 1;
2339 fr_log_fp = stdout;
2340
2341 /*
2342 * Must be called first, so the handler is called last
2343 */
2345
2347
2348 /*
2349 * Useful if using radsniff as a long running stats daemon
2350 */
2351#ifndef NDEBUG
2352 if (fr_fault_setup(autofree, getenv("PANIC_ACTION"), argv[0]) < 0) {
2353 fr_perror("radsniff");
2354 fr_exit_now(EXIT_FAILURE);
2355 }
2356#endif
2357
2358 talloc_set_log_stderr();
2359
2360 conf = talloc_zero(autofree, rs_t);
2361 RS_ASSERT(conf);
2364
2365 stats = talloc_zero(conf, rs_stats_t);
2366
2367 /*
2368 * Set some defaults
2369 */
2370 conf->print_packet = true;
2371 conf->limit = 0;
2372 conf->promiscuous = true;
2373#ifdef HAVE_COLLECTDC_H
2374 conf->stats.prefix = RS_DEFAULT_PREFIX;
2375#endif
2376 conf->radius_secret = talloc_strdup(conf, RS_DEFAULT_SECRET);
2377 conf->logger = NULL;
2378
2379#ifdef HAVE_COLLECTDC_H
2380 conf->stats.prefix = RS_DEFAULT_PREFIX;
2381#endif
2382
2383 /*
2384 * Get options
2385 */
2386 while ((c = getopt(argc, argv, "ab:c:C:d:D:e:Ef:hi:I:l:L:mp:P:qr:R:s:St:vw:xXW:T:P:N:O:Z:")) != -1) {
2387 switch (c) {
2388 case 'a':
2389 {
2390 pcap_if_t *all_devices = NULL;
2391 pcap_if_t *dev_p;
2392 int i;
2393
2394 if (pcap_findalldevs(&all_devices, errbuf) < 0) {
2395 ERROR("Error getting available capture devices: %s", errbuf);
2396 goto finish;
2397 }
2398
2399 i = 1;
2400 for (dev_p = all_devices;
2401 dev_p;
2402 dev_p = dev_p->next) {
2403 INFO("%i.%s", i++, dev_p->name);
2404 }
2405 ret = 0;
2406 pcap_freealldevs(all_devices);
2407 goto finish;
2408 }
2409
2410 /* super secret option */
2411 case 'b':
2412 conf->buffer_pkts = atoi(optarg);
2413 if (conf->buffer_pkts == 0) {
2414 ERROR("Invalid buffer length \"%s\"", optarg);
2415 usage(1);
2416 }
2417 break;
2418
2419 case 'c':
2420 conf->limit = atoi(optarg);
2421 if (conf->limit == 0) {
2422 ERROR("Invalid number of packets \"%s\"", optarg);
2423 usage(1);
2424 }
2425 break;
2426
2427 /* UDP/RADIUS checksum validation */
2428 case 'C':
2429 if (strcmp(optarg, "udp") == 0) {
2430 conf->verify_udp_checksum = true;
2431
2432 } else if (strcmp(optarg, "radius") == 0) {
2434
2435 } else {
2436 ERROR("Must specify 'udp' or 'radius' for -C, not %s", optarg);
2437 usage(1);
2438 }
2439 break;
2440
2441 case 'd':
2442 raddb_dir = optarg;
2443 break;
2444
2445 case 'D':
2446 dict_dir = optarg;
2447 break;
2448
2449 case 'e':
2451 rs_events, rs_events_len, optarg) < 0) usage(64);
2452 break;
2453
2454 case 'E':
2456 break;
2457
2458 case 'f':
2459 conf->pcap_filter = optarg;
2460 break;
2461
2462 case 'h':
2463 usage(0); /* never returns */
2464
2465 case 'i':
2466 *in_head = fr_pcap_init(conf, optarg, PCAP_INTERFACE_IN);
2467 if (!*in_head) goto finish;
2468 in_head = &(*in_head)->next;
2469 conf->from_dev = true;
2470 break;
2471
2472 case 'I':
2473 *in_head = fr_pcap_init(conf, optarg, PCAP_FILE_IN);
2474 if (!*in_head) {
2475 goto finish;
2476 }
2477 in_head = &(*in_head)->next;
2478 conf->from_file = true;
2479 break;
2480
2481 case 'l':
2482 conf->list_attributes = optarg;
2483 break;
2484
2485 case 'L':
2486 conf->link_attributes = optarg;
2487 break;
2488
2489 case 'm':
2490 conf->promiscuous = false;
2491 break;
2492
2493 case 'p':
2494 port = atoi(optarg);
2495 break;
2496
2497 case 'P':
2498 conf->daemonize = true;
2499 conf->pidfile = optarg;
2500 break;
2501
2502 case 'q':
2503 if (fr_debug_lvl > 0) {
2504 fr_debug_lvl--;
2505 }
2506 break;
2507
2508 case 'r':
2509 conf->filter_request = optarg;
2510 break;
2511
2512 case 'R':
2513 conf->filter_response = optarg;
2514 break;
2515
2516 case 's':
2518 conf->radius_secret = talloc_strdup(conf, optarg);
2519 break;
2520
2521 case 't':
2522 timeout = atoi(optarg);
2523 break;
2524
2525 case 'S':
2526 conf->to_stdout = true;
2527 break;
2528
2529 case 'v':
2530#ifdef HAVE_COLLECTDC_H
2531 INFO("%s, %s, collectdclient version %s", radsniff_version, pcap_lib_version(),
2532 lcc_version_string());
2533#else
2534 INFO("%s %s", radsniff_version, pcap_lib_version());
2535#endif
2536 fr_exit_now(EXIT_SUCCESS);
2537
2538 case 'w':
2539 out = fr_pcap_init(conf, optarg, PCAP_FILE_OUT);
2540 if (!out) {
2541 ERROR("Failed creating pcap file \"%s\"", optarg);
2542 fr_exit_now(EXIT_FAILURE);
2543 }
2544 conf->to_file = true;
2545 break;
2546
2547 case 'x':
2548 case 'X':
2549 fr_debug_lvl++;
2550 break;
2551
2552 case 'W':
2553 conf->stats.interval = atoi(optarg);
2554 conf->print_packet = false;
2555 if (conf->stats.interval <= 0) {
2556 ERROR("Stats interval must be > 0");
2557 usage(64);
2558 }
2559 break;
2560
2561 case 'Z':
2562 {
2563 char *p = optarg;
2564 size_t len = strlen(p);
2565
2566 conf->to_output_dir = true;
2567
2568 /* Strip the last '/' */
2569 if (p[len-1] == '/') p[len-1] = '\0';
2570
2571 conf->output_dir = p;
2572
2573 if (fr_mkdir(NULL, conf->output_dir, -1, 0755, NULL, NULL) < 0) {
2574 ERROR("Failed to create directory %s: %s", conf->output_dir, fr_syserror(errno));
2575 usage(64);
2576 }
2577 break;
2578 }
2579
2580 case 'T':
2581 conf->stats.timeout = atoi(optarg);
2582 if (conf->stats.timeout <= 0) {
2583 ERROR("Timeout value must be > 0");
2584 usage(64);
2585 }
2586 break;
2587
2588#ifdef HAVE_COLLECTDC_H
2589 case 'N':
2590 conf->stats.prefix = optarg;
2591 break;
2592
2593 case 'O':
2594 conf->stats.collectd = optarg;
2595 conf->stats.out = RS_STATS_OUT_COLLECTD;
2596 break;
2597#endif
2598 default:
2599 usage(64);
2600 }
2601 }
2602
2603 /*
2604 * Mismatch between the binary and the libraries it depends on
2605 */
2607 fr_perror("radsniff");
2608 fr_exit_now(EXIT_FAILURE);
2609 }
2610
2611 /* Useful for file globbing */
2612 while (optind < argc) {
2613 *in_head = fr_pcap_init(conf, argv[optind], PCAP_FILE_IN);
2614 if (!*in_head) {
2615 goto finish;
2616 }
2617 in_head = &(*in_head)->next;
2618 conf->from_file = true;
2619 optind++;
2620 }
2621
2622 /* Is stdin not a tty? If so it's probably a pipe */
2623 if (!isatty(fileno(stdin))) {
2624 conf->from_stdin = true;
2625 }
2626
2627 /* What's the point in specifying -F ?! */
2628 if (conf->from_stdin && conf->from_file && conf->to_file) {
2629 usage(64);
2630 }
2631
2632 /* Can't read from both... */
2633 if (conf->from_file && conf->from_dev) {
2634 ERROR("Can't read from both a file and a device");
2635 usage(64);
2636 }
2637
2638 /* Can't set stats export mode if we're not writing stats */
2639 if ((conf->stats.out == RS_STATS_OUT_STDIO_CSV) && !conf->stats.interval) {
2640 ERROR("CSV output requires a statistics interval (-W)");
2641 usage(64);
2642 }
2643
2644 /* Reading from file overrides stdin */
2645 if (conf->from_stdin && (conf->from_file || conf->from_dev)) {
2646 conf->from_stdin = false;
2647 }
2648
2649 /* Writing to file overrides stdout */
2650 if (conf->to_file && conf->to_stdout) {
2651 conf->to_stdout = false;
2652 }
2653
2654 if (conf->to_stdout) {
2655 out = fr_pcap_init(conf, "stdout", PCAP_STDIO_OUT);
2656 if (!out) {
2657 goto finish;
2658 }
2659 }
2660
2661 if (conf->from_stdin) {
2662 *in_head = fr_pcap_init(conf, "stdin", PCAP_STDIO_IN);
2663 if (!*in_head) {
2664 goto finish;
2665 }
2666 in_head = &(*in_head)->next;
2667 }
2668
2669 /* Set the default stats output */
2670 if (conf->stats.interval && !conf->stats.out) {
2672 }
2673
2674 if (conf->stats.timeout == 0) {
2675 conf->stats.timeout = RS_DEFAULT_TIMEOUT;
2676 }
2677
2678 /*
2679 * If we're writing pcap data, or CSV to stdout we *really* don't want to send
2680 * logging there as well.
2681 */
2683 fr_log_fp = stderr;
2684 }
2685
2686 if (conf->list_attributes) {
2688 } else if (conf->to_output_dir) {
2690 } else if (fr_debug_lvl > 0) {
2692 }
2693
2694#if !defined(HAVE_PCAP_FOPEN_OFFLINE) || !defined(HAVE_PCAP_DUMP_FOPEN)
2695 if (conf->from_stdin || conf->to_stdout) {
2696 ERROR("PCAP streams not supported");
2697 goto finish;
2698 }
2699#endif
2700
2701 if (!conf->pcap_filter) {
2702 conf->pcap_filter = talloc_asprintf(conf, "udp port %d or %d or %d", port, port + 1, FR_COA_UDP_PORT);
2703
2704 /*
2705 * Using the VLAN keyword strips off the .1q tag
2706 * allowing the UDP filter to work. Without this
2707 * tagged packets aren't processed.
2708 */
2709 conf->pcap_filter_vlan = talloc_asprintf(conf, "(%s) or (vlan and (%s))",
2711 }
2712
2713 if (!fr_dict_global_ctx_init(NULL, true, dict_dir)) {
2714 fr_perror("radsniff");
2715 fr_exit_now(EXIT_FAILURE);
2716 }
2717
2719 fr_perror("radsniff");
2720 ret = 64;
2721 goto finish;
2722 }
2723
2725 fr_perror("radsniff");
2726 ret = 64;
2727 goto finish;
2728 }
2729
2731 fr_perror("radsniff");
2732 ret = 64;
2733 goto finish;
2734 }
2735
2736 /* Initialise the protocol library */
2737 if (fr_radius_global_init() < 0) {
2738 fr_perror("radclient");
2739 return 1;
2740 }
2741
2742 fr_strerror_clear(); /* Clear out any non-fatal errors */
2743
2744 if (conf->list_attributes) {
2747 if (conf->list_da_num < 0) {
2748 usage(64);
2749 }
2751 }
2752
2753 if (conf->link_attributes) {
2756 if (conf->link_da_num < 0) {
2757 usage(64);
2758 }
2759
2761 if (!link_tree) {
2762 ERROR("Failed creating RTX tree");
2763 goto finish;
2764 }
2765 }
2766
2767 if (conf->filter_request) {
2768 fr_dcursor_t cursor;
2769 fr_pair_t *type;
2770
2772
2774 if (type) {
2775 fr_dcursor_remove(&cursor);
2776 conf->filter_request_code = type->vp_uint32;
2778 }
2779 }
2780
2781 if (conf->filter_response) {
2782 fr_dcursor_t cursor;
2783 fr_pair_t *type;
2784
2786
2788 if (type) {
2789 fr_dcursor_remove(&cursor);
2790 conf->filter_response_code = type->vp_uint32;
2792 }
2793 }
2794
2795 /*
2796 * Default to logging and capturing all events
2797 */
2798 if (conf->event_flags == 0) {
2799 DEBUG("Logging all events");
2800 memset(&conf->event_flags, 0xff, sizeof(conf->event_flags));
2801 }
2802
2803 /*
2804 * If we need to list attributes, link requests using attributes, filter attributes
2805 * or print the packet contents, we need to decode the attributes.
2806 *
2807 * But, if were just logging requests, or graphing packets, we don't need to decode
2808 * attributes.
2809 */
2811 conf->print_packet) {
2812 conf->decode_attrs = true;
2813 }
2814
2815 /*
2816 * Setup the request tree
2817 */
2819 if (!request_tree) {
2820 ERROR("Failed creating request tree");
2821 goto finish;
2822 }
2823
2824 /*
2825 * Get the default capture device
2826 */
2827 if (!conf->from_stdin && !conf->from_file && !conf->from_dev) {
2828 pcap_if_t *all_devices; /* List of all devices libpcap can listen on */
2829 pcap_if_t *dev_p;
2830
2831 if (pcap_findalldevs(&all_devices, errbuf) < 0) {
2832 ERROR("Error getting available capture devices: %s", errbuf);
2833 goto finish;
2834 }
2835
2836 if (!all_devices) {
2837 ERROR("No capture files specified and no live interfaces available");
2838 ret = 64;
2839 pcap_freealldevs(all_devices);
2840 goto finish;
2841 }
2842
2843 for (dev_p = all_devices;
2844 dev_p;
2845 dev_p = dev_p->next) {
2846 int link_layer;
2847
2848 /* Don't use the any device, it's horribly broken */
2849 if (!strcmp(dev_p->name, "any")) continue;
2850
2851 /* ...same here. See https://github.com/FreeRADIUS/freeradius-server/pull/3364 for details */
2852 if (!strncmp(dev_p->name, "pktap", 5)) continue;
2853
2854 link_layer = fr_pcap_if_link_layer(dev_p);
2855 if (link_layer < 0) {
2856 DEBUG2("Skipping %s: %s", dev_p->name, fr_strerror());
2857 continue;
2858 }
2859
2860 if (!fr_pcap_link_layer_supported(link_layer)) {
2861 DEBUG2("Skipping %s: datalink type %s not supported",
2862 dev_p->name, pcap_datalink_val_to_name(link_layer));
2863 continue;
2864 }
2865
2866 *in_head = fr_pcap_init(conf, dev_p->name, PCAP_INTERFACE_IN);
2867 in_head = &(*in_head)->next;
2868 }
2869 pcap_freealldevs(all_devices);
2870
2871 conf->from_auto = true;
2872 conf->from_dev = true;
2873 INFO("Defaulting to capture on all interfaces");
2874 }
2875
2876 /*
2877 * Print captures values which will be used
2878 */
2879 if (fr_debug_lvl > 2) {
2880 DEBUG2("Sniffing with options:");
2881 if (conf->from_dev) {
2882 char *buff = fr_pcap_device_names(conf, in, ' ');
2883 DEBUG2(" Device(s) : [%s]", buff);
2885 }
2886 if (out) {
2887 DEBUG2(" Writing to : [%s]", out->name);
2888 }
2889 if (conf->limit > 0) {
2890 DEBUG2(" Capture limit (packets) : [%" PRIu64 "]", conf->limit);
2891 }
2892 DEBUG2(" PCAP filter : [%s]", conf->pcap_filter);
2893 DEBUG2(" RADIUS secret : [%s]", conf->radius_secret);
2894
2896 DEBUG2(" RADIUS request code : [%s]", fr_radius_packet_name[conf->filter_request_code]);
2897 }
2898
2900 DEBUG2(" RADIUS request filter :");
2902 }
2903
2905 DEBUG2(" RADIUS response code : [%s]", fr_radius_packet_name[conf->filter_response_code]);
2906 }
2907
2908 if (conf->to_output_dir) {
2909 DEBUG2(" Writing packets in : [%s/{requests,reply}.${count}.txt]", conf->output_dir);
2910 }
2911
2913 DEBUG2(" RADIUS response filter :");
2915 }
2916 }
2917
2918 /*
2919 * Setup collectd templates
2920 */
2921#ifdef HAVE_COLLECTDC_H
2922 if (conf->stats.out == RS_STATS_OUT_COLLECTD) {
2923 size_t i;
2924 rs_stats_tmpl_t *tmpl, **next;
2925
2926 if (rs_stats_collectd_open(conf) < 0) {
2927 fr_exit_now(EXIT_FAILURE);
2928 }
2929
2930 next = &conf->stats.tmpl;
2931
2932 for (i = 0; i < (NUM_ELEMENTS(rs_useful_codes)); i++) {
2933 tmpl = rs_stats_collectd_init_latency(conf, next, conf, "exchanged",
2934 &(stats->exchange[rs_useful_codes[i]]),
2935 rs_useful_codes[i]);
2936 if (!tmpl) {
2937 ERROR("Error allocating memory for stats template");
2938 goto finish;
2939 }
2940 next = &(tmpl->next);
2941 }
2942 }
2943#endif
2944
2945 /*
2946 * This actually opens the capture interfaces/files (we just allocated the memory earlier)
2947 */
2948 {
2949 fr_pcap_t *tmp;
2950 fr_pcap_t **tmp_p = &tmp;
2951
2952 for (in_p = in;
2953 in_p;
2954 in_p = in_p->next) {
2955 in_p->promiscuous = conf->promiscuous;
2956 in_p->buffer_pkts = conf->buffer_pkts;
2957 if (fr_pcap_open(in_p) < 0) {
2958 fr_perror("Failed opening pcap handle (%s)", in_p->name);
2959 if (conf->from_auto || (in_p->type == PCAP_FILE_IN)) {
2960 continue;
2961 }
2962
2963 goto finish;
2964 }
2965
2966 if (!fr_pcap_link_layer_supported(in_p->link_layer)) {
2967 ERROR("Failed opening pcap handle (%s): Datalink type %s not supported",
2968 in_p->name, pcap_datalink_val_to_name(in_p->link_layer));
2969 goto finish;
2970 }
2971
2972 if (conf->pcap_filter) {
2973 /*
2974 * Not all link layers support VLAN tags
2975 * and this is the easiest way to discover
2976 * which do and which don't.
2977 */
2978 if ((!conf->pcap_filter_vlan ||
2979 (fr_pcap_apply_filter(in_p, conf->pcap_filter_vlan) < 0)) &&
2980 (fr_pcap_apply_filter(in_p, conf->pcap_filter) < 0)) {
2981 fr_perror("Failed applying filter");
2982 goto finish;
2983 }
2984 }
2985
2986 *tmp_p = in_p;
2987 tmp_p = &(in_p->next);
2988 }
2989 *tmp_p = NULL;
2990 in = tmp;
2991
2992 if (!in) {
2993 ERROR("No PCAP sources available");
2994 fr_exit_now(EXIT_FAILURE);
2995 }
2996
2997 /* Clear any irrelevant errors */
2999 }
3000
3001 /*
3002 * Open our output interface (if we have one);
3003 */
3004 if (out) {
3005 out->link_layer = -1; /* Infer output link type from input */
3006
3007 for (in_p = in;
3008 in_p;
3009 in_p = in_p->next) {
3010 if (out->link_layer < 0) {
3011 out->link_layer = in_p->link_layer;
3012 continue;
3013 }
3014
3015 if (out->link_layer != in_p->link_layer) {
3016 ERROR("Asked to write to output file, but inputs do not have the same link type");
3017 ret = 64;
3018 goto finish;
3019 }
3020 }
3021
3022 RS_ASSERT(out->link_layer >= 0);
3023
3024 if (fr_pcap_open(out) < 0) {
3025 fr_perror("Failed opening pcap output (%s)", out->name);
3026 goto finish;
3027 }
3028 }
3029
3030 /*
3031 * Get the offset between server time and wallclock time
3032 */
3033 fr_time_start();
3034
3035 /*
3036 * Setup and enter the main event loop. Who needs libev when you can roll your own...
3037 */
3038 {
3039 struct timeval now;
3040
3041 char *buff;
3042
3044 if (!events) {
3045 ERROR();
3046 goto finish;
3047 }
3048
3049 /*
3050 * Initialise the signal handler pipe
3051 */
3052 if (pipe(self_pipe) < 0) {
3053 ERROR("Couldn't open signal pipe: %s", fr_syserror(errno));
3054 fr_exit_now(EXIT_FAILURE);
3055 }
3056
3057 if (fr_event_fd_insert(NULL, NULL, events, self_pipe[0],
3059 NULL,
3060 NULL,
3061 events) < 0) {
3062 fr_perror("Failed inserting signal pipe descriptor");
3063 goto finish;
3064 }
3065
3066 buff = fr_pcap_device_names(conf, in, ' ');
3067 DEBUG("Sniffing on (%s)", buff);
3068
3069 /*
3070 * Insert our stats processor
3071 */
3072 if (conf->stats.interval && conf->from_dev) {
3073 now = fr_time_to_timeval(fr_time());
3074 rs_install_stats_processor(stats, events, in, &now, false);
3075 }
3076
3077 /*
3078 * Now add fd's for each of the pcap sessions we opened
3079 */
3080 for (in_p = in;
3081 in_p;
3082 in_p = in_p->next) {
3083 rs_event_t *event;
3084
3085 event = talloc_zero(events, rs_event_t);
3086 event->list = events;
3087 event->in = in_p;
3088 event->out = out;
3089 event->stats = stats;
3090
3091 /*
3092 * kevent() doesn't indicate that the
3093 * file is readable if there's not
3094 * sufficient packets in the file.
3095 *
3096 * Work around this by processing
3097 * files immediately, and only inserting
3098 * "live" inputs, i.e. stdin and
3099 * actual pcap sockets into the
3100 * event loop.
3101 */
3102 if (event->in->type == PCAP_FILE_IN) {
3103 rs_got_packet(events, in_p->fd, 0, event);
3104 } else if (fr_event_fd_insert(NULL, NULL, events, in_p->fd,
3106 NULL,
3107 NULL,
3108 event) < 0) {
3109 ERROR("Failed inserting file descriptor");
3110 goto finish;
3111 }
3112 }
3113
3114 if (timeout) {
3115 if (fr_event_timer_in(NULL, events, &timeout_ev, fr_time_delta_from_sec(timeout),
3116 timeout_event, NULL) < 0) {
3117 ERROR("Failed inserting timeout event");
3118 }
3119 }
3120 }
3121
3122 /*
3123 * If we just have the pipe, then exit.
3124 */
3125 if (fr_event_list_num_fds(events) == 1) goto finish;
3126
3127 /*
3128 * Do this as late as possible so we can return an error code if something went wrong.
3129 */
3130 if (conf->daemonize) {
3132 }
3133
3134 /*
3135 * Setup signal handlers so we always exit gracefully, ensuring output buffers are always
3136 * flushed.
3137 */
3138 fr_set_signal(SIGPIPE, rs_signal_self);
3140 fr_set_signal(SIGTERM, rs_signal_self);
3141#ifdef SIGQUIT
3142 fr_set_signal(SIGQUIT, rs_signal_self);
3143#endif
3144 DEBUG2("Entering event loop");
3145
3146 fr_event_loop(events); /* Enter the main event loop */
3147
3148 DEBUG2("Done sniffing");
3149
3150finish:
3151 cleanup = true;
3152
3153 if (conf->daemonize) unlink(conf->pidfile);
3154
3155 /*
3156 * Free all the things! This also closes all the sockets and file descriptors
3157 */
3159
3162
3163 /*
3164 * Ensure our atexit handlers run before any other
3165 * atexit handlers registered by third party libraries.
3166 */
3168
3169 return ret;
3170}
static int const char char buffer[256]
Definition acutest.h:576
int fr_atexit_global_setup(void)
Setup the atexit handler, should be called at the start of a program's execution.
Definition atexit.c:160
int fr_atexit_global_trigger_all(void)
Cause all global free triggers to fire.
Definition atexit.c:286
#define fr_base16_encode(_out, _in)
Definition base16.h:57
#define RCSID(id)
Definition build.h:483
#define NEVER_RETURNS
Should be placed before the function return type.
Definition build.h:313
#define L(_str)
Helper for initialising arrays of string literals.
Definition build.h:209
#define CMP_RETURN(_a, _b, _field)
Return if the comparison is not 0 (is unequal)
Definition build.h:121
#define CMP(_a, _b)
Same as CMP_PREFER_SMALLER use when you don't really care about ordering, you just want an ordering.
Definition build.h:112
#define UNUSED
Definition build.h:315
#define NUM_ELEMENTS(_t)
Definition build.h:337
#define FR_DBUFF_TMP(_start, _len_or_end)
Creates a compound literal to pass into functions which accept a dbuff.
Definition dbuff.h:514
static void * fr_dcursor_set_current(fr_dcursor_t *cursor, void *item)
Set the cursor to a specified item.
Definition dcursor.h:353
static void * fr_dcursor_filter_next(fr_dcursor_t *cursor, fr_dcursor_eval_t eval, void const *uctx)
Return the next item, skipping the current item, that satisfies an evaluation function.
Definition dcursor.h:545
static void * fr_dcursor_remove(fr_dcursor_t *cursor)
Remove the current item.
Definition dcursor.h:480
int fr_fault_setup(TALLOC_CTX *ctx, char const *cmd, char const *program)
Registers signal handlers to execute panic_action on fatal signal.
Definition debug.c:1242
#define fr_exit_now(_x)
Exit without calling atexit() handlers, producing a log message in debug builds.
Definition debug.h:234
fr_radius_packet_code_t
RADIUS packet codes.
Definition defs.h:31
@ FR_RADIUS_CODE_ACCESS_CHALLENGE
RFC2865 - Access-Challenge.
Definition defs.h:43
@ FR_RADIUS_CODE_ACCESS_REQUEST
RFC2865 - Access-Request.
Definition defs.h:33
@ FR_RADIUS_CODE_DISCONNECT_REQUEST
RFC3575/RFC5176 - Disconnect-Request.
Definition defs.h:46
@ FR_RADIUS_CODE_DISCONNECT_ACK
RFC3575/RFC5176 - Disconnect-Ack (positive)
Definition defs.h:47
@ FR_RADIUS_CODE_STATUS_SERVER
RFC2865/RFC5997 - Status Server (request)
Definition defs.h:44
@ FR_RADIUS_CODE_COA_REQUEST
RFC3575/RFC5176 - CoA-Request.
Definition defs.h:49
@ FR_RADIUS_CODE_ACCESS_ACCEPT
RFC2865 - Access-Accept.
Definition defs.h:34
@ FR_RADIUS_CODE_ACCOUNTING_RESPONSE
RFC2866 - Accounting-Response.
Definition defs.h:37
@ FR_RADIUS_CODE_COA_NAK
RFC3575/RFC5176 - CoA-Nak (not willing to perform)
Definition defs.h:51
@ FR_RADIUS_CODE_COA_ACK
RFC3575/RFC5176 - CoA-Ack (positive)
Definition defs.h:50
@ FR_RADIUS_CODE_DISCONNECT_NAK
RFC3575/RFC5176 - Disconnect-Nak (not willing to perform)
Definition defs.h:48
@ FR_RADIUS_CODE_ACCOUNTING_REQUEST
RFC2866 - Accounting-Request.
Definition defs.h:36
@ FR_RADIUS_CODE_ACCESS_REJECT
RFC2865 - Access-Reject.
Definition defs.h:35
#define FR_COA_UDP_PORT
Definition defs.h:63
#define FR_AUTH_UDP_PORT
Definition defs.h:57
#define ERROR(fmt,...)
Definition dhcpclient.c:41
#define DEBUG(fmt,...)
Definition dhcpclient.c:39
static NEVER_RETURNS void usage(void)
Definition dhcpclient.c:114
fr_dict_gctx_t * fr_dict_global_ctx_init(TALLOC_CTX *ctx, bool free_at_exit, char const *dict_dir)
Initialise the global protocol hashes.
Definition dict_util.c:4392
fr_dict_t * fr_dict_unconst(fr_dict_t const *dict)
Coerce to non-const.
Definition dict_util.c:4585
#define fr_dict_autofree(_to_free)
Definition dict.h:853
fr_dict_attr_t const * fr_dict_attr_by_name(fr_dict_attr_err_t *err, fr_dict_attr_t const *parent, char const *attr))
Locate a fr_dict_attr_t by its name.
Definition dict_util.c:3263
fr_dict_attr_t const * fr_dict_root(fr_dict_t const *dict)
Return the root attribute of a dictionary.
Definition dict_util.c:2400
fr_dict_attr_t const ** out
Where to write a pointer to the resolved fr_dict_attr_t.
Definition dict.h:268
fr_dict_t const ** out
Where to write a pointer to the loaded/resolved fr_dict_t.
Definition dict.h:281
int fr_dict_attr_autoload(fr_dict_attr_autoload_t const *to_load)
Process a dict_attr_autoload element to load/verify a dictionary attribute.
Definition dict_util.c:4090
#define fr_dict_autoload(_to_load)
Definition dict.h:850
int fr_dict_read(fr_dict_t *dict, char const *dict_dir, char const *filename)
Read supplementary attribute definitions into an existing dictionary.
static fr_slen_t in
Definition dict.h:824
Specifies an attribute which must be present for the module to function.
Definition dict.h:267
Specifies a dictionary which must be loaded/loadable for the module to function.
Definition dict.h:280
#define fr_event_fd_insert(...)
Definition event.h:232
@ FR_EVENT_FILTER_IO
Combined filter for read/write functions/.
Definition event.h:62
#define fr_event_timer_at(...)
Definition event.h:250
#define fr_event_timer_in(...)
Definition event.h:255
ssize_t fr_mkdir(int *fd_out, char const *path, ssize_t len, mode_t mode, fr_mkdir_func_t func, void *uctx)
Create directories that are missing in the specified path.
Definition file.c:219
int fr_unlink(char const *filename)
Remove a regular file from the filesystem.
Definition file.c:367
int8_t fr_ipaddr_cmp(fr_ipaddr_t const *a, fr_ipaddr_t const *b)
Compare two ip addresses.
Definition inet.c:1346
talloc_free(reap)
uint64_t fr_event_list_num_fds(fr_event_list_t *el)
Return the number of file descriptors is_registered with this event loop.
Definition event.c:601
int fr_event_timer_delete(fr_event_timer_t const **ev_p)
Delete a timer event from the event list.
Definition event.c:1611
fr_event_list_t * fr_event_list_alloc(TALLOC_CTX *ctx, fr_event_status_cb_t status, void *status_uctx)
Initialise a new event list.
Definition event.c:2899
bool fr_event_loop_exiting(fr_event_list_t *el)
Check to see whether the event loop is in the process of exiting.
Definition event.c:2755
int fr_event_timer_run(fr_event_list_t *el, fr_time_t *when)
Run a single scheduled timer event.
Definition event.c:2363
void fr_event_loop_exit(fr_event_list_t *el, int code)
Signal an event loop exit with the specified code.
Definition event.c:2744
int fr_event_fd_delete(fr_event_list_t *el, int fd, fr_event_filter_t filter)
Remove a file descriptor from the event loop.
Definition event.c:1260
int fr_event_loop(fr_event_list_t *el)
Run an event loop.
Definition event.c:2766
Stores all information relating to an event list.
Definition event.c:411
A timer event.
Definition event.c:102
int fr_debug_lvl
Definition log.c:43
FILE * fr_log_fp
Definition log.c:42
fr_log_t default_log
Definition log.c:291
int fr_log_init_file(fr_log_t *log, char const *file)
Initialise a file logging destination.
Definition log.c:1083
int fr_log_close(fr_log_t *log)
Universal close function for all logging destinations.
Definition log.c:1189
@ L_TIMESTAMP_OFF
Never log timestamps.
Definition log.h:91
@ L_DBG_LVL_2
2nd highest priority debug messages (-xx | -X).
Definition log.h:71
@ L_DBG_LVL_4
4th highest priority debug messages (-xxxx | -Xxx).
Definition log.h:73
fr_packet_t * fr_packet_alloc(TALLOC_CTX *ctx, bool new_vector)
Allocate a new fr_packet_t.
Definition packet.c:38
fr_packet_t * fr_packet_alloc_reply(TALLOC_CTX *ctx, fr_packet_t *packet)
Allocate a new fr_packet_t response.
Definition packet.c:63
void fr_packet_free(fr_packet_t **packet_p)
Free a fr_packet_t.
Definition packet.c:89
int8_t fr_packet_cmp(void const *a_v, void const *b_v)
Definition list.c:43
unsigned short uint16_t
@ FR_TYPE_STRING
String of printable characters.
@ FR_TYPE_UINT32
32 Bit unsigned integer.
unsigned int uint32_t
long int ssize_t
unsigned char uint8_t
unsigned long int size_t
void fr_quick_sort(void const *to_sort[], int start, int end, fr_cmp_t cmp)
Quick sort an array of pointers using a comparator.
Definition misc.c:429
int fr_set_signal(int sig, sig_t func)
Sets a signal handler using sigaction if available, else signal.
Definition misc.c:47
int8_t fr_pointer_cmp(void const *a, void const *b)
Compares two pointers.
Definition misc.c:417
char const * inet_ntop(int af, void const *src, char *dst, size_t cnt)
Definition missing.c:443
char * strsep(char **stringp, char const *delim)
Definition missing.c:123
struct tm * localtime_r(time_t const *l_clock, struct tm *result)
Definition missing.c:163
uint16_t fr_udp_checksum(uint8_t const *data, uint16_t len, uint16_t checksum, struct in_addr const src_addr, struct in_addr const dst_addr)
Calculate UDP checksum.
Definition net.c:119
uint16_t len
UDP length.
Definition net.h:141
struct in6_addr ip_src ip_dst
Src and Dst address.
Definition net.h:125
#define RADIUS_AUTH_VECTOR_LENGTH
Definition net.h:89
uint16_t dst
Destination port.
Definition net.h:140
uint16_t src
Source port.
Definition net.h:139
uint16_t checksum
UDP checksum.
Definition net.h:142
struct in_addr ip_src ip_dst
Src and Dst address.
Definition net.h:115
uint8_t ip_vhl
Header length, version.
Definition net.h:105
bool fr_pair_matches_da(void const *item, void const *uctx)
Evaluation function for matching if vp matches a given da.
Definition pair.c:3476
int fr_pair_list_cmp(fr_pair_list_t const *a, fr_pair_list_t const *b)
Determine equality of two lists.
Definition pair.c:2047
fr_pair_t * fr_pair_find_by_da(fr_pair_list_t const *list, fr_pair_t const *prev, fr_dict_attr_t const *da)
Find the first pair with a matching da.
Definition pair.c:693
int fr_pair_append(fr_pair_list_t *list, fr_pair_t *to_add)
Add a VP to the end of the list.
Definition pair.c:1345
void fr_pair_list_init(fr_pair_list_t *list)
Initialise a pair list header.
Definition pair.c:46
int fr_pair_steal(TALLOC_CTX *ctx, fr_pair_t *vp)
Steal one VP.
Definition pair.c:521
bool fr_pair_validate_relaxed(fr_pair_t const *failed[2], fr_pair_list_t *filter, fr_pair_list_t *list)
Uses fr_pair_cmp to verify all fr_pair_ts in list match the filter defined by check.
Definition pair.c:2205
fr_pair_t * fr_pair_copy(TALLOC_CTX *ctx, fr_pair_t const *vp)
Copy a single valuepair.
Definition pair.c:489
int8_t fr_pair_cmp_by_da(void const *a, void const *b)
Order attributes by their da, and tag.
Definition pair.c:1844
fr_slen_t fr_pair_list_afrom_substr(fr_pair_parse_t const *root, fr_pair_parse_t *relative, fr_sbuff_t *in)
Parse a fr_pair_list_t from a substring.
struct fr_pair_parse_s fr_pair_parse_t
TALLOC_CTX * ctx
Definition pair_legacy.h:43
int fr_radius_global_init(void)
Definition base.c:1218
ssize_t fr_radius_decode_simple(TALLOC_CTX *ctx, fr_pair_list_t *out, uint8_t *packet, size_t packet_len, uint8_t const *vector, char const *secret)
Simple wrapper for callers who just need a shared secret.
Definition base.c:1196
void fr_radius_global_free(void)
Definition base.c:1241
char const * fr_radius_packet_name[FR_RADIUS_CODE_MAX]
Definition base.c:112
int fr_packet_verify(fr_packet_t *packet, fr_packet_t *original, char const *secret)
Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet.
Definition packet.c:143
bool fr_packet_ok(fr_packet_t *packet, uint32_t max_attributes, bool require_message_authenticator, fr_radius_decode_fail_t *reason)
See if the data pointed to by PTR is a valid RADIUS packet.
Definition packet.c:119
static TALLOC_CTX * autofree
#define REDEBUG(fmt,...)
Definition radclient.h:52
#define RDEBUG2(fmt,...)
Definition radclient.h:54
#define RDEBUG(fmt,...)
Definition radclient.h:53
#define DEBUG2(fmt,...)
Definition radclient.h:43
#define INFO(fmt,...)
Definition radict.c:54
fr_radius_decode_fail_t
Failure reasons.
Definition radius.h:162
#define RADIUS_MAX_ATTRIBUTES
Definition radius.h:40
#define fr_packet_log_hex(_log, _packet)
Definition radius.h:270
#define FR_RADIUS_PACKET_CODE_VALID(_x)
Definition radius.h:52
fr_dict_attr_autoload_t radsniff_dict_attr[]
Definition radsniff.c:106
static void rs_stats_process(fr_event_list_t *el, fr_time_t now_t, void *ctx)
Process stats for a single interval.
Definition radsniff.c:844
static int rs_request_to_pcap(rs_event_t *event, rs_request_t *request, struct pcap_pkthdr const *header, uint8_t const *data)
Definition radsniff.c:1201
static struct timeval start_pcap
Definition radsniff.c:54
static size_t rs_snprint_csv(char *out, size_t outlen, char const *in, size_t inlen)
Definition radsniff.c:220
static fr_rb_tree_t * link_tree
Definition radsniff.c:58
static void rs_packet_print(rs_request_t *request, uint64_t count, rs_status_t status, fr_pcap_t *handle, fr_packet_t *packet, fr_pair_list_t *list, struct timeval *elapsed, struct timeval *latency, bool response, bool body)
Definition radsniff.c:529
static int self_pipe[2]
Signals from sig handlers.
Definition radsniff.c:63
#define RS_ASSERT(_x)
Definition radsniff.c:51
int main(int argc, char *argv[])
Definition radsniff.c:2318
static fr_dict_attr_t const * attr_packet_type
Definition radsniff.c:103
static void rs_stats_process_latency(rs_latency_t *stats)
Update smoothed average.
Definition radsniff.c:580
static ssize_t rs_stats_print_code_csv(char *out, size_t outlen, rs_latency_t *stats)
Definition radsniff.c:774
static void rs_stats_print_code_fancy(rs_latency_t *stats, fr_radius_packet_code_t code)
Definition radsniff.c:635
static void rs_daemonize(char const *pidfile)
Fork and kill the parent process, writing out our PID.
Definition radsniff.c:117
static int rs_install_stats_processor(rs_stats_t *stats, fr_event_list_t *el, fr_pcap_t *in, struct timeval *now, bool live)
Definition radsniff.c:939
static fr_event_list_t * events
Definition radsniff.c:59
static const uint8_t zeros[RADIUS_AUTH_VECTOR_LENGTH]
Definition radsniff.c:1261
static void rs_packet_save_in_output_dir(uint64_t count, UNUSED rs_status_t status, UNUSED fr_pcap_t *handle, fr_packet_t *packet, fr_pair_list_t *list, UNUSED struct timeval *elapsed, UNUSED struct timeval *latency, bool response, bool body)
Definition radsniff.c:478
static void rs_packet_print_csv_header(void)
Definition radsniff.c:268
static int packets_count
Definition radsniff.c:61
static fr_dict_t const * dict_freeradius
Definition radsniff.c:93
static int rs_response_to_pcap(rs_event_t *event, rs_request_t *request, struct pcap_pkthdr const *header, uint8_t const *data)
Definition radsniff.c:1151
static fr_rb_tree_t * request_tree
Definition radsniff.c:57
static fr_dict_t const * dict_radius
Definition radsniff.c:94
static rs_request_t * rs_request_alloc(TALLOC_CTX *ctx)
Definition radsniff.c:1247
static bool cleanup
Definition radsniff.c:60
static int _rs_event_status(UNUSED fr_time_t now, fr_time_delta_t wake_t, UNUSED void *uctx)
Definition radsniff.c:2019
static char const * radsniff_version
Definition radsniff.c:65
static void _unmark_request(void *request)
Callback for when the request is removed from the request tree.
Definition radsniff.c:2156
static int rs_build_event_flags(int *flags, fr_table_num_sorted_t const *map, size_t map_len, char *list)
Definition radsniff.c:2127
static int8_t rs_rtx_cmp(void const *one, void const *two)
Compare requests using packet info and lists of attributes.
Definition radsniff.c:2039
static void rs_stats_print_csv(rs_update_t *this, rs_stats_t *stats, UNUSED struct timeval *now)
Definition radsniff.c:799
static int rs_check_pcap_drop(fr_pcap_t *in)
Query libpcap to see if it dropped any packets.
Definition radsniff.c:552
static void rs_stats_print_fancy(rs_update_t *this, rs_stats_t *stats, struct timeval *now)
Definition radsniff.c:679
static size_t rs_events_len
Definition radsniff.c:91
static int rs_build_dict_list(fr_dict_attr_t const **out, size_t len, char *list)
Definition radsniff.c:2061
fr_dict_autoload_t radsniff_dict[]
Definition radsniff.c:97
static void rs_tv_add_ms(struct timeval const *start, unsigned long interval, struct timeval *result)
Definition radsniff.c:183
static void rs_time_print(char *out, size_t len, struct timeval const *t)
Definition radsniff.c:193
static void rs_signal_self(int sig)
Write the last signal to the signal pipe.
Definition radsniff.c:2209
static void rs_packet_cleanup(rs_request_t *request)
Definition radsniff.c:1061
static void _rs_event(UNUSED fr_event_list_t *el, UNUSED fr_time_t now, void *ctx)
Definition radsniff.c:1132
static void _unmark_link(void *request)
Callback for when the request is removed from the link tree.
Definition radsniff.c:2166
static void rs_stats_print_csv_header(rs_update_t *this)
Definition radsniff.c:726
static char timestr[50]
Definition radsniff.c:55
#define RS_CLEANUP_NOW(_x, _s)
Definition radsniff.c:1239
static void rs_got_packet(fr_event_list_t *el, int fd, UNUSED int flags, void *ctx)
Definition radsniff.c:1926
static void rs_packet_print_fancy(uint64_t count, rs_status_t status, fr_pcap_t *handle, fr_packet_t *packet, fr_pair_list_t *list, struct timeval *elapsed, struct timeval *latency, bool response, bool body)
Definition radsniff.c:383
static void rs_packet_process(uint64_t count, rs_event_t *event, struct pcap_pkthdr const *header, uint8_t const *data)
Definition radsniff.c:1263
static int8_t rs_packet_cmp(void const *one, void const *two)
Wrapper around fr_packet_cmp to strip off the outer request struct.
Definition radsniff.c:1143
static int rs_get_pairs(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_pair_list_t *vps, fr_dict_attr_t const *da[], int num)
Copy a subset of attributes from one list into the other.
Definition radsniff.c:994
static void rs_signal_action(UNUSED fr_event_list_t *list, int fd, int UNUSED flags, UNUSED void *ctx)
Read the last signal from the signal pipe.
Definition radsniff.c:2220
static void rs_packet_print_csv(uint64_t count, rs_status_t status, fr_pcap_t *handle, fr_packet_t *packet, fr_pair_list_t *list, UNUSED struct timeval *elapsed, struct timeval *latency, UNUSED bool response, bool body)
Definition radsniff.c:309
static void rs_stats_process_counters(rs_latency_t *stats)
Definition radsniff.c:620
static int rs_useful_codes[]
Definition radsniff.c:67
static rs_t * conf
Definition radsniff.c:53
static int _request_free(rs_request_t *request)
Definition radsniff.c:1028
static void rs_stats_update_latency(rs_latency_t *stats, struct timeval *latency)
Update latency statistics for request/response and forwarded packets.
Definition radsniff.c:922
static int rs_build_filter(fr_pair_list_t *out, char const *filter)
Definition radsniff.c:2097
static void timeout_event(fr_event_list_t *el, UNUSED fr_time_t now_t, UNUSED void *ctx)
Exit the event loop after a given timeout.
Definition radsniff.c:2175
static fr_table_num_sorted_t const rs_events[]
Definition radsniff.c:83
Structures and prototypes for the RADIUS sniffer.
fr_radius_packet_code_t filter_response_code
Filter response packets by code.
Definition radsniff.h:300
fr_pcap_t * in
PCAP handle event occurred on.
Definition radsniff.h:227
fr_packet_t * expect
Request/response.
Definition radsniff.h:195
bool to_output_dir
Were writing attributes into directory.
Definition radsniff.h:266
fr_event_timer_t const * event
Event created when we received the original request.
Definition radsniff.h:186
struct rs::@1 stats
rs_stats_print_cb_t body
Print body.
Definition radsniff.h:256
bool print_packet
Print packet info, disabled with -W.
Definition radsniff.h:274
uint8_t * data
PCAP packet data.
Definition radsniff.h:176
fr_dict_attr_t const * list_da[RS_MAX_ATTRS]
Output CSV with these attribute values.
Definition radsniff.h:287
char const * output_dir
Where we should save the files $PATH/requests.txt and $PATH/reply.txt.
Definition radsniff.h:267
@ RS_STATS_OUT_STDIO_CSV
Definition radsniff.h:86
@ RS_STATS_OUT_STDIO_FANCY
Definition radsniff.h:85
#define RS_DEFAULT_SECRET
Default secret.
Definition radsniff.h:41
bool in_request_tree
Whether the request is currently in the request tree.
Definition radsniff.h:217
rs_status_t event_flags
Events we log and capture on.
Definition radsniff.h:302
fr_dict_attr_t const * link_da[RS_MAX_ATTRS]
fr_dict_attr_ts to link on.
Definition radsniff.h:291
#define RIDEBUG(fmt,...)
Definition radsniff.h:65
uint64_t latency_smoothed_count
Number of CMA datapoints processed.
Definition radsniff.h:116
int link_da_num
Number of rtx fr_dict_attr_ts.
Definition radsniff.h:292
fr_radius_packet_code_t filter_request_code
Filter request packets by code.
Definition radsniff.h:299
rs_stats_t * stats
Stats to process.
Definition radsniff.h:254
int buffer_pkts
Size of the ring buffer to setup for live capture.
Definition radsniff.h:305
char const * filter_response
Raw response filter string.
Definition radsniff.h:295
fr_event_list_t * list
List to insert new event into.
Definition radsniff.h:251
int list_da_num
Definition radsniff.h:288
struct timeval when
Time when the packet was received, or next time an event is scheduled.
Definition radsniff.h:190
bool from_dev
Were reading pcap data from devices.
Definition radsniff.h:261
#define RS_FORCE_YIELD
Service another descriptor every X number of packets.
Definition radsniff.h:43
#define RS_DEFAULT_TIMEOUT
Standard timeout of 5s + 300ms to cover network latency.
Definition radsniff.h:42
rs_packet_logger_t logger
Packet logger.
Definition radsniff.h:303
char * pcap_filter_vlan
Variant of the normal filter to apply to devices which support VLAN tags.
Definition radsniff.h:283
char * pcap_filter
PCAP filter string applied to live capture devices.
Definition radsniff.h:282
rs_capture_t capture[RS_RETRANSMIT_MAX]
Buffered request packets (if a response filter has been applied).
Definition radsniff.h:201
bool from_auto
From list was auto-generated.
Definition radsniff.h:272
rs_latency_t * stats_req
Latency entry for the request type.
Definition radsniff.h:208
bool decode_attrs
Whether we should decode attributes in the request and response.
Definition radsniff.h:275
uint64_t id
Monotonically increasing packet counter.
Definition radsniff.h:185
rs_latency_t * stats_rsp
Latency entry for the request type.
Definition radsniff.h:209
bool to_file
Were writing pcap data to files.
Definition radsniff.h:263
fr_pair_list_t link_vps
fr_pair_ts used to link retransmissions.
Definition radsniff.h:199
fr_packet_t * packet
The original packet.
Definition radsniff.h:193
#define RS_RETRANSMIT_MAX
Maximum number of times we expect to see a packet retransmitted.
Definition radsniff.h:44
rs_stats_print_header_cb_t head
Print header.
Definition radsniff.h:255
char * list_attributes
Raw attribute filter string.
Definition radsniff.h:286
char * radius_secret
Secret to decode encrypted attributes.
Definition radsniff.h:280
bool from_file
Were reading pcap data from files.
Definition radsniff.h:260
fr_pcap_t * out
Where to write output.
Definition radsniff.h:228
#define RS_DEFAULT_PREFIX
Default instance.
Definition radsniff.h:40
fr_pcap_t * in
PCAP handle the original request was received on.
Definition radsniff.h:192
fr_pcap_t * in
Linked list of PCAP handles to check for drops.
Definition radsniff.h:253
rs_capture_t * capture_p
Next packet slot.
Definition radsniff.h:203
bool in_link_tree
Whether the request is currently in the linked tree.
Definition radsniff.h:218
struct timeval quiet
We may need to 'mute' the stats if libpcap starts dropping packets, or we run out of memory.
Definition radsniff.h:170
#define RIDEBUG_ENABLED()
Definition radsniff.h:60
int intervals
Number of stats intervals.
Definition radsniff.h:163
fr_event_list_t * list
The event list.
Definition radsniff.h:225
fr_packet_t * linked
The subsequent response or forwarded request the packet.
Definition radsniff.h:197
bool verify_radius_authenticator
Check RADIUS authenticator in packets.
Definition radsniff.h:278
uint64_t limit
Maximum number of packets to capture.
Definition radsniff.h:306
char const * pidfile
File to write PID to.
Definition radsniff.h:270
uint64_t rt_rsp
Number of times we saw a retransmitted response packet.
Definition radsniff.h:206
bool from_stdin
Were reading pcap data from stdin.
Definition radsniff.h:262
bool daemonize
Daemonize and write PID out to file.
Definition radsniff.h:269
double latency_smoothed
Smoothed moving average.
Definition radsniff.h:115
uint64_t rt_req
Number of times we saw the same request packet.
Definition radsniff.h:205
rs_latency_t exchange[FR_RADIUS_CODE_MAX+1]
We end up allocating ~16K, but memory is cheap so.
Definition radsniff.h:165
fr_pair_list_t filter_response_vps
Sorted filter vps.
Definition radsniff.h:298
bool promiscuous
Capture in promiscuous mode.
Definition radsniff.h:273
fr_pair_list_t expect_vps
Definition radsniff.h:196
fr_pair_list_t packet_vps
Definition radsniff.h:194
bool logged
Whether any messages regarding this request were logged.
Definition radsniff.h:188
char * link_attributes
Names of fr_dict_attr_ts to use for rtx.
Definition radsniff.h:290
bool silent_cleanup
Cleanup was forced before normal expiry period, ignore stats about packet loss.
Definition radsniff.h:211
char const * filter_request
Raw request filter string.
Definition radsniff.h:294
rs_status_t
Definition radsniff.h:69
@ RS_ERROR
Definition radsniff.h:74
@ RS_UNLINKED
Definition radsniff.h:71
@ RS_REUSED
Definition radsniff.h:73
@ RS_LOST
Definition radsniff.h:75
@ RS_NORMAL
Definition radsniff.h:70
@ RS_RTX
Definition radsniff.h:72
struct pcap_pkthdr * header
PCAP packet header.
Definition radsniff.h:175
#define RS_SOCKET_REOPEN_DELAY
How long we delay re-opening a collectd socket.
Definition radsniff.h:46
bool verify_udp_checksum
Check UDP checksum in packets.
Definition radsniff.h:277
bool to_stdout
Were writing pcap data to stdout.
Definition radsniff.h:264
struct rs_latency_t::@0 interval
fr_pair_list_t filter_request_vps
Sorted filter vps.
Definition radsniff.h:297
Definition radsniff.h:259
Statistic write/print event.
Definition radsniff.h:224
Stats for a single interval.
Definition radsniff.h:112
Wrapper for fr_packet_t.
Definition radsniff.h:184
One set of statistics.
Definition radsniff.h:162
FD data which gets passed to callbacks.
Definition radsniff.h:249
void * fr_rb_find(fr_rb_tree_t const *tree, void const *data)
Find an element in the tree, returning the data, not the node.
Definition rb.c:577
bool fr_rb_insert(fr_rb_tree_t *tree, void const *data)
Insert data into a tree.
Definition rb.c:626
bool fr_rb_delete(fr_rb_tree_t *tree, void const *data)
Remove node and free data (if a free function was specified)
Definition rb.c:741
#define fr_rb_inline_talloc_alloc(_ctx, _type, _field, _data_cmp, _data_free)
Allocs a red black that verifies elements are of a specific talloc type.
Definition rb.h:246
The main red black tree structure.
Definition rb.h:73
static char const * name
ssize_t fr_sbuff_in_sprintf(fr_sbuff_t *sbuff, char const *fmt,...)
Print using a fmt string to an sbuff.
Definition sbuff.c:1595
#define fr_sbuff_start(_sbuff_or_marker)
#define FR_SBUFF_IN(_start, _len_or_end)
#define fr_sbuff_current(_sbuff_or_marker)
#define fr_sbuff_advance(_sbuff_or_marker, _len)
#define fr_sbuff_remaining(_sbuff_or_marker)
#define FR_SBUFF_OUT(_start, _len_or_end)
#define fr_sbuff_in_char(_sbuff,...)
static char buff[sizeof("18446744073709551615")+3]
Definition size_tests.c:41
PUBLIC int snprintf(char *string, size_t length, char *format, va_alist)
Definition snprintf.c:689
return count
Definition module.c:163
fr_aka_sim_id_type_t type
fr_pair_t * vp
#define fr_time()
Allow us to arbitrarily manipulate time.
Definition state_test.c:8
size_t strlcpy(char *dst, char const *src, size_t siz)
Definition strlcpy.c:34
Definition log.h:96
fr_log_timestamp_t timestamp
Prefix log messages with timestamps.
Definition log.h:110
bool print_level
sometimes we don't want log levels printed
Definition log.h:106
FILE * handle
Path to log file.
Definition log.h:116
Stores an attribute, a value and various bits of other data.
Definition pair.h:68
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition syserror.c:243
#define fr_table_value_by_str(_table, _name, _def)
Convert a string to a value using a sorted or ordered table.
Definition table.h:653
#define fr_table_str_by_value(_table, _number, _def)
Convert an integer to a string.
Definition table.h:772
An element in a lexicographically sorted array of name to num mappings.
Definition table.h:49
#define talloc_autofree_context
The original function is deprecated, so replace it with our version.
Definition talloc.h:51
int fr_time_sync(void)
Get a new fr_time_monotonic_to_realtime value.
Definition time.c:102
int fr_time_start(void)
Initialize the local time.
Definition time.c:150
Simple time functions.
static fr_time_t fr_time_from_timeval(struct timeval const *when_tv)
Convert a timeval (wallclock time) to a fr_time_t (internal time)
Definition time.h:896
static fr_time_delta_t fr_time_delta_from_msec(int64_t msec)
Definition time.h:575
static fr_time_delta_t fr_time_delta_from_sec(int64_t sec)
Definition time.h:590
#define fr_time_wrap(_time)
Definition time.h:145
#define fr_time_delta_to_timeval(_delta)
Convert a delta to a timeval.
Definition time.h:656
#define fr_time_add(_a, _b)
Add a time/time delta together.
Definition time.h:196
#define fr_time_to_timeval(_when)
Convert server epoch time to unix epoch time.
Definition time.h:742
#define USEC
Definition time.h:380
#define fr_time_sub(_a, _b)
Subtract one time from another.
Definition time.h:229
#define fr_time_delta_gt(_a, _b)
Definition time.h:283
A time delta, a difference in time measured in nanoseconds.
Definition time.h:80
"server local" time.
Definition time.h:69
void fr_timeval_subtract(struct timeval *out, struct timeval const *end, struct timeval const *start)
Subtract one timeval from another.
Definition timeval.c:36
@ T_BARE_WORD
Definition token.h:120
close(uq->fd)
static fr_event_list_t * el
static void print_packet(FILE *fp, fr_packet_t *packet, fr_pair_list_t *list)
static fr_slen_t head
Definition xlat.h:422
#define FR_DICTIONARY_FILE
Definition conf.h:7
unsigned int code
Packet code (type).
Definition packet.h:61
fr_socket_t socket
This packet was received on.
Definition packet.h:57
int id
Packet ID (used to link requests/responses).
Definition packet.h:60
uint8_t * data
Packet data (body).
Definition packet.h:63
size_t data_len
Length of packet data.
Definition packet.h:64
uint8_t vector[RADIUS_AUTH_VECTOR_LENGTH]
RADIUS authentication vector.
Definition packet.h:69
fr_time_t timestamp
When we received the packet.
Definition packet.h:58
#define fr_pair_dcursor_by_da_init(_cursor, _list, _da)
Initialise a cursor that will return only attributes matching the specified fr_dict_attr_t.
Definition pair.h:628
bool fr_pair_list_empty(fr_pair_list_t const *list)
Is a valuepair list empty.
void fr_pair_list_sort(fr_pair_list_t *list, fr_cmp_t cmp)
Sort a doubly linked list of fr_pair_ts using merge sort.
fr_pair_t * fr_pair_list_next(fr_pair_list_t const *list, fr_pair_t const *item))
Get the next item in a valuepair list after a specific entry.
Definition pair_inline.c:70
void fr_pair_list_free(fr_pair_list_t *list)
Free memory used by a valuepair list.
void fr_pair_list_append(fr_pair_list_t *dst, fr_pair_list_t *src)
Appends a list of fr_pair_t from a temporary list to a destination list.
ssize_t fr_pair_print_value_quoted(fr_sbuff_t *out, fr_pair_t const *vp, fr_token_t quote)
Print the value of an attribute to a string.
Definition pair_print.c:53
#define fr_pair_list_log(_log, _lvl, _list)
Definition pair.h:857
#define fr_pair_dcursor_init(_cursor, _list)
Initialises a special dcursor with callbacks that will maintain the attr sublists correctly.
Definition pair.h:591
fr_pair_t * fr_pair_list_head(fr_pair_list_t const *list)
Get the head of a valuepair list.
Definition pair_inline.c:43
int af
AF_INET, AF_INET6, or AF_UNIX.
Definition socket.h:78
int type
SOCK_STREAM, SOCK_DGRAM, etc.
Definition socket.h:79
char const * fr_strerror(void)
Get the last library error.
Definition strerror.c:554
void fr_perror(char const *fmt,...)
Print the current error to stderr with a prefix.
Definition strerror.c:733
void fr_strerror_clear(void)
Clears all pending messages from the talloc pools.
Definition strerror.c:577
int fr_check_lib_magic(uint64_t magic)
Check if the application linking to the library has the correct magic number.
Definition version.c:40
#define RADIUSD_VERSION_BUILD(_x)
Create a version string for a utility in the suite of FreeRADIUS utilities.
Definition version.h:58
#define RADIUSD_MAGIC_NUMBER
Definition version.h:81
static fr_slen_t data
Definition value.h:1265
static size_t char fr_sbuff_t size_t inlen
Definition value.h:997
static size_t char ** out
Definition value.h:997