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