Add ENV[PANIC_ACTION] support to all applications
[freeradius.git] / src / main / radclient.c
1 /*
2  * radclient.c  General radius packet debug tool.
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (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 2000,2006  The FreeRADIUS server project
21  * Copyright 2000  Miquel van Smoorenburg <miquels@cistron.nl>
22  * Copyright 2000  Alan DeKok <aland@ox.org>
23  */
24
25 RCSID("$Id$")
26
27 #include <freeradius-devel/libradius.h>
28 #include <freeradius-devel/conf.h>
29 #include <freeradius-devel/radpaths.h>
30
31 #include <ctype.h>
32
33 #ifdef HAVE_GETOPT_H
34 #       include <getopt.h>
35 #endif
36
37 #include <assert.h>
38
39 typedef struct REQUEST REQUEST; /* to shut up warnings about mschap.h */
40
41 #include "smbdes.h"
42 #include "mschap.h"
43
44 static int success = 0;
45 static int retries = 3;
46 static float timeout = 5;
47 static char const *secret = NULL;
48 static int do_output = 1;
49 static int totalapp = 0;
50 static int totaldeny = 0;
51 static int totallost = 0;
52
53 static int server_port = 0;
54 static int packet_code = 0;
55 static fr_ipaddr_t server_ipaddr;
56 static int resend_count = 1;
57 static int done = 1;
58 static int print_filename = 0;
59
60 static fr_ipaddr_t client_ipaddr;
61 static int client_port = 0;
62
63 static int sockfd;
64 static int last_used_id = -1;
65
66 #ifdef WITH_TCP
67 char const *proto = NULL;
68 #endif
69 static int ipproto = IPPROTO_UDP;
70
71 static rbtree_t *filename_tree = NULL;
72 static fr_packet_list_t *pl = NULL;
73
74 static int sleep_time = -1;
75
76 typedef struct radclient_t {
77         struct          radclient_t *prev;
78         struct          radclient_t *next;
79
80         char const      *filename;
81         int             packet_number; /* in the file */
82         char            password[256];
83         time_t          timestamp;
84         RADIUS_PACKET   *request;
85         RADIUS_PACKET   *reply;
86         int             resend;
87         int             tries;
88         int             done;
89 } radclient_t;
90
91 static radclient_t *radclient_head = NULL;
92 static radclient_t *radclient_tail = NULL;
93
94 char const *radclient_version = "radclient version " RADIUSD_VERSION_STRING
95 #ifdef RADIUSD_VERSION_COMMIT
96 " (git #" STRINGIFY(RADIUSD_VERSION_COMMIT) ")"
97 #endif
98 ", built on " __DATE__ " at " __TIME__;
99
100 static void NEVER_RETURNS usage(void)
101 {
102         fprintf(stderr, "Usage: radclient [options] server[:port] <command> [<secret>]\n");
103
104         fprintf(stderr, "  <command>     One of auth, acct, status, coa, or disconnect.\n");
105         fprintf(stderr, "  -c <count>    Send each packet 'count' times.\n");
106         fprintf(stderr, "  -d <raddb>    Set dictionary directory.\n");
107         fprintf(stderr, "  -f <file>     Read packets from file, not stdin.\n");
108         fprintf(stderr, "  -F            Print the file name, packet number and reply code.\n");
109         fprintf(stderr, "  -h            Print usage help information.\n");
110         fprintf(stderr, "  -i <id>       Set request id to 'id'.  Values may be 0..255\n");
111         fprintf(stderr, "  -n <num>      Send N requests/s\n");
112         fprintf(stderr, "  -p <num>      Send 'num' packets from a file in parallel.\n");
113         fprintf(stderr, "  -q            Do not print anything out.\n");
114         fprintf(stderr, "  -r <retries>  If timeout, retry sending the packet 'retries' times.\n");
115         fprintf(stderr, "  -s            Print out summary information of auth results.\n");
116         fprintf(stderr, "  -S <file>     read secret from file, not command line.\n");
117         fprintf(stderr, "  -t <timeout>  Wait 'timeout' seconds before retrying (may be a floating point number).\n");
118         fprintf(stderr, "  -v            Show program version information.\n");
119         fprintf(stderr, "  -x            Debugging mode.\n");
120         fprintf(stderr, "  -4            Use IPv4 address of server\n");
121         fprintf(stderr, "  -6            Use IPv6 address of server.\n");
122 #ifdef WITH_TCP
123         fprintf(stderr, "  -P <proto>    Use proto (tcp or udp) for transport.\n");
124 #endif
125
126         exit(1);
127 }
128
129 /*
130  *      Free a radclient struct, which may (or may not)
131  *      already be in the list.
132  */
133 static void radclient_free(radclient_t *radclient)
134 {
135         radclient_t *prev, *next;
136
137         if (radclient->request) rad_free(&radclient->request);
138         if (radclient->reply) rad_free(&radclient->reply);
139
140         prev = radclient->prev;
141         next = radclient->next;
142
143         if (prev) {
144                 assert(radclient_head != radclient);
145                 prev->next = next;
146         } else if (radclient_head) {
147                 assert(radclient_head == radclient);
148                 radclient_head = next;
149         }
150
151         if (next) {
152                 assert(radclient_tail != radclient);
153                 next->prev = prev;
154         } else if (radclient_tail) {
155                 assert(radclient_tail == radclient);
156                 radclient_tail = prev;
157         }
158
159         free(radclient);
160 }
161
162 static int mschapv1_encode(RADIUS_PACKET *packet, VALUE_PAIR **request,
163                            char const *password)
164 {
165         unsigned int i;
166         uint8_t *p;
167         VALUE_PAIR *challenge, *response;
168         uint8_t nthash[16];
169
170         challenge = paircreate(packet, PW_MSCHAP_CHALLENGE, VENDORPEC_MICROSOFT);
171         if (!challenge) {
172                 return 0;
173         }
174
175         pairadd(request, challenge);
176         challenge->length = 8;
177         challenge->vp_octets = p = talloc_array(challenge, uint8_t, challenge->length);
178         for (i = 0; i < challenge->length; i++) {
179                 p[i] = fr_rand();
180         }
181
182         response = paircreate(packet, PW_MSCHAP_RESPONSE, VENDORPEC_MICROSOFT);
183         if (!response) {
184                 return 0;
185         }
186
187         pairadd(request, response);
188         response->length = 50;
189         response->vp_octets = p = talloc_array(response, uint8_t, response->length);
190         memset(p, 0, response->length);
191
192         p[1] = 0x01; /* NT hash */
193
194         if (mschap_ntpwdhash(nthash, password) < 0) {
195                 return 0;
196         }
197
198         smbdes_mschap(nthash, challenge->vp_octets, p + 26);
199         return 1;
200 }
201
202
203 /*
204  *      Initialize a radclient data structure and add it to
205  *      the global linked list.
206  */
207 static int radclient_init(char const *filename)
208 {
209         FILE *fp;
210         vp_cursor_t cursor;
211         VALUE_PAIR *vp;
212         radclient_t *radclient;
213         int filedone = 0;
214         int packet_number = 1;
215
216         assert(filename != NULL);
217
218         /*
219          *      Determine where to read the VP's from.
220          */
221         if (strcmp(filename, "-") != 0) {
222                 fp = fopen(filename, "r");
223                 if (!fp) {
224                         fprintf(stderr, "radclient: Error opening %s: %s\n",
225                                 filename, fr_syserror(errno));
226                         return 0;
227                 }
228         } else {
229                 fp = stdin;
230         }
231
232         /*
233          *      Loop until the file is done.
234          */
235         do {
236                 /*
237                  *      Allocate it.
238                  */
239                 radclient = malloc(sizeof(*radclient));
240                 if (!radclient) {
241                         goto oom;
242                 }
243                 memset(radclient, 0, sizeof(*radclient));
244
245                 radclient->request = rad_alloc(NULL, 1);
246                 if (!radclient->request) {
247                         goto oom;
248                 }
249
250 #ifdef WITH_TCP
251                 radclient->request->src_ipaddr = client_ipaddr;
252                 radclient->request->src_port = client_port;
253                 radclient->request->dst_ipaddr = server_ipaddr;
254                 radclient->request->dst_port = server_port;
255 #endif
256
257                 radclient->filename = filename;
258                 radclient->request->id = -1; /* allocate when sending */
259                 radclient->packet_number = packet_number++;
260
261                 /*
262                  *      Read the VP's.
263                  */
264                 radclient->request->vps = readvp2(NULL, fp, &filedone, "radclient:");
265                 if (!radclient->request->vps) {
266                         rad_free(&radclient->request);
267                         free(radclient);
268                         if (fp != stdin) fclose(fp);
269                         return 1;
270                 }
271
272                 /*
273                  *      Keep a copy of the the User-Password attribute.
274                  */
275                 if ((vp = pairfind(radclient->request->vps, PW_USER_PASSWORD, 0, TAG_ANY)) != NULL) {
276                         strlcpy(radclient->password, vp->vp_strvalue,
277                                 sizeof(radclient->password));
278                         /*
279                          *      Otherwise keep a copy of the CHAP-Password attribute.
280                          */
281                 } else if ((vp = pairfind(radclient->request->vps, PW_CHAP_PASSWORD, 0, TAG_ANY)) != NULL) {
282                         strlcpy(radclient->password, vp->vp_strvalue,
283                                 sizeof(radclient->password));
284
285                 } else if ((vp = pairfind(radclient->request->vps, PW_MSCHAP_PASSWORD, 0, TAG_ANY)) != NULL) {
286                         strlcpy(radclient->password, vp->vp_strvalue,
287                                 sizeof(radclient->password));
288                 } else {
289                         radclient->password[0] = '\0';
290                 }
291
292                 /*
293                  *      Fix up Digest-Attributes issues
294                  */
295                 for (vp = paircursor(&cursor, &radclient->request->vps);
296                      vp;
297                      vp = pairnext(&cursor)) {
298                         /*
299                          *      Double quoted strings get marked up as xlat expansions,
300                          *      but we don't support that in radclient.
301                          */
302                         if (vp->type == VT_XLAT) {
303                                 vp->vp_strvalue = vp->value.xlat;
304                                 vp->value.xlat = NULL;
305                                 vp->type = VT_DATA;
306                         }
307
308                         if (!vp->da->vendor) switch (vp->da->attr) {
309                         default:
310                                 break;
311
312                                 /*
313                                  *      Allow it to set the packet type in
314                                  *      the attributes read from the file.
315                                  */
316                         case PW_PACKET_TYPE:
317                                 radclient->request->code = vp->vp_integer;
318                                 break;
319
320                         case PW_PACKET_DST_PORT:
321                                 radclient->request->dst_port = (vp->vp_integer & 0xffff);
322                                 break;
323
324                         case PW_PACKET_DST_IP_ADDRESS:
325                                 radclient->request->dst_ipaddr.af = AF_INET;
326                                 radclient->request->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
327                                 break;
328
329                         case PW_PACKET_DST_IPV6_ADDRESS:
330                                 radclient->request->dst_ipaddr.af = AF_INET6;
331                                 radclient->request->dst_ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
332                                 break;
333
334                         case PW_PACKET_SRC_PORT:
335                                 radclient->request->src_port = (vp->vp_integer & 0xffff);
336                                 break;
337
338                         case PW_PACKET_SRC_IP_ADDRESS:
339                                 radclient->request->src_ipaddr.af = AF_INET;
340                                 radclient->request->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
341                                 break;
342
343                         case PW_PACKET_SRC_IPV6_ADDRESS:
344                                 radclient->request->src_ipaddr.af = AF_INET6;
345                                 radclient->request->src_ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
346                                 break;
347
348                         case PW_DIGEST_REALM:
349                         case PW_DIGEST_NONCE:
350                         case PW_DIGEST_METHOD:
351                         case PW_DIGEST_URI:
352                         case PW_DIGEST_QOP:
353                         case PW_DIGEST_ALGORITHM:
354                         case PW_DIGEST_BODY_DIGEST:
355                         case PW_DIGEST_CNONCE:
356                         case PW_DIGEST_NONCE_COUNT:
357                         case PW_DIGEST_USER_NAME:
358                                 /* overlapping! */
359                                 {
360                                         DICT_ATTR const *da;
361                                         uint8_t *p;
362
363                                         p = talloc_array(vp, uint8_t, vp->length + 2);
364
365                                         memcpy(p + 2, vp->vp_octets, vp->length);
366                                         p[0] = vp->da->attr - PW_DIGEST_REALM + 1;
367                                         vp->length += 2;
368                                         p[1] = vp->length;
369
370                                         pairmemsteal(vp, p);
371
372                                         da = dict_attrbyvalue(PW_DIGEST_ATTRIBUTES, 0);
373                                         if (!da) {
374                                                 goto oom;
375                                         }
376
377                                         vp->da = da;
378                                 }
379
380                                 break;
381                         }
382                 } /* loop over the VP's we read in */
383
384                 /*
385                  *      Add it to the tail of the list.
386                  */
387                 if (!radclient_head) {
388                         assert(radclient_tail == NULL);
389                         radclient_head = radclient;
390                         radclient->prev = NULL;
391                 } else {
392                         assert(radclient_tail->next == NULL);
393                         radclient_tail->next = radclient;
394                         radclient->prev = radclient_tail;
395                 }
396                 radclient_tail = radclient;
397                 radclient->next = NULL;
398
399         } while (!filedone); /* loop until the file is done. */
400
401         if (fp != stdin) fclose(fp);
402
403         /*
404          *      And we're done.
405          */
406         return 1;
407
408         oom:
409         fprintf(stderr, "radclient: Out of memory\n");
410         free(radclient);
411         if (fp != stdin) fclose(fp);
412         return 0;
413 }
414
415
416 /*
417  *      Sanity check each argument.
418  */
419 static int radclient_sane(radclient_t *radclient)
420 {
421         if (radclient->request->dst_port == 0) {
422                 radclient->request->dst_port = server_port;
423         }
424         if (radclient->request->dst_ipaddr.af == AF_UNSPEC) {
425                 if (server_ipaddr.af == AF_UNSPEC) {
426                         fprintf(stderr, "radclient: No server was given, but request %d in file %s did not contain Packet-Dst-IP-Address\n",
427                                 radclient->packet_number, radclient->filename);
428                         return -1;
429                 }
430                 radclient->request->dst_ipaddr = server_ipaddr;
431         }
432         if (radclient->request->code == 0) {
433                 if (packet_code == -1) {
434                         fprintf(stderr, "radclient: Request was \"auto\", but request %d in file %s did not contain Packet-Type\n",
435                                 radclient->packet_number, radclient->filename);
436                         return -1;
437                 }
438                 radclient->request->code = packet_code;
439         }
440         radclient->request->sockfd = -1;
441
442         return 0;
443 }
444
445
446 /*
447  *      For request handline.
448  */
449 static int filename_cmp(void const *one, void const *two)
450 {
451         return strcmp((char const *) one, (char const *) two);
452 }
453
454 static int filename_walk(UNUSED void *context, void *data)
455 {
456         char const      *filename = data;
457
458         /*
459          *      Read request(s) from the file.
460          */
461         if (!radclient_init(filename)) {
462                 return -1;      /* stop walking */
463         }
464
465         return 0;
466 }
467
468
469 /*
470  *      Deallocate packet ID, etc.
471  */
472 static void deallocate_id(radclient_t *radclient)
473 {
474         if (!radclient || !radclient->request ||
475             (radclient->request->id < 0)) {
476                 return;
477         }
478
479         /*
480          *      One more unused RADIUS ID.
481          */
482         fr_packet_list_id_free(pl, radclient->request, true);
483
484         /*
485          *      If we've already sent a packet, free up the old one,
486          *      and ensure that the next packet has a unique
487          *      authentication vector.
488          */
489         if (radclient->request->data) {
490                 talloc_free(radclient->request->data);
491                 radclient->request->data = NULL;
492         }
493
494         if (radclient->reply) rad_free(&radclient->reply);
495 }
496
497
498 static void print_hex(RADIUS_PACKET *packet)
499 {
500         int i;
501
502         if (!packet->data) return;
503
504         printf("  Code:\t\t%u\n", packet->data[0]);
505         printf("  Id:\t\t%u\n", packet->data[1]);
506         printf("  Length:\t%u\n", ((packet->data[2] << 8) |
507                                    (packet->data[3])));
508         printf("  Vector:\t");
509         for (i = 4; i < 20; i++) {
510                 printf("%02x", packet->data[i]);
511         }
512         printf("\n");
513
514         if (packet->data_len > 20) {
515                 int total;
516                 uint8_t const *ptr;
517                 printf("  Data:");
518
519                 total = packet->data_len - 20;
520                 ptr = packet->data + 20;
521
522                 while (total > 0) {
523                         int attrlen;
524
525                         printf("\t\t");
526                         if (total < 2) { /* too short */
527                                 printf("%02x\n", *ptr);
528                                 break;
529                         }
530
531                         if (ptr[1] > total) { /* too long */
532                                 for (i = 0; i < total; i++) {
533                                         printf("%02x ", ptr[i]);
534                                 }
535                                 break;
536                         }
537
538                         printf("%02x  %02x  ", ptr[0], ptr[1]);
539                         attrlen = ptr[1] - 2;
540                         ptr += 2;
541                         total -= 2;
542
543                         for (i = 0; i < attrlen; i++) {
544                                 if ((i > 0) && ((i & 0x0f) == 0x00))
545                                         printf("\t\t\t");
546                                 printf("%02x ", ptr[i]);
547                                 if ((i & 0x0f) == 0x0f) printf("\n");
548                         }
549
550                         if ((attrlen & 0x0f) != 0x00) printf("\n");
551
552                         ptr += attrlen;
553                         total -= attrlen;
554                 }
555         }
556         fflush(stdout);
557 }
558
559 /*
560  *      Send one packet.
561  */
562 static int send_one_packet(radclient_t *radclient)
563 {
564         assert(radclient->done == 0);
565
566         /*
567          *      Remember when we have to wake up, to re-send the
568          *      request, of we didn't receive a response.
569          */
570         if ((sleep_time == -1) ||
571             (sleep_time > (int) timeout)) {
572                 sleep_time = (int) timeout;
573         }
574
575         /*
576          *      Haven't sent the packet yet.  Initialize it.
577          */
578         if (radclient->request->id == -1) {
579                 int i;
580                 bool rcode;
581
582                 assert(radclient->reply == NULL);
583
584                 /*
585                  *      Didn't find a free packet ID, we're not done,
586                  *      we don't sleep, and we stop trying to process
587                  *      this packet.
588                  */
589         retry:
590                 radclient->request->src_ipaddr.af = server_ipaddr.af;
591                 rcode = fr_packet_list_id_alloc(pl, ipproto,
592                                                 &radclient->request, NULL);
593                 if (!rcode) {
594                         int mysockfd;
595
596 #ifdef WITH_TCP
597                         if (proto) {
598                                 mysockfd = fr_tcp_client_socket(NULL,
599                                                                 &server_ipaddr,
600                                                                 server_port);
601                         } else
602 #endif
603                         mysockfd = fr_socket(&client_ipaddr, 0);
604                         if (mysockfd < 0) {
605                                 fprintf(stderr, "radclient: Can't open new socket: %s\n",
606                                         fr_syserror(errno));
607                                 exit(1);
608                         }
609                         if (!fr_packet_list_socket_add(pl, mysockfd, ipproto,
610                                                        &server_ipaddr,
611                                                        server_port, NULL)) {
612                                 fprintf(stderr, "radclient: Can't add new socket\n");
613                                 exit(1);
614                         }
615                         goto retry;
616                 }
617
618                 assert(radclient->request->id != -1);
619                 assert(radclient->request->data == NULL);
620
621                 for (i = 0; i < 4; i++) {
622                         ((uint32_t *) radclient->request->vector)[i] = fr_rand();
623                 }
624
625                 /*
626                  *      Update the password, so it can be encrypted with the
627                  *      new authentication vector.
628                  */
629                 if (radclient->password[0] != '\0') {
630                         VALUE_PAIR *vp;
631
632                         if ((vp = pairfind(radclient->request->vps, PW_USER_PASSWORD, 0, TAG_ANY)) != NULL) {
633                                 pairstrcpy(vp, radclient->password);
634
635                         } else if ((vp = pairfind(radclient->request->vps, PW_CHAP_PASSWORD, 0, TAG_ANY)) != NULL) {
636                                 int already_hex = 0;
637
638                                 /*
639                                  *      If it's 17 octets, it *might* be already encoded.
640                                  *      Or, it might just be a 17-character password (maybe UTF-8)
641                                  *      Check it for non-printable characters.  The odds of ALL
642                                  *      of the characters being 32..255 is (1-7/8)^17, or (1/8)^17,
643                                  *      or 1/(2^51), which is pretty much zero.
644                                  */
645                                 if (vp->length == 17) {
646                                         for (i = 0; i < 17; i++) {
647                                                 if (vp->vp_octets[i] < 32) {
648                                                         already_hex = 1;
649                                                         break;
650                                                 }
651                                         }
652                                 }
653
654                                 /*
655                                  *      Allow the user to specify ASCII or hex CHAP-Password
656                                  */
657                                 if (!already_hex) {
658                                         uint8_t *p;
659                                         size_t len, len2;
660
661                                         len = len2 = strlen(radclient->password);
662                                         if (len2 < 17) len2 = 17;
663
664                                         p = talloc_zero_array(vp, uint8_t, len2);
665
666                                         memcpy(p, radclient->password, len);
667
668                                         rad_chap_encode(radclient->request,
669                                                         p,
670                                                         fr_rand() & 0xff, vp);
671                                         vp->vp_octets = p;
672                                         vp->length = 17;
673                                 }
674                         } else if (pairfind(radclient->request->vps, PW_MSCHAP_PASSWORD, 0, TAG_ANY) != NULL) {
675                                 mschapv1_encode(radclient->request,
676                                                 &radclient->request->vps,
677                                                 radclient->password);
678                         } else if (fr_debug_flag) {
679                                 printf("WARNING: No password in the request\n");
680                         }
681                 }
682
683                 radclient->timestamp = time(NULL);
684                 radclient->tries = 1;
685                 radclient->resend++;
686
687 #ifdef WITH_TCP
688                 /*
689                  *      WTF?
690                  */
691                 if (client_port == 0) {
692                         client_ipaddr = radclient->request->src_ipaddr;
693                         client_port = radclient->request->src_port;
694                 }
695 #endif
696
697         } else {                /* radclient->request->id >= 0 */
698                 time_t now = time(NULL);
699
700                 /*
701                  *      FIXME: Accounting packets are never retried!
702                  *      The Acct-Delay-Time attribute is updated to
703                  *      reflect the delay, and the packet is re-sent
704                  *      from scratch!
705                  */
706
707                 /*
708                  *      Not time for a retry, do so.
709                  */
710                 if ((now - radclient->timestamp) < timeout) {
711                         /*
712                          *      When we walk over the tree sending
713                          *      packets, we update the minimum time
714                          *      required to sleep.
715                          */
716                         if ((sleep_time == -1) ||
717                             (sleep_time > (now - radclient->timestamp))) {
718                                 sleep_time = now - radclient->timestamp;
719                         }
720                         return 0;
721                 }
722
723                 /*
724                  *      We're not trying later, maybe the packet is done.
725                  */
726                 if (radclient->tries == retries) {
727                         assert(radclient->request->id >= 0);
728
729                         /*
730                          *      Delete the request from the tree of
731                          *      outstanding requests.
732                          */
733                         fr_packet_list_yank(pl, radclient->request);
734
735                         fprintf(stderr, "radclient: no response from server for ID %d socket %d\n", radclient->request->id, radclient->request->sockfd);
736                         deallocate_id(radclient);
737
738                         /*
739                          *      Normally we mark it "done" when we've received
740                          *      the response, but this is a special case.
741                          */
742                         if (radclient->resend == resend_count) {
743                                 radclient->done = 1;
744                         }
745                         totallost++;
746                         return -1;
747                 }
748
749                 /*
750                  *      We are trying later.
751                  */
752                 radclient->timestamp = now;
753                 radclient->tries++;
754         }
755
756
757         /*
758          *      Send the packet.
759          */
760         if (rad_send(radclient->request, NULL, secret) < 0) {
761                 fprintf(stderr, "radclient: Failed to send packet for ID %d: %s\n",
762                         radclient->request->id, fr_strerror());
763         }
764
765         if (fr_debug_flag > 2) print_hex(radclient->request);
766
767         return 0;
768 }
769
770 /*
771  *      Receive one packet, maybe.
772  */
773 static int recv_one_packet(int wait_time)
774 {
775         fd_set          set;
776         struct timeval  tv;
777         radclient_t     *radclient;
778         RADIUS_PACKET   *reply, **request_p;
779         volatile int max_fd;
780
781         /* And wait for reply, timing out as necessary */
782         FD_ZERO(&set);
783
784         max_fd = fr_packet_list_fd_set(pl, &set);
785         if (max_fd < 0) exit(1); /* no sockets to listen on! */
786
787         if (wait_time <= 0) {
788                 tv.tv_sec = 0;
789         } else {
790                 tv.tv_sec = wait_time;
791         }
792         tv.tv_usec = 0;
793
794         /*
795          *      No packet was received.
796          */
797         if (select(max_fd, &set, NULL, NULL, &tv) <= 0) {
798                 return 0;
799         }
800
801         /*
802          *      Look for the packet.
803          */
804
805         reply = fr_packet_list_recv(pl, &set);
806         if (!reply) {
807                 fprintf(stderr, "radclient: received bad packet: %s\n",
808                         fr_strerror());
809 #ifdef WITH_TCP
810                 /*
811                  *      If the packet is bad, we close the socket.
812                  *      I'm not sure how to do that now, so we just
813                  *      die...
814                  */
815                 if (proto) exit(1);
816 #endif
817                 return -1;      /* bad packet */
818         }
819
820         /*
821          *      udpfromto issues.  We may have bound to "*",
822          *      and we want to find the replies that are sent to
823          *      (say) 127.0.0.1.
824          */
825         reply->dst_ipaddr = client_ipaddr;
826         reply->dst_port = client_port;
827 #ifdef WITH_TCP
828         reply->src_ipaddr = server_ipaddr;
829         reply->src_port = server_port;
830 #endif
831
832         if (fr_debug_flag > 2) print_hex(reply);
833
834         request_p = fr_packet_list_find_byreply(pl, reply);
835         if (!request_p) {
836                 fprintf(stderr, "radclient: received response to request we did not send. (id=%d socket %d)\n", reply->id, reply->sockfd);
837                 rad_free(&reply);
838                 return -1;      /* got reply to packet we didn't send */
839         }
840         radclient = fr_packet2myptr(radclient_t, request, request_p);
841
842         /*
843          *      Fails the signature validation: not a real reply.
844          *      FIXME: Silently drop it and listen for another packet.
845          */
846         if (rad_verify(reply, radclient->request, secret) < 0) {
847                 fr_perror("rad_verify");
848                 totallost++;
849                 goto packet_done; /* shared secret is incorrect */
850         }
851
852         if (print_filename) printf("%s:%d %d\n",
853                                    radclient->filename,
854                                    radclient->packet_number,
855                                    reply->code);
856         deallocate_id(radclient);
857         radclient->reply = reply;
858         reply = NULL;
859
860         /*
861          *      If this fails, we're out of memory.
862          */
863         if (rad_decode(radclient->reply, radclient->request, secret) != 0) {
864                 fr_perror("rad_decode");
865                 totallost++;
866                 goto packet_done;
867         }
868
869         /* libradius debug already prints out the value pairs for us */
870         if (!fr_debug_flag && do_output) {
871                 printf("Received response ID %d, code %d, length = %zd\n",
872                        radclient->reply->id, radclient->reply->code,
873                        radclient->reply->data_len);
874                 vp_printlist(stdout, radclient->reply->vps);
875         }
876
877         if ((radclient->reply->code == PW_AUTHENTICATION_ACK) ||
878             (radclient->reply->code == PW_ACCOUNTING_RESPONSE) ||
879             (radclient->reply->code == PW_COA_ACK) ||
880             (radclient->reply->code == PW_DISCONNECT_ACK)) {
881                 success = 1;            /* have a good response */
882                 totalapp++;
883         } else {
884                 totaldeny++;
885         }
886
887         if (radclient->resend == resend_count) {
888                 radclient->done = 1;
889         }
890
891  packet_done:
892         rad_free(&radclient->reply);
893         rad_free(&reply);       /* may be NULL */
894
895         return 0;
896 }
897
898
899 static int getport(char const *name)
900 {
901         struct  servent         *svp;
902
903         svp = getservbyname (name, "udp");
904         if (!svp) {
905                 return 0;
906         }
907
908         return ntohs(svp->s_port);
909 }
910
911 int main(int argc, char **argv)
912 {
913         char *p;
914         int c;
915         char const *radius_dir = RADDBDIR;
916         char filesecret[256];
917         FILE *fp;
918         int do_summary = 0;
919         int persec = 0;
920         int parallel = 1;
921         radclient_t     *this;
922         int force_af = AF_UNSPEC;
923
924         fr_debug_flag = 0;
925
926 #ifndef NDEBUG
927         fr_fault_setup(getenv("PANIC_ACTION"), argv[0]);
928 #endif
929
930         talloc_set_log_stderr();
931
932         filename_tree = rbtree_create(filename_cmp, NULL, 0);
933         if (!filename_tree) {
934                 fprintf(stderr, "radclient: Out of memory\n");
935                 exit(1);
936         }
937
938         while ((c = getopt(argc, argv, "46c:d:f:Fhi:n:p:qr:sS:t:vx"
939 #ifdef WITH_TCP
940                 "P:"
941 #endif
942                            )) != EOF) switch(c) {
943                 case '4':
944                         force_af = AF_INET;
945                         break;
946                 case '6':
947                         force_af = AF_INET6;
948                         break;
949                 case 'c':
950                         if (!isdigit((int) *optarg))
951                                 usage();
952                         resend_count = atoi(optarg);
953                         break;
954                 case 'd':
955                         radius_dir = optarg;
956                         break;
957                 case 'f':
958                         rbtree_insert(filename_tree, optarg);
959                         break;
960                 case 'F':
961                         print_filename = 1;
962                         break;
963                 case 'i':       /* currently broken */
964                         if (!isdigit((int) *optarg))
965                                 usage();
966                         last_used_id = atoi(optarg);
967                         if ((last_used_id < 0) || (last_used_id > 255)) {
968                                 usage();
969                         }
970                         break;
971
972                 case 'n':
973                         persec = atoi(optarg);
974                         if (persec <= 0) usage();
975                         break;
976
977                         /*
978                          *      Note that sending MANY requests in
979                          *      parallel can over-run the kernel
980                          *      queues, and Linux will happily discard
981                          *      packets.  So even if the server responds,
982                          *      the client may not see the response.
983                          */
984                 case 'p':
985                         parallel = atoi(optarg);
986                         if (parallel <= 0) usage();
987                         break;
988
989 #ifdef WITH_TCP
990                 case 'P':
991                         proto = optarg;
992                         if (strcmp(proto, "tcp") != 0) {
993                                 if (strcmp(proto, "udp") == 0) {
994                                         proto = NULL;
995                                 } else {
996                                         usage();
997                                 }
998                         } else {
999                                 ipproto = IPPROTO_TCP;
1000                         }
1001                         break;
1002
1003 #endif
1004
1005                 case 'q':
1006                         do_output = 0;
1007                         fr_log_fp = NULL; /* no output from you, either! */
1008                         break;
1009                 case 'r':
1010                         if (!isdigit((int) *optarg))
1011                                 usage();
1012                         retries = atoi(optarg);
1013                         if ((retries == 0) || (retries > 1000)) usage();
1014                         break;
1015                 case 's':
1016                         do_summary = 1;
1017                         break;
1018                 case 'S':
1019                        fp = fopen(optarg, "r");
1020                        if (!fp) {
1021                                fprintf(stderr, "radclient: Error opening %s: %s\n",
1022                                        optarg, fr_syserror(errno));
1023                                exit(1);
1024                        }
1025                        if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
1026                                fprintf(stderr, "radclient: Error reading %s: %s\n",
1027                                        optarg, fr_syserror(errno));
1028                                exit(1);
1029                        }
1030                        fclose(fp);
1031
1032                        /* truncate newline */
1033                        p = filesecret + strlen(filesecret) - 1;
1034                        while ((p >= filesecret) &&
1035                               (*p < ' ')) {
1036                                *p = '\0';
1037                                --p;
1038                        }
1039
1040                        if (strlen(filesecret) < 2) {
1041                                fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
1042                                exit(1);
1043                        }
1044                        secret = filesecret;
1045                        break;
1046                 case 't':
1047                         if (!isdigit((int) *optarg))
1048                                 usage();
1049                         timeout = atof(optarg);
1050                         break;
1051                 case 'v':
1052                         printf("%s\n", radclient_version);
1053                         exit(0);
1054                         break;
1055                 case 'x':
1056                         fr_debug_flag++;
1057                         fr_log_fp = stdout;
1058                         break;
1059                 case 'h':
1060                 default:
1061                         usage();
1062                         break;
1063         }
1064         argc -= (optind - 1);
1065         argv += (optind - 1);
1066
1067         if ((argc < 3)  ||
1068             ((secret == NULL) && (argc < 4))) {
1069                 usage();
1070         }
1071
1072         /*
1073          *      Mismatch between the binary and the libraries it depends on
1074          */
1075         if (fr_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) {
1076                 fr_perror("radclient");
1077                 return 1;
1078         }
1079
1080         if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
1081                 fr_perror("radclient");
1082                 return 1;
1083         }
1084
1085         /*
1086          *      Resolve hostname.
1087          */
1088         if (force_af == AF_UNSPEC) force_af = AF_INET;
1089         server_ipaddr.af = force_af;
1090         if (strcmp(argv[1], "-") != 0) {
1091                 char const *hostname = argv[1];
1092                 char const *portname = argv[1];
1093                 char buffer[256];
1094
1095                 if (*argv[1] == '[') { /* IPv6 URL encoded */
1096                         p = strchr(argv[1], ']');
1097                         if ((size_t) (p - argv[1]) >= sizeof(buffer)) {
1098                                 usage();
1099                         }
1100
1101                         memcpy(buffer, argv[1] + 1, p - argv[1] - 1);
1102                         buffer[p - argv[1] - 1] = '\0';
1103
1104                         hostname = buffer;
1105                         portname = p + 1;
1106
1107                 }
1108                 p = strchr(portname, ':');
1109                 if (p && (strchr(p + 1, ':') == NULL)) {
1110                         *p = '\0';
1111                         portname = p + 1;
1112                 } else {
1113                         portname = NULL;
1114                 }
1115
1116                 if (ip_hton(hostname, force_af, &server_ipaddr) < 0) {
1117                         fprintf(stderr, "radclient: Failed to find IP address for host %s: %s\n", hostname, fr_syserror(errno));
1118                         exit(1);
1119                 }
1120
1121                 /*
1122                  *      Strip port from hostname if needed.
1123                  */
1124                 if (portname) server_port = atoi(portname);
1125         }
1126
1127         /*
1128          *      See what kind of request we want to send.
1129          */
1130         if (strcmp(argv[2], "auth") == 0) {
1131                 if (server_port == 0) server_port = getport("radius");
1132                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
1133                 packet_code = PW_AUTHENTICATION_REQUEST;
1134
1135         } else if (strcmp(argv[2], "challenge") == 0) {
1136                 if (server_port == 0) server_port = getport("radius");
1137                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
1138                 packet_code = PW_ACCESS_CHALLENGE;
1139
1140         } else if (strcmp(argv[2], "acct") == 0) {
1141                 if (server_port == 0) server_port = getport("radacct");
1142                 if (server_port == 0) server_port = PW_ACCT_UDP_PORT;
1143                 packet_code = PW_ACCOUNTING_REQUEST;
1144                 do_summary = 0;
1145
1146         } else if (strcmp(argv[2], "status") == 0) {
1147                 if (server_port == 0) server_port = getport("radius");
1148                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
1149                 packet_code = PW_STATUS_SERVER;
1150
1151         } else if (strcmp(argv[2], "disconnect") == 0) {
1152                 if (server_port == 0) server_port = PW_COA_UDP_PORT;
1153                 packet_code = PW_DISCONNECT_REQUEST;
1154
1155         } else if (strcmp(argv[2], "coa") == 0) {
1156                 if (server_port == 0) server_port = PW_COA_UDP_PORT;
1157                 packet_code = PW_COA_REQUEST;
1158
1159         } else if (strcmp(argv[2], "auto") == 0) {
1160                 packet_code = -1;
1161
1162         } else if (isdigit((int) argv[2][0])) {
1163                 if (server_port == 0) server_port = getport("radius");
1164                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
1165                 packet_code = atoi(argv[2]);
1166         } else {
1167                 usage();
1168         }
1169
1170         /*
1171          *      Add the secret.
1172          */
1173         if (argv[3]) secret = argv[3];
1174
1175         /*
1176          *      If no '-f' is specified, we're reading from stdin.
1177          */
1178         if (rbtree_num_elements(filename_tree) == 0) {
1179                 if (!radclient_init("-")) exit(1);
1180         }
1181
1182         /*
1183          *      Walk over the list of filenames, creating the requests.
1184          */
1185         if (rbtree_walk(filename_tree, InOrder, filename_walk, NULL) != 0) {
1186                 fprintf(stderr, "Failed walking over filenames\n");
1187                 exit(1);
1188         }
1189
1190         /*
1191          *      No packets read.  Die.
1192          */
1193         if (!radclient_head) {
1194                 fprintf(stderr, "radclient: Nothing to send.\n");
1195                 exit(1);
1196         }
1197
1198         /*
1199          *      Bind to the first specified IP address and port.
1200          *      This means we ignore later ones.
1201          */
1202         if (radclient_head->request->src_ipaddr.af == AF_UNSPEC) {
1203                 memset(&client_ipaddr, 0, sizeof(client_ipaddr));
1204                 client_ipaddr.af = server_ipaddr.af;
1205                 client_port = 0;
1206         } else {
1207                 client_ipaddr = radclient_head->request->src_ipaddr;
1208                 client_port = radclient_head->request->src_port;
1209         }
1210 #ifdef WITH_TCP
1211         if (proto) {
1212                 sockfd = fr_tcp_client_socket(NULL, &server_ipaddr, server_port);
1213         } else
1214 #endif
1215         sockfd = fr_socket(&client_ipaddr, client_port);
1216         if (sockfd < 0) {
1217                 fprintf(stderr, "radclient: socket: %s\n", fr_strerror());
1218                 exit(1);
1219         }
1220
1221         pl = fr_packet_list_create(1);
1222         if (!pl) {
1223                 fprintf(stderr, "radclient: Out of memory\n");
1224                 exit(1);
1225         }
1226
1227         if (!fr_packet_list_socket_add(pl, sockfd, ipproto, &server_ipaddr,
1228                                        server_port, NULL)) {
1229                 fprintf(stderr, "radclient: Out of memory\n");
1230                 exit(1);
1231         }
1232
1233         /*
1234          *      Walk over the list of packets, sanity checking
1235          *      everything.
1236          */
1237         for (this = radclient_head; this != NULL; this = this->next) {
1238                 this->request->src_ipaddr = client_ipaddr;
1239                 this->request->src_port = client_port;
1240                 if (radclient_sane(this) != 0) {
1241                         exit(1);
1242                 }
1243         }
1244
1245         /*
1246          *      Walk over the packets to send, until
1247          *      we're all done.
1248          *
1249          *      FIXME: This currently busy-loops until it receives
1250          *      all of the packets.  It should really have some sort of
1251          *      send packet, get time to wait, select for time, etc.
1252          *      loop.
1253          */
1254         do {
1255                 int n = parallel;
1256                 radclient_t *next;
1257                 char const *filename = NULL;
1258
1259                 done = 1;
1260                 sleep_time = -1;
1261
1262                 /*
1263                  *      Walk over the packets, sending them.
1264                  */
1265
1266                 for (this = radclient_head; this != NULL; this = next) {
1267                         next = this->next;
1268
1269                         /*
1270                          *      If there's a packet to receive,
1271                          *      receive it, but don't wait for a
1272                          *      packet.
1273                          */
1274                         recv_one_packet(0);
1275
1276                         /*
1277                          *      This packet is done.  Delete it.
1278                          */
1279                         if (this->done) {
1280                                 radclient_free(this);
1281                                 continue;
1282                         }
1283
1284                         /*
1285                          *      Packets from multiple '-f' are sent
1286                          *      in parallel.
1287                          *
1288                          *      Packets from one file are sent in
1289                          *      series, unless '-p' is specified, in
1290                          *      which case N packets from each file
1291                          *      are sent in parallel.
1292                          */
1293                         if (this->filename != filename) {
1294                                 filename = this->filename;
1295                                 n = parallel;
1296                         }
1297
1298                         if (n > 0) {
1299                                 n--;
1300
1301                                 /*
1302                                  *      Send the current packet.
1303                                  */
1304                                 send_one_packet(this);
1305
1306                                 /*
1307                                  *      Wait a little before sending
1308                                  *      the next packet, if told to.
1309                                  */
1310                                 if (persec) {
1311                                         struct timeval tv;
1312
1313                                         /*
1314                                          *      Don't sleep elsewhere.
1315                                          */
1316                                         sleep_time = 0;
1317
1318                                         if (persec == 1) {
1319                                                 tv.tv_sec = 1;
1320                                                 tv.tv_usec = 0;
1321                                         } else {
1322                                                 tv.tv_sec = 0;
1323                                                 tv.tv_usec = 1000000/persec;
1324                                         }
1325
1326                                         /*
1327                                          *      Sleep for milliseconds,
1328                                          *      portably.
1329                                          *
1330                                          *      If we get an error or
1331                                          *      a signal, treat it like
1332                                          *      a normal timeout.
1333                                          */
1334                                         select(0, NULL, NULL, NULL, &tv);
1335                                 }
1336
1337                                 /*
1338                                  *      If we haven't sent this packet
1339                                  *      often enough, we're not done,
1340                                  *      and we shouldn't sleep.
1341                                  */
1342                                 if (this->resend < resend_count) {
1343                                         done = 0;
1344                                         sleep_time = 0;
1345                                 }
1346                         } else { /* haven't sent this packet, we're not done */
1347                                 assert(this->done == 0);
1348                                 assert(this->reply == NULL);
1349                                 done = 0;
1350                         }
1351                 }
1352
1353                 /*
1354                  *      Still have outstanding requests.
1355                  */
1356                 if (fr_packet_list_num_elements(pl) > 0) {
1357                         done = 0;
1358                 } else {
1359                         sleep_time = 0;
1360                 }
1361
1362                 /*
1363                  *      Nothing to do until we receive a request, so
1364                  *      sleep until then.  Once we receive one packet,
1365                  *      we go back, and walk through the whole list again,
1366                  *      sending more packets (if necessary), and updating
1367                  *      the sleep time.
1368                  */
1369                 if (!done && (sleep_time > 0)) {
1370                         recv_one_packet(sleep_time);
1371                 }
1372         } while (!done);
1373
1374         rbtree_free(filename_tree);
1375         fr_packet_list_free(pl);
1376         while (radclient_head) radclient_free(radclient_head);
1377         dict_free();
1378
1379         if (do_summary) {
1380                 printf("\n\t   Total approved auths:  %d\n", totalapp);
1381                 printf("\t     Total denied auths:  %d\n", totaldeny);
1382                 printf("\t       Total lost auths:  %d\n", totallost);
1383         }
1384
1385         if (success) return 0;
1386
1387         return 1;
1388 }