Made it a little more robust...
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * Copyright 2000  The FreeRADIUS server project
21  * Copyright 2000  Miquel van Smoorenburg <miquels@cistron.nl>
22  * Copyright 2000  Alan DeKok <aland@ox.org>
23  */
24 static const char rcsid[] = "$Id$";
25
26 #include "autoconf.h"
27 #include "libradius.h"
28
29 #include <stdio.h>
30 #include <stdlib.h>
31
32 #if HAVE_UNISTD_H
33 #       include <unistd.h>
34 #endif
35
36 #include <string.h>
37 #include <ctype.h>
38 #include <netdb.h>
39 #include <sys/socket.h>
40
41 #if HAVE_NETINET_IN_H
42 #       include <netinet/in.h>
43 #endif
44
45 #if HAVE_SYS_SELECT_H
46 #       include <sys/select.h>
47 #endif
48
49 #if HAVE_GETOPT_H
50 #       include <getopt.h>
51 #endif
52
53 #include "conf.h"
54 #include "radpaths.h"
55 #include "missing.h"
56
57 static int retries = 10;
58 static float timeout = 3;
59 static const char *secret = NULL;
60 static int do_output = 1;
61 static int do_summary = 0;
62 static int filedone = 0;
63 static int totalapp = 0;
64 static int totaldeny = 0;
65 static char filesecret[256];
66
67 /*
68  *      Read valuepairs from the fp up to End-Of-File.
69  */
70 static VALUE_PAIR *readvp(FILE *fp)
71 {
72         char buf[8192];
73         LRAD_TOKEN last_token;
74         char *p;
75         VALUE_PAIR *vp;
76         VALUE_PAIR *list;
77         int error = 0;
78
79         list = NULL;
80
81         while (!error && fgets(buf, sizeof(buf), fp) != NULL) {
82
83                 p = buf;
84
85                 /* If we get a '\n' by itself, we assume that's the end of that VP */
86                 if((buf[0] == '\n') && (list)) {
87                         return error ? NULL: list;
88                 } 
89                 if((buf[0] == '\n') && (!list))
90                         continue;
91                 if(buf[0] == '#') {
92                         continue;
93                 } else {
94                         do {
95                                 if ((vp = pairread(&p, &last_token)) == NULL) {
96                                         librad_perror("radclient:");
97                                         error = 1;
98                                         break;
99                                 }
100                                 pairadd(&list, vp);
101                         } while (last_token == T_COMMA);
102                 }
103         }
104         filedone = 1;
105         return error ? NULL: list;
106 }
107
108 static void usage(void)
109 {
110         fprintf(stderr, "Usage: radclient [-c count] [-d raddb] [-f file] [-r retries] [-t timeout]\n"
111                         "[-i id] [-qvxS] server[:port] auth|acct|status [<secret>]\n");
112         
113         fprintf(stderr, " -c count    Send each packet 'count' times.\n");
114         fprintf(stderr, " -d raddb    Set dictionary directory.\n");
115         fprintf(stderr, " -f file     Read packets from file, not stdin.\n");
116         fprintf(stderr, " -r retries  If timeout, retry sending the packet 'retries' times.\n");
117         fprintf(stderr, " -t timeout  Wait 'timeout' seconds before retrying.\n");
118         fprintf(stderr, " -i id       Set request id to 'id'.  Values may be 0..255\n");
119         fprintf(stderr, " -S file     read secret from file, not command line.\n");
120         fprintf(stderr, " -q          Do not print anything out.\n");
121         fprintf(stderr, " -s          Print out summary information of auth results.\n");
122         fprintf(stderr, " -v          Show program version information.\n");
123         fprintf(stderr, " -x          Debugging mode.\n");
124
125         exit(1);
126 }
127
128 static int getport(const char *name)
129 {
130         struct  servent         *svp;
131
132         svp = getservbyname (name, "udp");
133         if (!svp) {
134                 return 0;
135         }
136
137         return ntohs(svp->s_port);
138 }
139
140 static int send_packet(RADIUS_PACKET *req, RADIUS_PACKET **rep)
141 {
142         int i;
143         struct timeval  tv;
144
145         for (i = 0; i < retries; i++) {
146                 fd_set          rdfdesc;
147
148                 rad_send(req, NULL, secret);
149
150                 /* And wait for reply, timing out as necessary */
151                 FD_ZERO(&rdfdesc);
152                 FD_SET(req->sockfd, &rdfdesc);
153
154                 tv.tv_sec = (int)timeout;
155                 tv.tv_usec = 1000000 * (timeout - (int)timeout);
156
157                 /* Something's wrong if we don't get exactly one fd. */
158                 if (select(req->sockfd + 1, &rdfdesc, NULL, NULL, &tv) != 1) {
159                         continue;
160                 }
161
162                 *rep = rad_recv(req->sockfd);
163                 if (*rep != NULL) {
164                         /*
165                          *      If we get a response from a machine
166                          *      which we did NOT send a request to,
167                          *      then complain.
168                          */
169                         if (((*rep)->src_ipaddr != req->dst_ipaddr) ||
170                             ((*rep)->src_port != req->dst_port)) {
171                                 char src[64], dst[64];
172
173                                 ip_ntoa(src, (*rep)->src_ipaddr);
174                                 ip_ntoa(dst, req->src_ipaddr);
175                                 fprintf(stderr, "radclient: ERROR: Sent request to host %s, got response from host %s\n!", dst, src);
176                                 exit(1);
177                         }
178                         break;
179                 } else {        /* NULL: couldn't receive the packet */
180                         librad_perror("radclient:");
181                         exit(1);
182                 }
183         }
184
185         /* No response or no data read (?) */
186         if (i == retries) {
187                 fprintf(stderr, "radclient: no response from server\n");
188                 exit(1);
189         }
190
191         if (rad_decode(*rep, req, secret) != 0) {
192                 librad_perror("rad_decode");
193                 exit(1);
194         }
195
196         /* libradius debug already prints out the value pairs for us */
197         if (!librad_debug && do_output) {
198                 printf("Received response ID %d, code %d, length = %d\n",
199                                 (*rep)->id, (*rep)->code, (*rep)->data_len);
200                 vp_printlist(stdout, (*rep)->vps);
201         }
202         if((*rep)->code == PW_AUTHENTICATION_ACK) {
203                 totalapp++;
204         } else {
205                 totaldeny++;
206         }
207
208         return 0;
209 }
210
211 int main(int argc, char **argv)
212 {
213         RADIUS_PACKET *req;
214         RADIUS_PACKET *rep = NULL;
215         char *p;
216         int c;
217         int port = 0;
218         const char *radius_dir = RADDBDIR;
219         char *filename = NULL;
220         FILE *fp;
221         int count = 1;
222         int loop;
223         char password[256];
224         VALUE_PAIR *vp;
225         int id;
226
227         id = ((int)getpid() & 0xff);
228         librad_debug = 0;
229
230         while ((c = getopt(argc, argv, "c:d:f:hi:qst:r:S:xv")) != EOF) switch(c) {
231                 case 'c':
232                         if (!isdigit((int) *optarg)) 
233                                 usage();
234                         count = atoi(optarg);
235                         break;
236                 case 'd':
237                         radius_dir = optarg;
238                         break;
239                 case 'f':
240                         filename = optarg;
241                         break;
242                 case 'q':
243                         do_output = 0;
244                         break;
245                 case 'x':
246                         librad_debug++;
247                         break;
248                 case 'r':
249                         if (!isdigit((int) *optarg)) 
250                                 usage();
251                         retries = atoi(optarg);
252                         break;
253                 case 'i':
254                         if (!isdigit((int) *optarg)) 
255                                 usage();
256                         id = atoi(optarg);
257                         if ((id < 0) || (id > 255)) {
258                                 usage();
259                         }
260                         break;
261                 case 's':
262                         do_summary = 1;
263                         break;
264                 case 't':
265                         if (!isdigit((int) *optarg)) 
266                                 usage();
267                         timeout = atof(optarg);
268                         break;
269                 case 'v':
270                         printf("radclient: $Id$ built on " __DATE__ " at " __TIME__ "\n");
271                         exit(0);
272                         break;
273                case 'S':
274                        fp = fopen(optarg, "r");
275                        if (!fp) {
276                                fprintf(stderr, "radclient: Error opening %s: %s\n",
277                                        optarg, strerror(errno));
278                                exit(1);
279                        }
280                        if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
281                                fprintf(stderr, "radclient: Error reading %s: %s\n",
282                                        optarg, strerror(errno));
283                                exit(1);
284                        }
285                        fclose(fp);
286
287                        /* truncate newline */
288                        p = filesecret + strlen(filesecret) - 1;
289                        while ((p >= filesecret) &&
290                               (*p < ' ')) {
291                                *p = '\0';
292                                --p;
293                        }
294
295                        if (strlen(filesecret) < 2) {
296                                fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
297                                exit(1);
298                        }
299                        secret = filesecret;
300                        break;
301                 case 'h':
302                 default:
303                         usage();
304                         break;
305         }
306         argc -= (optind - 1);
307         argv += (optind - 1);
308
309         if ((argc < 3)  ||
310             ((secret == NULL) && (argc < 4))) {
311                 usage();
312         }
313
314         if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
315                 librad_perror("radclient");
316                 return 1;
317         }
318
319         if ((req = rad_alloc(1)) == NULL) {
320                 librad_perror("radclient");
321                 exit(1);
322         }
323
324         req->id = id;
325
326         /*
327          *      Strip port from hostname if needed.
328          */
329         if ((p = strchr(argv[1], ':')) != NULL) {
330                 *p++ = 0;
331                 port = atoi(p);
332         }
333
334         /*
335          *      See what kind of request we want to send.
336          */
337         if (strcmp(argv[2], "auth") == 0) {
338                 if (port == 0) port = getport("radius");
339                 if (port == 0) port = PW_AUTH_UDP_PORT;
340                 req->code = PW_AUTHENTICATION_REQUEST;
341         } else if (strcmp(argv[2], "acct") == 0) {
342                 if (port == 0) port = getport("radacct");
343                 if (port == 0) port = PW_ACCT_UDP_PORT;
344                 req->code = PW_ACCOUNTING_REQUEST;
345                 do_summary = 0;
346         } else if (strcmp(argv[2], "status") == 0) {
347                 if (port == 0) port = getport("radius");
348                 if (port == 0) port = PW_AUTH_UDP_PORT;
349                 req->code = PW_STATUS_SERVER;
350         } else if (isdigit((int) argv[2][0])) {
351                 if (port == 0) port = getport("radius");
352                 if (port == 0) port = PW_AUTH_UDP_PORT;
353                 req->code = atoi(argv[2]);
354         } else {
355                 usage();
356         }
357
358         /*
359          *      Resolve hostname.
360          */
361         req->dst_port = port;
362         req->dst_ipaddr = ip_getaddr(argv[1]);
363         if (req->dst_ipaddr == INADDR_NONE) {
364                 librad_perror("radclient: %s: ", argv[1]);
365                 exit(1);
366         }
367
368         /*
369          *      Add the secret.
370          */
371         if (argv[3]) secret = argv[3];
372
373         /*
374          *      Read valuepairs.
375          *      Maybe read them, from stdin, if there's no
376          *      filename, or if the filename is '-'.
377          */
378         if (filename && (strcmp(filename, "-") != 0)) {
379                 fp = fopen(filename, "r");
380                 if (!fp) {
381                         fprintf(stderr, "radclient: Error opening %s: %s\n",
382                                 filename, strerror(errno));
383                         exit(1);
384                 }
385         } else {
386                 fp = stdin;
387         }
388         
389         /*
390          *      Send request.
391          */
392         if ((req->sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
393                 perror("radclient: socket: ");
394                 exit(1);
395         }
396
397         while(!filedone) {
398                 if(req->vps) pairfree(&req->vps);
399
400                 if ((req->vps = readvp(fp)) == NULL) {
401                         break;
402                 }
403         
404
405                 /*
406                  *      Keep a copy of the the User-Password attribute.
407                  */
408                 if ((vp = pairfind(req->vps, PW_PASSWORD)) != NULL) {
409                         strNcpy(password, (char *)vp->strvalue, sizeof(vp->strvalue));
410                 /*
411                  *      Otherwise keep a copy of the CHAP-Password attribute.
412                  */
413                 } else if ((vp = pairfind(req->vps, PW_CHAP_PASSWORD)) != NULL) {
414                         strNcpy(password, (char *)vp->strvalue, sizeof(vp->strvalue));
415                 } else {
416                         *password = '\0';
417                 }
418         
419                 /*
420                  *  Fix up Digest-Attributes issues
421                  */
422                 for (vp = req->vps; vp != NULL; vp = vp->next) {
423                   switch (vp->attribute) {
424                   default:
425                     break;
426
427                   case PW_DIGEST_REALM:
428                   case PW_DIGEST_NONCE:
429                   case PW_DIGEST_METHOD:
430                   case PW_DIGEST_URI:
431                   case PW_DIGEST_QOP:
432                   case PW_DIGEST_ALGORITHM:
433                   case PW_DIGEST_BODY_DIGEST:
434                   case PW_DIGEST_CNONCE:
435                   case PW_DIGEST_NONCE_COUNT:
436                   case PW_DIGEST_USER_NAME:
437                     /* overlapping! */
438                     memmove(&vp->strvalue[2], &vp->strvalue[0], vp->length);
439                     vp->strvalue[0] = vp->attribute - PW_DIGEST_REALM + 1;
440                     vp->length += 2;
441                     vp->strvalue[1] = vp->length;
442                     vp->attribute = PW_DIGEST_ATTRIBUTES;
443                     break;
444                   }
445                 }
446
447                 /*
448                  *      Loop, sending the packet N times.
449                  */
450                 for (loop = 0; loop < count; loop++) {
451                         req->id++;
452         
453                         /*
454                          *      If we've already sent a packet, free up the old
455                          *      one, and ensure that the next packet has a unique
456                          *      ID and authentication vector.
457                          */
458                         if (req->data) {
459                                 free(req->data);
460                                 req->data = NULL;
461                         }
462
463                         librad_md5_calc(req->vector, req->vector,
464                                         sizeof(req->vector));
465                                 
466                         if (*password != '\0') {
467                                 if ((vp = pairfind(req->vps, PW_CHAP_PASSWORD)) != NULL) {
468                                         strNcpy((char *)vp->strvalue, password, strlen(password) + 1);
469                                         vp->length = strlen(password);
470                                         
471                                         rad_chap_encode(req, (char *) vp->strvalue, req->id, vp);
472                                         vp->length = 17;
473                                 }
474                         } /* there WAS a password */
475                         send_packet(req, &rep);
476                         rad_free(&rep);
477                 }
478         }
479         if(do_summary) {
480                 printf("\n\t   Total approved auths:  %d\n", totalapp);
481                 printf("\t     Total denied auths:  %d\n", totaldeny);
482         }
483         return 0;
484 }