Be a little more selective about RADIUS replies. If we get a reply
[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] auth|acct|status [<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 'retries' 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                         /*
163                          *      If we get a response from a machine
164                          *      which we did NOT send a request to,
165                          *      then complain.
166                          */
167                         if (((*rep)->src_ipaddr != req->dst_ipaddr) ||
168                             ((*rep)->src_port != req->dst_port)) {
169                                 char src[64], dst[64];
170
171                                 ip_ntoa(src, (*rep)->src_ipaddr);
172                                 ip_ntoa(dst, req->src_ipaddr);
173                                 fprintf(stderr, "radclient: ERROR: Sent request to host %s, got response from host %s\n!", dst, src);
174                                 exit(1);
175                         }
176                         break;
177                 } else {        /* NULL: couldn't receive the packet */
178                         librad_perror("radclient:");
179                         exit(1);
180                 }
181         }
182
183         /* No response or no data read (?) */
184         if (i == retries) {
185                 fprintf(stderr, "radclient: no response from server\n");
186                 exit(1);
187         }
188
189         if (rad_decode(*rep, req, secret) != 0) {
190                 librad_perror("rad_decode");
191                 exit(1);
192         }
193
194         /* libradius debug already prints out the value pairs for us */
195         if (!librad_debug && do_output) {
196                 printf("Received response ID %d, code %d, length = %d\n",
197                                 (*rep)->id, (*rep)->code, (*rep)->data_len);
198                 vp_printlist(stdout, (*rep)->vps);
199         }
200         if((*rep)->code == PW_AUTHENTICATION_ACK) {
201                 totalapp++;
202         } else {
203                 totaldeny++;
204         }
205
206         return 0;
207 }
208
209 int main(int argc, char **argv)
210 {
211         RADIUS_PACKET *req;
212         RADIUS_PACKET *rep = NULL;
213         char *p;
214         int c;
215         int port = 0;
216         const char *radius_dir = RADDBDIR;
217         char *filename = NULL;
218         FILE *fp;
219         int count = 1;
220         int loop;
221         char password[256];
222         VALUE_PAIR *vp;
223         int id;
224
225         id = ((int)getpid() & 0xff);
226         librad_debug = 0;
227
228         while ((c = getopt(argc, argv, "c:d:f:hi:qst:r:S:xv")) != EOF) switch(c) {
229                 case 'c':
230                         if (!isdigit((int) *optarg)) 
231                                 usage();
232                         count = atoi(optarg);
233                         break;
234                 case 'd':
235                         radius_dir = optarg;
236                         break;
237                 case 'f':
238                         filename = optarg;
239                         break;
240                 case 'q':
241                         do_output = 0;
242                         break;
243                 case 'x':
244                         librad_debug++;
245                         break;
246                 case 'r':
247                         if (!isdigit((int) *optarg)) 
248                                 usage();
249                         retries = atoi(optarg);
250                         break;
251                 case 'i':
252                         if (!isdigit((int) *optarg)) 
253                                 usage();
254                         id = atoi(optarg);
255                         if ((id < 0) || (id > 255)) {
256                                 usage();
257                         }
258                         break;
259                 case 's':
260                         do_summary = 1;
261                         break;
262                 case 't':
263                         if (!isdigit((int) *optarg)) 
264                                 usage();
265                         timeout = atof(optarg);
266                         break;
267                 case 'v':
268                         printf("radclient: $Id$ built on " __DATE__ " at " __TIME__ "\n");
269                         exit(0);
270                         break;
271                case 'S':
272                        fp = fopen(optarg, "r");
273                        if (!fp) {
274                                fprintf(stderr, "radclient: Error opening %s: %s\n",
275                                        optarg, strerror(errno));
276                                exit(1);
277                        }
278                        if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
279                                fprintf(stderr, "radclient: Error reading %s: %s\n",
280                                        optarg, strerror(errno));
281                                exit(1);
282                        }
283                        fclose(fp);
284
285                        /* truncate newline */
286                        p = filesecret + strlen(filesecret) - 1;
287                        while ((p >= filesecret) &&
288                               (*p < ' ')) {
289                                *p = '\0';
290                                --p;
291                        }
292
293                        if (strlen(filesecret) < 2) {
294                                fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
295                                exit(1);
296                        }
297                        secret = filesecret;
298                        break;
299                 case 'h':
300                 default:
301                         usage();
302                         break;
303         }
304         argc -= (optind - 1);
305         argv += (optind - 1);
306
307         if ((argc < 3)  ||
308             ((secret == NULL) && (argc < 4))) {
309                 usage();
310         }
311
312         if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
313                 librad_perror("radclient");
314                 return 1;
315         }
316
317         if ((req = rad_alloc(1)) == NULL) {
318                 librad_perror("radclient");
319                 exit(1);
320         }
321
322         req->id = id;
323
324         /*
325          *      Strip port from hostname if needed.
326          */
327         if ((p = strchr(argv[1], ':')) != NULL) {
328                 *p++ = 0;
329                 port = atoi(p);
330         }
331
332         /*
333          *      See what kind of request we want to send.
334          */
335         if (strcmp(argv[2], "auth") == 0) {
336                 if (port == 0) port = getport("radius");
337                 if (port == 0) port = PW_AUTH_UDP_PORT;
338                 req->code = PW_AUTHENTICATION_REQUEST;
339         } else if (strcmp(argv[2], "acct") == 0) {
340                 if (port == 0) port = getport("radacct");
341                 if (port == 0) port = PW_ACCT_UDP_PORT;
342                 req->code = PW_ACCOUNTING_REQUEST;
343                 do_summary = 0;
344         } else if (strcmp(argv[2], "status") == 0) {
345                 if (port == 0) port = getport("radius");
346                 if (port == 0) port = PW_AUTH_UDP_PORT;
347                 req->code = PW_STATUS_SERVER;
348         } else if (isdigit((int) argv[2][0])) {
349                 if (port == 0) port = getport("radius");
350                 if (port == 0) port = PW_AUTH_UDP_PORT;
351                 req->code = atoi(argv[2]);
352         } else {
353                 usage();
354         }
355
356         /*
357          *      Resolve hostname.
358          */
359         req->dst_port = port;
360         req->dst_ipaddr = ip_getaddr(argv[1]);
361         if (req->dst_ipaddr == INADDR_NONE) {
362                 librad_perror("radclient: %s: ", argv[1]);
363                 exit(1);
364         }
365
366         /*
367          *      Add the secret.
368          */
369         if (argv[3]) secret = argv[3];
370
371         /*
372          *      Read valuepairs.
373          *      Maybe read them, from stdin, if there's no
374          *      filename, or if the filename is '-'.
375          */
376         if (filename && (strcmp(filename, "-") != 0)) {
377                 fp = fopen(filename, "r");
378                 if (!fp) {
379                         fprintf(stderr, "radclient: Error opening %s: %s\n",
380                                 filename, strerror(errno));
381                         exit(1);
382                 }
383         } else {
384                 fp = stdin;
385         }
386         
387         /*
388          *      Send request.
389          */
390         if ((req->sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
391                 perror("radclient: socket: ");
392                 exit(1);
393         }
394
395         while(!filedone) {
396                 if(req->vps) pairfree(&req->vps);
397
398                 if ((req->vps = readvp(fp)) == NULL) {
399                         break;
400                 }
401         
402
403                 /*
404                  *      Keep a copy of the the User-Password attribute.
405                  */
406                 if ((vp = pairfind(req->vps, PW_PASSWORD)) != NULL) {
407                         strNcpy(password, (char *)vp->strvalue, sizeof(vp->strvalue));
408                 /*
409                  *      Otherwise keep a copy of the CHAP-Password attribute.
410                  */
411                 } else if ((vp = pairfind(req->vps, PW_CHAP_PASSWORD)) != NULL) {
412                         strNcpy(password, (char *)vp->strvalue, sizeof(vp->strvalue));
413                 } else {
414                         *password = '\0';
415                 }
416         
417                 /*
418                  *  Fix up Digest-Attributes issues
419                  */
420                 for (vp = req->vps; vp != NULL; vp = vp->next) {
421                   switch (vp->attribute) {
422                   default:
423                     break;
424
425                   case PW_DIGEST_REALM:
426                   case PW_DIGEST_NONCE:
427                   case PW_DIGEST_METHOD:
428                   case PW_DIGEST_URI:
429                   case PW_DIGEST_QOP:
430                   case PW_DIGEST_ALGORITHM:
431                   case PW_DIGEST_BODY_DIGEST:
432                   case PW_DIGEST_CNONCE:
433                   case PW_DIGEST_NONCE_COUNT:
434                   case PW_DIGEST_USER_NAME:
435                     /* overlapping! */
436                     memmove(&vp->strvalue[2], &vp->strvalue[0], vp->length);
437                     vp->strvalue[0] = vp->attribute - PW_DIGEST_REALM + 1;
438                     vp->length += 2;
439                     vp->strvalue[1] = vp->length;
440                     vp->attribute = PW_DIGEST_ATTRIBUTES;
441                     break;
442                   }
443                 }
444
445                 /*
446                  *      Loop, sending the packet N times.
447                  */
448                 for (loop = 0; loop < count; loop++) {
449                         req->id++;
450         
451                         /*
452                          *      If we've already sent a packet, free up the old
453                          *      one, and ensure that the next packet has a unique
454                          *      ID and authentication vector.
455                          */
456                         if (req->data) {
457                                 free(req->data);
458                                 req->data = NULL;
459                         }
460
461                         librad_md5_calc(req->vector, req->vector,
462                                         sizeof(req->vector));
463                                 
464                         if (*password != '\0') {
465                                 if ((vp = pairfind(req->vps, PW_CHAP_PASSWORD)) != NULL) {
466                                         strNcpy((char *)vp->strvalue, password, strlen(password) + 1);
467                                         vp->length = strlen(password);
468                                         
469                                         rad_chap_encode(req, (char *) vp->strvalue, req->id, vp);
470                                         vp->length = 17;
471                                 }
472                         } /* there WAS a password */
473                         send_packet(req, &rep);
474                         rad_free(&rep);
475                 }
476         }
477         if(do_summary) {
478                 printf("\n\t   Total approved auths:  %d\n", totalapp);
479                 printf("\t     Total denied auths:  %d\n", totaldeny);
480         }
481         return 0;
482 }