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