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