Update help messages for 'radclient' to say how to specify a port
[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         int 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
213         while ((c = getopt(argc, argv, "c:d:f:hi:qst:r:S:xv")) != EOF) switch(c) {
214                 case 'c':
215                         if (!isdigit(*optarg)) 
216                                 usage();
217                         count = atoi(optarg);
218                         break;
219                 case 'd':
220                         radius_dir = optarg;
221                         break;
222                 case 'f':
223                         filename = optarg;
224                         break;
225                 case 'q':
226                         do_output = 0;
227                         break;
228                 case 'x':
229                         librad_debug = 1;
230                         break;
231                 case 'r':
232                         if (!isdigit(*optarg)) 
233                                 usage();
234                         retries = atoi(optarg);
235                         break;
236                 case 'i':
237                         if (!isdigit(*optarg)) 
238                                 usage();
239                         id = atoi(optarg);
240                         if ((id < 0) || (id > 255)) {
241                                 usage();
242                         }
243                         break;
244                 case 's':
245                         do_summary = 1;
246                         break;
247                 case 't':
248                         if (!isdigit(*optarg)) 
249                                 usage();
250                         timeout = atof(optarg);
251                         break;
252                 case 'v':
253                         printf("radclient: $Id$ built on " __DATE__ " at " __TIME__ "\n");
254                         exit(0);
255                         break;
256                case 'S':
257                        fp = fopen(optarg, "r");
258                        if (!fp) {
259                                fprintf(stderr, "radclient: Error opening %s: %s\n",
260                                        optarg, strerror(errno));
261                                exit(1);
262                        }
263                        if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
264                                fprintf(stderr, "radclient: Error reading %s: %s\n",
265                                        optarg, strerror(errno));
266                                exit(1);
267                        }
268                        fclose(fp);
269
270                        /* truncate newline */
271                        p = filesecret + strlen(filesecret) - 1;
272                        while ((p >= filesecret) &&
273                               (*p < ' ')) {
274                                *p = '\0';
275                                --p;
276                        }
277
278                        if (strlen(filesecret) < 2) {
279                                fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
280                                exit(1);
281                        }
282                        secret = filesecret;
283                        break;
284                 case 'h':
285                 default:
286                         usage();
287                         break;
288         }
289         argc -= (optind - 1);
290         argv += (optind - 1);
291
292         if ((argc < 3)  ||
293             ((secret == NULL) && (argc < 4))) {
294                 usage();
295         }
296
297         if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
298                 librad_perror("radclient");
299                 return 1;
300         }
301
302         if ((req = rad_alloc(1)) == NULL) {
303                 librad_perror("radclient");
304                 exit(1);
305         }
306
307         req->id = id;
308
309         /*
310          *      Strip port from hostname if needed.
311          */
312         if ((p = strchr(argv[1], ':')) != NULL) {
313                 *p++ = 0;
314                 port = atoi(p);
315         }
316
317         /*
318          *      See what kind of request we want to send.
319          */
320         if (strcmp(argv[2], "auth") == 0) {
321                 if (port == 0) port = getport("radius");
322                 if (port == 0) port = PW_AUTH_UDP_PORT;
323                 req->code = PW_AUTHENTICATION_REQUEST;
324         } else if (strcmp(argv[2], "acct") == 0) {
325                 if (port == 0) port = getport("radacct");
326                 if (port == 0) port = PW_ACCT_UDP_PORT;
327                 req->code = PW_ACCOUNTING_REQUEST;
328                 do_summary = 0;
329         } else if (isdigit(argv[2][0])) {
330                 if (port == 0) port = getport("radius");
331                 if (port == 0) port = PW_AUTH_UDP_PORT;
332                 req->code = atoi(argv[2]);
333         } else {
334                 usage();
335         }
336
337         /*
338          *      Resolve hostname.
339          */
340         req->dst_port = port;
341         req->dst_ipaddr = ip_getaddr(argv[1]);
342         if (req->dst_ipaddr == INADDR_NONE) {
343                 librad_perror("radclient: %s: ", argv[1]);
344                 exit(1);
345         }
346
347         /*
348          *      Add the secret.
349          */
350         if (argv[3]) secret = argv[3];
351
352         /*
353          *      Read valuepairs.
354          *      Maybe read them, from stdin, if there's no
355          *      filename, or if the filename is '-'.
356          */
357         if (filename && (strcmp(filename, "-") != 0)) {
358                 fp = fopen(filename, "r");
359                 if (!fp) {
360                         fprintf(stderr, "radclient: Error opening %s: %s\n",
361                                 filename, strerror(errno));
362                         exit(1);
363                 }
364         } else {
365                 fp = stdin;
366         }
367         
368         /*
369          *      Send request.
370          */
371         if ((req->sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
372                 perror("radclient: socket: ");
373                 exit(1);
374         }
375
376         while(!filedone) {
377                 if(req->vps) pairfree(&req->vps);
378
379                 if ((req->vps = readvp(fp)) == NULL) {
380                         break;
381                 }
382         
383
384                 /*
385                  *      Keep a copy of the the User-Password attribute.
386                  */
387                 if ((vp = pairfind(req->vps, PW_PASSWORD)) != NULL) {
388                         strNcpy(password, (char *)vp->strvalue, sizeof(vp->strvalue));
389                 /*
390                  *      Otherwise keep a copy of the CHAP-Password attribute.
391                  */
392                 } else if ((vp = pairfind(req->vps, PW_CHAP_PASSWORD)) != NULL) {
393                         strNcpy(password, (char *)vp->strvalue, sizeof(vp->strvalue));
394                 } else {
395                         *password = '\0';
396                 }
397         
398                 /*
399                  *      Loop, sending the packet N times.
400                  */
401                 for (loop = 0; loop < count; loop++) {
402                         req->id++;
403         
404                         /*
405                          *      If we've already sent a packet, free up the old
406                          *      one, and ensure that the next packet has a unique
407                          *      ID and authentication vector.
408                          */
409                         if (req->data) {
410                                 free(req->data);
411                                 req->data = NULL;
412                         }
413
414                         librad_md5_calc(req->vector, req->vector,
415                                         sizeof(req->vector));
416                                 
417                         if (*password != '\0') {
418                                 vp = pairfind(req->vps, PW_PASSWORD);
419                                 if (vp) {
420                                         strNcpy((char *)vp->strvalue, password, vp->length + 1);
421                                         vp->length = strlen(password);
422                                         
423                                         rad_pwencode((char *)vp->strvalue,
424                                                      &(vp->length),
425                                                      secret, (char *)req->vector);
426                                 } else if ((vp = pairfind(req->vps, PW_CHAP_PASSWORD)) != NULL) {
427                                         strNcpy((char *)vp->strvalue, password, vp->length + 1);
428                                         vp->length = strlen(password);
429                                         
430                                         rad_chap_encode(req, (char *) vp->strvalue, req->id, vp);
431                                         vp->length = 17;
432                                 }
433                         } /* there WAS a password */
434                         send_packet(req, &rep);
435                         rad_free(&rep);
436                 }
437         }
438         if(do_summary) {
439                 printf("\n\t   Total approved auths:  %d\n", totalapp);
440                 printf("\t     Total denied auths:  %d\n", totaldeny);
441         }
442         return 0;
443 }