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