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