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