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