Remove unused variable
[freeradius.git] / src / main / radsniff.c
1 /*
2  *  radsniff.c  Display the RADIUS traffic on the network.
3  *
4  *  Version:    $Id$
5  *
6  *  This program is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU General Public License
8  *  as published by the Free Software Foundation; either version 2
9  *  of the License, or (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  *  Copyright 2006  The FreeRADIUS server project
21  *  Copyright 2006  Nicolas Baradakis <nicolas.baradakis@cegetel.net>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #define _LIBRADIUS 1
28 #include <freeradius-devel/libradius.h>
29
30 #include <pcap.h>
31
32 #include <freeradius-devel/radpaths.h>
33 #include <freeradius-devel/conf.h>
34 #include <freeradius-devel/radsniff.h>
35
36 static const char *radius_secret = "testing123";
37 static VALUE_PAIR *filter_vps = NULL;
38
39 static int do_sort = 0;
40 static int to_stdout = 0;
41 static FILE *log_dst;
42
43 #ifndef PCAP_NETMASK_UNKNOWN
44 #  define PCAP_NETMASK_UNKNOWN 0
45 #endif
46
47 #undef DEBUG1
48 #define DEBUG1 if (fr_debug_flag > 2) fprintf
49 #undef DEBUG
50 #define DEBUG if (fr_debug_flag > 1) fprintf
51 #undef INFO
52 #define INFO if (fr_debug_flag > 0) fprintf
53
54 struct timeval start_pcap = {0, 0};
55 static rbtree_t *filter_tree = NULL;
56 static rbtree_t *request_tree = NULL;
57 static pcap_dumper_t *out = NULL;
58 static RADIUS_PACKET *nullpacket = NULL;
59
60 typedef int (*rbcmp)(const void *, const void *);
61
62 static const char *radsniff_version = "radsniff version " RADIUSD_VERSION_STRING
63 #ifdef RADIUSD_VERSION_COMMIT
64 " (git #" RADIUSD_VERSION_COMMIT ")"
65 #endif
66 ", built on " __DATE__ " at " __TIME__;
67
68 static int filter_packet(RADIUS_PACKET *packet)
69 {
70         VALUE_PAIR *check_item;
71         VALUE_PAIR *vp;
72         unsigned int pass, fail;
73         int compare;
74
75         pass = fail = 0;
76         for (vp = packet->vps; vp != NULL; vp = vp->next) {
77                 for (check_item = filter_vps;
78                      check_item != NULL;
79                      check_item = check_item->next)
80                         if ((check_item->da == vp->da)
81                          && (check_item->op != T_OP_SET)) {
82                                 compare = paircmp(check_item, vp);
83                                 if (compare == 1)
84                                         pass++;
85                                 else
86                                         fail++;
87                         }
88         }
89
90         if (fail == 0 && pass != 0) {
91                 /*
92                  *      Cache authentication requests, as the replies
93                  *      may not match the RADIUS filter.
94                  */
95                 if ((packet->code == PW_AUTHENTICATION_REQUEST) ||
96                     (packet->code == PW_ACCOUNTING_REQUEST)) {
97                         rbtree_deletebydata(filter_tree, packet);
98                         
99                         if (!rbtree_insert(filter_tree, packet)) {
100                         oom:
101                                 fprintf(stderr, "radsniff: Out of memory\n");
102                                 exit(1);
103                         }
104                 }
105                 return 0;       /* matched */
106         }
107
108         /*
109          *      Don't create erroneous matches.
110          */
111         if ((packet->code == PW_AUTHENTICATION_REQUEST) ||
112             (packet->code == PW_ACCOUNTING_REQUEST)) {
113                 rbtree_deletebydata(filter_tree, packet);
114                 return 1;
115         }
116         
117         /*
118          *      Else see if a previous Access-Request
119          *      matched.  If so, also print out the
120          *      matching accept, reject, or challenge.
121          */
122         if ((packet->code == PW_AUTHENTICATION_ACK) ||
123             (packet->code == PW_AUTHENTICATION_REJECT) ||
124             (packet->code == PW_ACCESS_CHALLENGE) ||
125             (packet->code == PW_ACCOUNTING_RESPONSE)) {
126                 RADIUS_PACKET *reply;
127
128                 /*
129                  *      This swaps the various fields.
130                  */
131                 reply = rad_alloc_reply(NULL, packet);
132                 if (!reply) goto oom;
133                 
134                 compare = 1;
135                 if (rbtree_finddata(filter_tree, reply)) {
136                         compare = 0;
137                 }
138                 
139                 rad_free(&reply);
140                 return compare;
141         }
142         
143         return 1;
144 }
145
146 /*
147  *      Bubble goodness
148  */
149 static void sort(RADIUS_PACKET *packet)
150 {
151         int i, j, size;
152         VALUE_PAIR *vp, *tmp;
153         VALUE_PAIR *array[1024]; /* way more than necessary */
154
155         size = 0;
156         for (vp = packet->vps; vp != NULL; vp = vp->next) {
157                 array[size++] = vp;
158         }
159
160         if (size == 0) return;
161
162         for (i = 0; i < size - 1; i++)  {
163                 for (j = 0; j < size - 1 - i; j++) {
164                         if (array[j + 1]->da->attr < array[j]->da->attr)  {
165                                 tmp = array[j];         
166                                 array[j] = array[j + 1];
167                                 array[j + 1] = tmp;
168                         }
169                 }
170         }
171
172         /*
173          *      And put them back again.
174          */
175         vp = packet->vps = array[0];
176         for (i = 1; i < size; i++) {
177                 vp->next = array[i];
178                 vp = array[i];
179         }
180         vp->next = NULL;
181 }
182
183 #define USEC 1000000
184 static void tv_sub(const struct timeval *end, const struct timeval *start,
185                    struct timeval *elapsed)
186 {
187         elapsed->tv_sec = end->tv_sec - start->tv_sec;
188         if (elapsed->tv_sec > 0) {
189                 elapsed->tv_sec--;
190                 elapsed->tv_usec = USEC;
191         } else {
192                 elapsed->tv_usec = 0;
193         }
194         elapsed->tv_usec += end->tv_usec;
195         elapsed->tv_usec -= start->tv_usec;
196         
197         if (elapsed->tv_usec >= USEC) {
198                 elapsed->tv_usec -= USEC;
199                 elapsed->tv_sec++;
200         }
201 }
202
203 static void got_packet(UNUSED uint8_t *args, const struct pcap_pkthdr *header, const uint8_t *data)
204 {
205
206         static int count = 1;                   /* Packets seen */
207         
208         /*
209          *  Define pointers for packet's attributes
210          */
211         const struct ip_header *ip;             /* The IP header */
212         const struct udp_header *udp;           /* The UDP header */
213         const uint8_t *payload;                 /* Packet payload */
214         
215         /*
216          *  And define the size of the structures we're using
217          */
218         int size_ethernet = sizeof(struct ethernet_header);
219         int size_ip = sizeof(struct ip_header);
220         int size_udp = sizeof(struct udp_header);
221         
222         /*
223          *  For FreeRADIUS
224          */
225         RADIUS_PACKET *packet, *original;
226         struct timeval elapsed;
227
228         /*
229          * Define our packet's attributes
230          */
231
232         if ((data[0] == 2) && (data[1] == 0) &&
233             (data[2] == 0) && (data[3] == 0)) {
234                 ip = (const struct ip_header*) (data + 4);
235
236         } else {
237                 ip = (const struct ip_header*)(data + size_ethernet);
238         }
239         
240         udp = (const struct udp_header*)(((const uint8_t *) ip) + size_ip);
241         payload = (const uint8_t *)(((const uint8_t *) udp) + size_udp);
242
243         packet = rad_alloc(NULL, 0);
244         if (!packet) {
245                 fprintf(stderr, "Out of memory\n");
246                 return;
247         }
248
249         packet->src_ipaddr.af = AF_INET;
250         packet->src_ipaddr.ipaddr.ip4addr.s_addr = ip->ip_src.s_addr;
251         packet->src_port = ntohs(udp->udp_sport);
252         packet->dst_ipaddr.af = AF_INET;
253         packet->dst_ipaddr.ipaddr.ip4addr.s_addr = ip->ip_dst.s_addr;
254         packet->dst_port = ntohs(udp->udp_dport);
255
256         memcpy(&packet->data, &payload, sizeof(packet->data));
257         packet->data_len = header->len - (payload - data);
258
259         if (!rad_packet_ok(packet, 0)) {
260                 DEBUG(log_dst, "Packet: %s\n", fr_strerror());
261                 
262                 DEBUG(log_dst, "  From     %s:%d\n", inet_ntoa(ip->ip_src), ntohs(udp->udp_sport));
263                 DEBUG(log_dst, "  To:      %s:%d\n", inet_ntoa(ip->ip_dst), ntohs(udp->udp_dport));
264                 DEBUG(log_dst, "  Type:    %s\n", fr_packet_codes[packet->code]);
265
266                 rad_free(&packet);
267                 return;
268         }
269         
270         switch (packet->code) {
271         case PW_COA_REQUEST:
272                 /* we need a 16 x 0 byte vector for decrypting encrypted VSAs */
273                 original = nullpacket;
274                 break;
275         case PW_AUTHENTICATION_ACK:
276                 /* look for a matching request and use it for decoding */
277                 original = rbtree_finddata(request_tree, packet);
278                 break;
279         case PW_AUTHENTICATION_REQUEST:
280                 /* save the request for later matching */
281                 original = rad_alloc_reply(NULL, packet);
282                 if (original) { /* just ignore allocation failures */
283                         rbtree_deletebydata(request_tree, original);
284                         rbtree_insert(request_tree, original);
285                 }
286                 /* fallthrough */
287         default:
288                 /* don't attempt to decode any encrypted attributes */
289                 original = NULL;
290         }
291
292         /*
293          *  Decode the data without bothering to check the signatures.
294          */
295         if (rad_decode(packet, original, radius_secret) != 0) {
296                 rad_free(&packet);
297                 fr_perror("decode");
298                 return;
299         }
300
301         /*
302          *  We've seen a successfull reply to this, so delete it now
303          */
304         if (original)
305                 rbtree_deletebydata(request_tree, original);
306
307         if (filter_vps && filter_packet(packet)) {
308                 rad_free(&packet);
309                 DEBUG(log_dst, "Packet number %d doesn't match\n", count++);
310                 return;
311         }
312
313         if (out) {
314                 pcap_dump((void *) out, header, data);
315                 goto check_filter;
316         }
317
318         INFO(log_dst, "%s Id %d\t", fr_packet_codes[packet->code], packet->id);
319
320         /*
321          *  Print the RADIUS packet
322          */
323         INFO(log_dst, "%s:%d -> ", inet_ntoa(ip->ip_src), ntohs(udp->udp_sport));
324         INFO(log_dst, "%s:%d", inet_ntoa(ip->ip_dst), ntohs(udp->udp_dport));
325         
326         DEBUG1(log_dst, "\t(%d packets)", count++);
327         
328         if (!start_pcap.tv_sec) {
329                 start_pcap = header->ts;
330         }
331
332         tv_sub(&header->ts, &start_pcap, &elapsed);
333
334         INFO(log_dst, "\t+%u.%03u", (unsigned int) elapsed.tv_sec,
335                (unsigned int) elapsed.tv_usec / 1000);
336                
337         if (fr_debug_flag > 1) {
338                 DEBUG(log_dst, "\n");
339                 if (packet->vps) {
340                         if (do_sort) sort(packet);
341         
342                         vp_printlist(log_dst, packet->vps);
343                         pairfree(&packet->vps);
344                 }
345         }
346         
347         INFO(log_dst, "\n");
348         
349         if (!to_stdout && (fr_debug_flag > 4)) {
350                 rad_print_hex(packet);
351         }
352         
353         fflush(log_dst);
354
355  check_filter:
356         /*
357          *  If we're doing filtering, Access-Requests are cached in the
358          *  filter tree.
359          */
360         if (!filter_vps ||
361             ((packet->code != PW_AUTHENTICATION_REQUEST) &&
362              (packet->code != PW_ACCOUNTING_REQUEST))) {
363                 rad_free(&packet);
364         }
365 }
366
367 static void NEVER_RETURNS usage(int status)
368 {
369         FILE *output = status ? stderr : stdout;
370         fprintf(output, "Usage: radsniff [options]\n");
371         fprintf(output, "options:\n");
372         fprintf(output, "  -c <count>      Number of packets to capture.\n");
373         fprintf(output, "  -d <directory>  Set dictionary directory.\n");
374         fprintf(output, "  -F              Filter PCAP file from stdin to stdout.\n");
375         fprintf(output, "  -f <filter>     PCAP filter (default is 'udp port <port> or <port + 1> or 3799')\n");
376         fprintf(output, "  -h              This help message.\n");
377         fprintf(output, "  -i <interface>  Capture packets from interface (defaults to any if supported).\n");
378         fprintf(output, "  -I <file>       Read packets from file (overrides input of -F).\n");
379         fprintf(output, "  -p <port>       Filter packets by port (default is 1812).\n");
380         fprintf(output, "  -q              Print less debugging information.\n");
381         fprintf(output, "  -r <filter>     RADIUS attribute filter.\n");
382         fprintf(output, "  -s <secret>     RADIUS secret.\n");
383         fprintf(output, "  -S              Sort attributes in the packet (useful for diffing responses).\n");
384         fprintf(output, "  -v              Show program version information.\n");
385         fprintf(output, "  -w <file>       Write output packets to file (overrides output of -F).\n");
386         fprintf(output, "  -x              Print more debugging information (defaults to -xx).\n");
387         exit(status);
388 }
389
390 int main(int argc, char *argv[])
391 {
392         const char *from_dev = NULL;                    /* Capture from device */
393         const char *from_file = NULL;                   /* Read from pcap file */
394         int from_stdin = 0;                             /* Read from stdin */
395         
396         pcap_t *in;                                     /* PCAP input handle */
397         
398         int limit = -1;                                 /* How many packets to sniff */
399         
400         char errbuf[PCAP_ERRBUF_SIZE];                  /* Error buffer */
401
402         char *to_file = NULL;                           /* PCAP output file */
403         
404         char *pcap_filter = NULL;                       /* PCAP filter string */
405         char *radius_filter = NULL;
406         int port = 1812;
407         
408         struct bpf_program fp;                          /* Holds compiled filter */
409         bpf_u_int32 ip_mask = PCAP_NETMASK_UNKNOWN;     /* Device Subnet mask */
410         bpf_u_int32 ip_addr = 0;                        /* Device IP */
411         
412         char buffer[1024];
413
414         int opt;
415         FR_TOKEN parsecode;
416         const char *radius_dir = RADIUS_DIR;
417         
418         fr_debug_flag = 2;
419         log_dst = stdout;
420
421         /*
422          *  Get options
423          */
424         while ((opt = getopt(argc, argv, "c:d:Ff:hi:I:p:qr:s:Svw:xX")) != EOF) {
425                 switch (opt)
426                 {
427                 case 'c':
428                         limit = atoi(optarg);
429                         if (limit <= 0) {
430                                 fprintf(stderr, "radsniff: Invalid number of packets \"%s\"\n", optarg);
431                                 exit(1);
432                         }
433                         break;
434                 case 'd':
435                         radius_dir = optarg;
436                         break;
437                 case 'F':
438                         from_stdin = 1;
439                         to_stdout = 1;
440                         break;
441                 case 'f':
442                         pcap_filter = optarg;
443                         break;
444                 case 'h':
445                         usage(0);
446                         break;
447                 case 'i':
448                         from_dev = optarg;
449                         break;
450                 case 'I':
451                         from_file = optarg;
452                         break;
453                 case 'p':
454                         port = atoi(optarg);
455                         break;
456                 case 'q':
457                         if (fr_debug_flag > 0) {
458                                 fr_debug_flag--;
459                         }
460                         break;
461                 case 'r':
462                         radius_filter = optarg;
463                         break;
464                 case 's':
465                         radius_secret = optarg;
466                         break;
467                 case 'S':
468                         do_sort = 1;
469                         break;
470                 case 'v':
471                         INFO(log_dst, "%s %s\n", radsniff_version, pcap_lib_version());
472                         exit(0);
473                         break;
474                 case 'w':
475                         to_file = optarg;
476                         break;
477                 case 'x':
478                 case 'X':
479                         fr_debug_flag++;
480                         break;
481                 default:
482                         usage(64);
483                 }
484         }
485         
486         /* What's the point in specifying -F ?! */
487         if (from_stdin && from_file && to_file) {
488                 usage(64);
489         }
490         
491         /* Can't read from both... */
492         if (from_file && from_dev) {
493                 usage(64);
494         }
495         
496         /* Reading from file overrides stdin */
497         if (from_stdin && (from_file || from_dev)) {
498                 from_stdin = 0;
499         }
500         
501         /* Writing to file overrides stdout */
502         if (to_file && to_stdout) {
503                 to_stdout = 0;
504         }
505         
506         /*
507          *  If were writing pcap data stdout we *really* don't want to send
508          *  logging there as well.
509          */
510         log_dst = to_stdout ? stderr : stdout;
511
512 #if !defined(HAVE_PCAP_FOPEN_OFFLINE) || !defined(HAVE_PCAP_DUMP_FOPEN)
513         if (from_stdin || to_stdout) {
514                 fprintf(stderr, "radsniff: PCAP streams not supported.\n");
515                 exit(64);
516         }
517 #endif
518
519         if (!pcap_filter) {
520                 pcap_filter = buffer;
521                 snprintf(buffer, sizeof(buffer), "udp port %d or %d or %d",
522                          port, port + 1, 3799);
523         }
524         
525         /*
526          *  There are times when we don't need the dictionaries.
527          */
528         if (!to_stdout) {
529                 if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
530                         fr_perror("radsniff");
531                         exit(64);
532                 }
533         }
534
535         if (radius_filter) {
536                 parsecode = userparse(radius_filter, &filter_vps);
537                 if (parsecode == T_OP_INVALID) {
538                         fprintf(stderr, "radsniff: Invalid RADIUS filter \"%s\" (%s)\n", radius_filter, fr_strerror());
539                         exit(64);
540                 }
541                 
542                 if (!filter_vps) {
543                         fprintf(stderr, "radsniff: Empty RADIUS filter \"%s\"\n", radius_filter);
544                         exit(64);
545                 }
546
547                 filter_tree = rbtree_create((rbcmp) fr_packet_cmp, free, 0);
548                 if (!filter_tree) {
549                         fprintf(stderr, "radsniff: Failed creating filter tree\n");
550                         exit(1);
551                 }
552         }
553
554         /*
555          *  Setup the request tree
556          */
557         request_tree = rbtree_create((rbcmp) fr_packet_cmp, free, 0);
558         if (!request_tree) {
559                 fprintf(stderr, "radsniff: Failed creating request tree\n");
560                 exit(1);
561         }
562
563         /*
564          *  Allocate a null packet for decrypting attributes in CoA requests
565          */
566         nullpacket = rad_alloc(NULL, 0);
567         if (!nullpacket) {
568                 fprintf(stderr, "radsniff: Out of memory\n");
569                 exit(1);
570         }
571
572         /*
573          *  Get the default capture device
574          */
575         if (!from_stdin && !from_file && !from_dev) {
576                 from_dev = pcap_lookupdev(errbuf);
577                 if (!from_dev) {
578                         fprintf(stderr, "radsniff: Failed discovering default interface (%s)\n", errbuf);
579                         exit(1);
580                 }
581
582                 INFO(log_dst, "Capturing from interface \"%s\"\n", from_dev);
583         }
584         
585         /*
586          *  Print captures values which will be used
587          */
588         if (fr_debug_flag > 2) {
589                                 DEBUG1(log_dst, "Sniffing with options:\n");
590                 if (from_dev)   DEBUG1(log_dst, "  Device                   : [%s]\n", from_dev);
591                 if (limit > 0)  DEBUG1(log_dst, "  Capture limit (packets)  : [%d]\n", limit);
592                                 DEBUG1(log_dst, "  PCAP filter              : [%s]\n", pcap_filter);
593                                 DEBUG1(log_dst, "  RADIUS secret            : [%s]\n", radius_secret);
594                 if (filter_vps){DEBUG1(log_dst, "  RADIUS filter            :\n");
595                         vp_printlist(log_dst, filter_vps);
596                 }
597         }
598
599         /*
600          *  Figure out whether were doing a reading from a file, doing a live
601          *  capture or reading from stdin.
602          */
603         if (from_file) {
604                 in = pcap_open_offline(from_file, errbuf);
605 #ifdef HAVE_PCAP_FOPEN_OFFLINE
606         } else if (from_stdin) {
607                 in = pcap_fopen_offline(stdin, errbuf);
608 #endif
609         } else if (from_dev) {
610                 pcap_lookupnet(from_dev, &ip_addr, &ip_mask, errbuf);
611                 in = pcap_open_live(from_dev, 65536, 1, 1, errbuf);
612         } else {
613                 fprintf(stderr, "radsniff: No capture devices available\n");
614         }
615         
616         if (!in) {
617                 fprintf(stderr, "radsniff: Failed opening input (%s)\n", errbuf);
618                 exit(1);
619         }
620
621         if (to_file) {
622                 out = pcap_dump_open(in, to_file);
623                 if (!out) {
624                         fprintf(stderr, "radsniff: Failed opening output file (%s)\n", pcap_geterr(in));
625                         exit(1);
626                 }
627 #ifdef HAVE_PCAP_DUMP_FOPEN
628         } else if (to_stdout) {
629                 out = pcap_dump_fopen(in, stdout);
630                 if (!out) {
631                         fprintf(stderr, "radsniff: Failed opening stdout (%s)\n", pcap_geterr(in));
632                         exit(1);
633                 }
634 #endif
635         }
636
637         /*
638          *  Apply the rules
639          */
640         if (pcap_compile(in, &fp, pcap_filter, 0, ip_mask) < 0) {
641                 fprintf(stderr, "radsniff: Failed compiling PCAP filter (%s)\n", pcap_geterr(in));
642                 exit(1);
643         }
644         
645         if (pcap_setfilter(in, &fp) < 0) {
646                 fprintf(stderr, "radsniff: Failed applying PCAP filter (%s)\n", pcap_geterr(in));
647                 exit(1);
648         }
649
650         /*
651          *  Enter the main capture loop...
652          */
653         pcap_loop(in, limit, got_packet, NULL);
654         
655         /*
656          *  ...were done capturing.
657          */
658         pcap_close(in);
659         if (out) {
660                 pcap_dump_close(out);
661         }
662         
663         if (filter_tree) {
664                 rbtree_free(filter_tree);
665         }
666         
667         INFO(log_dst, "Done sniffing\n");
668         
669         return 0;
670 }