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