port fix from branch_1_1
[freeradius.git] / src / modules / rlm_eap / radeapclient.c
1 /*
2  * radeapclient.c       EAP specific 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2000,2006  The FreeRADIUS server project
21  * Copyright 2000  Miquel van Smoorenburg <miquels@cistron.nl>
22  * Copyright 2000  Alan DeKok <aland@ox.org>
23  */
24
25 #include <freeradius-devel/ident.h>
26 RCSID("$Id$")
27
28 #include <freeradius-devel/autoconf.h>
29
30 #include <stdio.h>
31 #include <stdlib.h>
32
33 #if HAVE_UNISTD_H
34 #       include <unistd.h>
35 #endif
36
37 #include <string.h>
38 #include <ctype.h>
39 #include <netdb.h>
40 #include <sys/socket.h>
41
42 #if HAVE_NETINET_IN_H
43 #       include <netinet/in.h>
44 #endif
45
46 #if HAVE_SYS_SELECT_H
47 #       include <sys/select.h>
48 #endif
49
50 #if HAVE_GETOPT_H
51 #       include <getopt.h>
52 #endif
53
54 #include <freeradius-devel/conf.h>
55 #include <freeradius-devel/radpaths.h>
56 #include <freeradius-devel/missing.h>
57 #include <freeradius-devel/md5.h>
58
59 #include "eap_types.h"
60 #include "eap_sim.h"
61
62 extern int sha1_data_problems;
63
64 static int retries = 10;
65 static float timeout = 3;
66 static const char *secret = NULL;
67 static int do_output = 1;
68 static int do_summary = 0;
69 static int filedone = 0;
70 static int totalapp = 0;
71 static int totaldeny = 0;
72 static char filesecret[256];
73 const char *radius_dir = RADDBDIR;
74 const char *progname = "radeapclient";
75 /* lrad_randctx randctx; */
76
77
78 radlog_dest_t radlog_dest = RADLOG_STDERR;
79 const char *radlog_dir = NULL;
80 int debug_flag = 0;
81 struct main_config_t mainconfig;
82 char password[256];
83
84 struct eapsim_keys eapsim_mk;
85
86 static void NEVER_RETURNS usage(void)
87 {
88         fprintf(stderr, "Usage: radeapclient [options] server[:port] <command> [<secret>]\n");
89
90         fprintf(stderr, "  <command>    One of auth, acct, status, or disconnect.\n");
91         fprintf(stderr, "  -c count    Send each packet 'count' times.\n");
92         fprintf(stderr, "  -d raddb    Set dictionary directory.\n");
93         fprintf(stderr, "  -f file     Read packets from file, not stdin.\n");
94         fprintf(stderr, "  -r retries  If timeout, retry sending the packet 'retries' times.\n");
95         fprintf(stderr, "  -t timeout  Wait 'timeout' seconds before retrying (may be a floating point number).\n");
96         fprintf(stderr, "  -i id       Set request id to 'id'.  Values may be 0..255\n");
97         fprintf(stderr, "  -S file     read secret from file, not command line.\n");
98         fprintf(stderr, "  -q          Do not print anything out.\n");
99         fprintf(stderr, "  -s          Print out summary information of auth results.\n");
100         fprintf(stderr, "  -v          Show program version information.\n");
101         fprintf(stderr, "  -x          Debugging mode.\n");
102
103         exit(1);
104 }
105
106 int radlog(int lvl, const char *msg, ...)
107 {
108         va_list ap;
109         int r;
110
111         r = lvl; /* shut up compiler */
112
113         va_start(ap, msg);
114         r = vfprintf(stderr, msg, ap);
115         va_end(ap);
116         fputc('\n', stderr);
117
118         return r;
119 }
120
121 int log_debug(const char *msg, ...)
122 {
123         va_list ap;
124         int r;
125
126         va_start(ap, msg);
127         r = vfprintf(stderr, msg, ap);
128         va_end(ap);
129         fputc('\n', stderr);
130
131         return r;
132 }
133
134 static int getport(const char *name)
135 {
136         struct  servent         *svp;
137
138         svp = getservbyname (name, "udp");
139         if (!svp) {
140                 return 0;
141         }
142
143         return ntohs(svp->s_port);
144 }
145
146 static int send_packet(RADIUS_PACKET *req, RADIUS_PACKET **rep)
147 {
148         int i;
149         struct timeval  tv;
150
151         for (i = 0; i < retries; i++) {
152                 fd_set          rdfdesc;
153
154                 rad_send(req, NULL, secret);
155
156                 /* And wait for reply, timing out as necessary */
157                 FD_ZERO(&rdfdesc);
158                 FD_SET(req->sockfd, &rdfdesc);
159
160                 tv.tv_sec = (int)timeout;
161                 tv.tv_usec = 1000000 * (timeout - (int) timeout);
162
163                 /* Something's wrong if we don't get exactly one fd. */
164                 if (select(req->sockfd + 1, &rdfdesc, NULL, NULL, &tv) != 1) {
165                         continue;
166                 }
167
168                 *rep = rad_recv(req->sockfd);
169                 if (*rep != NULL) {
170                         /*
171                          *      If we get a response from a machine
172                          *      which we did NOT send a request to,
173                          *      then complain.
174                          */
175                         if (((*rep)->src_ipaddr.af != req->dst_ipaddr.af) ||
176                             (memcmp(&(*rep)->src_ipaddr.ipaddr,
177                                     &req->dst_ipaddr.ipaddr,
178                                     ((req->dst_ipaddr.af == AF_INET ? /* AF_INET6? */
179                                       sizeof(req->dst_ipaddr.ipaddr.ip4addr) : /* FIXME: AF_INET6 */
180                                       sizeof(req->dst_ipaddr.ipaddr.ip6addr)))) != 0) ||
181                             ((*rep)->src_port != req->dst_port)) {
182                                 char src[128], dst[128];
183
184                                 ip_ntoh(&(*rep)->src_ipaddr, src, sizeof(src));
185                                 ip_ntoh(&req->dst_ipaddr, dst, sizeof(dst));
186                                 fprintf(stderr, "radclient: ERROR: Sent request to host %s port %d, got response from host %s port %d\n!",
187                                         dst, req->dst_port,
188                                         src, (*rep)->src_port);
189                                 exit(1);
190                         }
191                         break;
192                 } else {        /* NULL: couldn't receive the packet */
193                         librad_perror("radclient:");
194                         exit(1);
195                 }
196         }
197
198         /* No response or no data read (?) */
199         if (i == retries) {
200                 fprintf(stderr, "radclient: no response from server\n");
201                 exit(1);
202         }
203
204         /*
205          *      FIXME: Discard the packet & listen for another.
206          *
207          *      Hmm... we should really be using eapol_test, which does
208          *      a lot more than radeapclient.
209          */
210         if (rad_verify(*rep, req, secret) != 0) {
211                 librad_perror("rad_verify");
212                 exit(1);
213         }
214
215         if (rad_decode(*rep, req, secret) != 0) {
216                 librad_perror("rad_decode");
217                 exit(1);
218         }
219
220         /* libradius debug already prints out the value pairs for us */
221         if (!librad_debug && do_output) {
222                 printf("Received response ID %d, code %d, length = %d\n",
223                                 (*rep)->id, (*rep)->code, (*rep)->data_len);
224                 vp_printlist(stdout, (*rep)->vps);
225         }
226         if((*rep)->code == PW_AUTHENTICATION_ACK) {
227                 totalapp++;
228         } else {
229                 totaldeny++;
230         }
231
232         return 0;
233 }
234
235 static void cleanresp(RADIUS_PACKET *resp)
236 {
237         VALUE_PAIR *vpnext, *vp, **last;
238
239
240         /*
241          * maybe should just copy things we care about, or keep
242          * a copy of the original input and start from there again?
243          */
244         pairdelete(&resp->vps, PW_EAP_MESSAGE);
245         pairdelete(&resp->vps, ATTRIBUTE_EAP_BASE+PW_EAP_IDENTITY);
246
247         last = &resp->vps;
248         for(vp = *last; vp != NULL; vp = vpnext)
249         {
250                 vpnext = vp->next;
251
252                 if((vp->attribute > ATTRIBUTE_EAP_BASE &&
253                     vp->attribute <= ATTRIBUTE_EAP_BASE+256) ||
254                    (vp->attribute > ATTRIBUTE_EAP_SIM_BASE &&
255                     vp->attribute <= ATTRIBUTE_EAP_SIM_BASE+256))
256                 {
257                         *last = vpnext;
258                         pairbasicfree(vp);
259                 } else {
260                         last = &vp->next;
261                 }
262         }
263 }
264
265 /*
266  * we got an EAP-Request/Sim/Start message in a legal state.
267  *
268  * pick a supported version, put it into the reply, and insert a nonce.
269  */
270 static int process_eap_start(RADIUS_PACKET *req,
271                              RADIUS_PACKET *rep)
272 {
273         VALUE_PAIR *vp, *newvp;
274         VALUE_PAIR *anyidreq_vp, *fullauthidreq_vp, *permanentidreq_vp;
275         uint16_t *versions, selectedversion;
276         unsigned int i,versioncount;
277
278         /* form new response clear of any EAP stuff */
279         cleanresp(rep);
280
281         if((vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_VERSION_LIST)) == NULL) {
282                 fprintf(stderr, "illegal start message has no VERSION_LIST\n");
283                 return 0;
284         }
285
286         versions = (uint16_t *)vp->vp_strvalue;
287
288         /* verify that the attribute length is big enough for a length field */
289         if(vp->length < 4)
290         {
291                 fprintf(stderr, "start message has illegal VERSION_LIST. Too short: %d\n", vp->length);
292                 return 0;
293         }
294
295         versioncount = ntohs(versions[0])/2;
296         /* verify that the attribute length is big enough for the given number
297          * of versions present.
298          */
299         if((unsigned)vp->length <= (versioncount*2 + 2))
300         {
301                 fprintf(stderr, "start message is too short. Claimed %d versions does not fit in %d bytes\n", versioncount, vp->length);
302                 return 0;
303         }
304
305         /*
306          * record the versionlist for the MK calculation.
307          */
308         eapsim_mk.versionlistlen = versioncount*2;
309         memcpy(eapsim_mk.versionlist, (unsigned char *)(versions+1),
310                eapsim_mk.versionlistlen);
311
312         /* walk the version list, and pick the one we support, which
313          * at present, is 1, EAP_SIM_VERSION.
314          */
315         selectedversion=0;
316         for(i=0; i < versioncount; i++)
317         {
318                 if(ntohs(versions[i+1]) == EAP_SIM_VERSION)
319                 {
320                         selectedversion=EAP_SIM_VERSION;
321                         break;
322                 }
323         }
324         if(selectedversion == 0)
325         {
326                 fprintf(stderr, "eap-sim start message. No compatible version found. We need %d\n", EAP_SIM_VERSION);
327                 for(i=0; i < versioncount; i++)
328                 {
329                         fprintf(stderr, "\tfound version %d\n",
330                                 ntohs(versions[i+1]));
331                 }
332         }
333
334         /*
335          * now make sure that we have only FULLAUTH_ID_REQ.
336          * I think that it actually might not matter - we can answer in
337          * anyway we like, but it is illegal to have more than one
338          * present.
339          */
340         anyidreq_vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_ANY_ID_REQ);
341         fullauthidreq_vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_FULLAUTH_ID_REQ);
342         permanentidreq_vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_PERMANENT_ID_REQ);
343
344         if(fullauthidreq_vp == NULL ||
345            anyidreq_vp != NULL ||
346            permanentidreq_vp != NULL) {
347                 fprintf(stderr, "start message has %sanyidreq, %sfullauthid and %spermanentid. Illegal combination.\n",
348                         (anyidreq_vp != NULL ? "a " : "no "),
349                         (fullauthidreq_vp != NULL ? "a " : "no "),
350                         (permanentidreq_vp != NULL ? "a " : "no "));
351                 return 0;
352         }
353
354         /* okay, we have just any_id_req there, so fill in response */
355
356         /* mark the subtype as being EAP-SIM/Response/Start */
357         newvp = paircreate(ATTRIBUTE_EAP_SIM_SUBTYPE, PW_TYPE_INTEGER);
358         newvp->lvalue = eapsim_start;
359         pairreplace(&(rep->vps), newvp);
360
361         /* insert selected version into response. */
362         newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_SELECTED_VERSION,
363                            PW_TYPE_OCTETS);
364         versions = (uint16_t *)newvp->vp_strvalue;
365         versions[0] = htons(selectedversion);
366         newvp->length = 2;
367         pairreplace(&(rep->vps), newvp);
368
369         /* record the selected version */
370         memcpy(eapsim_mk.versionselect, (unsigned char *)versions, 2);
371
372         vp = newvp = NULL;
373
374         {
375                 uint32_t nonce[4];
376                 /*
377                  * insert a nonce_mt that we make up.
378                  */
379                 newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_NONCE_MT,
380                                    PW_TYPE_OCTETS);
381                 newvp->vp_octets[0]=0;
382                 newvp->vp_octets[1]=0;
383                 newvp->length = 18;  /* 16 bytes of nonce + padding */
384
385                 nonce[0]=lrad_rand();
386                 nonce[1]=lrad_rand();
387                 nonce[2]=lrad_rand();
388                 nonce[3]=lrad_rand();
389                 memcpy(&newvp->vp_octets[2], nonce, 16);
390                 pairreplace(&(rep->vps), newvp);
391
392                 /* also keep a copy of the nonce! */
393                 memcpy(eapsim_mk.nonce_mt, nonce, 16);
394         }
395
396         {
397                 uint16_t *pidlen, idlen;
398
399                 /*
400                  * insert the identity here.
401                  */
402                 vp = pairfind(rep->vps, PW_USER_NAME);
403                 if(vp == NULL)
404                 {
405                         fprintf(stderr, "eap-sim: We need to have a User-Name attribute!\n");
406                         return 0;
407                 }
408                 newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_IDENTITY,
409                                    PW_TYPE_OCTETS);
410                 idlen = strlen(vp->vp_strvalue);
411                 pidlen = (uint16_t *)newvp->vp_strvalue;
412                 *pidlen = htons(idlen);
413                 newvp->length = idlen + 2;
414
415                 memcpy(&newvp->vp_strvalue[2], vp->vp_strvalue, idlen);
416                 pairreplace(&(rep->vps), newvp);
417
418                 /* record it */
419                 memcpy(eapsim_mk.identity, vp->vp_strvalue, idlen);
420                 eapsim_mk.identitylen = idlen;
421         }
422
423         return 1;
424 }
425
426 /*
427  * we got an EAP-Request/Sim/Challenge message in a legal state.
428  *
429  * use the RAND challenge to produce the SRES result, and then
430  * use that to generate a new MAC.
431  *
432  * for the moment, we ignore the RANDs, then just plug in the SRES
433  * values.
434  *
435  */
436 static int process_eap_challenge(RADIUS_PACKET *req,
437                                  RADIUS_PACKET *rep)
438 {
439         VALUE_PAIR *newvp;
440         VALUE_PAIR *mac, *randvp;
441         VALUE_PAIR *sres1,*sres2,*sres3;
442         VALUE_PAIR *Kc1, *Kc2, *Kc3;
443         uint8_t calcmac[20];
444
445         /* look for the AT_MAC and the challenge data */
446         mac   = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_MAC);
447         randvp= pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_RAND);
448         if(mac == NULL || rand == NULL) {
449                 fprintf(stderr, "radeapclient: challenge message needs to contain RAND and MAC\n");
450                 return 0;
451         }
452
453         /*
454          * compare RAND with randX, to verify this is the right response
455          * to this challenge.
456          */
457         {
458           VALUE_PAIR *randcfgvp[3];
459           unsigned char *randcfg[3];
460
461           randcfg[0] = &randvp->vp_strvalue[2];
462           randcfg[1] = &randvp->vp_strvalue[2+EAPSIM_RAND_SIZE];
463           randcfg[2] = &randvp->vp_strvalue[2+EAPSIM_RAND_SIZE*2];
464
465           randcfgvp[0] = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_RAND1);
466           randcfgvp[1] = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_RAND2);
467           randcfgvp[2] = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_RAND3);
468
469           if(randcfgvp[0] == NULL ||
470              randcfgvp[1] == NULL ||
471              randcfgvp[2] == NULL) {
472             fprintf(stderr, "radeapclient: needs to have rand1, 2 and 3 set.\n");
473             return 0;
474           }
475
476           if(memcmp(randcfg[0], randcfgvp[0]->vp_strvalue, EAPSIM_RAND_SIZE)!=0 ||
477              memcmp(randcfg[1], randcfgvp[1]->vp_strvalue, EAPSIM_RAND_SIZE)!=0 ||
478              memcmp(randcfg[2], randcfgvp[2]->vp_strvalue, EAPSIM_RAND_SIZE)!=0) {
479             int rnum,i,j;
480
481             fprintf(stderr, "radeapclient: one of rand 1,2,3 didn't match\n");
482             for(rnum = 0; rnum < 3; rnum++) {
483               fprintf(stderr, "received   rand %d: ", rnum);
484               j=0;
485               for (i = 0; i < EAPSIM_RAND_SIZE; i++) {
486                 if(j==4) {
487                   printf("_");
488                   j=0;
489                 }
490                 j++;
491
492                 fprintf(stderr, "%02x", randcfg[rnum][i]);
493               }
494               fprintf(stderr, "\nconfigured rand %d: ", rnum);
495               j=0;
496               for (i = 0; i < EAPSIM_RAND_SIZE; i++) {
497                 if(j==4) {
498                   printf("_");
499                   j=0;
500                 }
501                 j++;
502
503                 fprintf(stderr, "%02x", randcfgvp[rnum]->vp_strvalue[i]);
504               }
505               fprintf(stderr, "\n");
506             }
507             return 0;
508           }
509         }
510
511         /*
512          * now dig up the sres values from the response packet,
513          * which were put there when we read things in.
514          *
515          * Really, they should be calculated from the RAND!
516          *
517          */
518         sres1 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_SRES1);
519         sres2 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_SRES2);
520         sres3 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_SRES3);
521
522         if(sres1 == NULL ||
523            sres2 == NULL ||
524            sres3 == NULL) {
525                 fprintf(stderr, "radeapclient: needs to have sres1, 2 and 3 set.\n");
526                 return 0;
527         }
528         memcpy(eapsim_mk.sres[0], sres1->vp_strvalue, sizeof(eapsim_mk.sres[0]));
529         memcpy(eapsim_mk.sres[1], sres2->vp_strvalue, sizeof(eapsim_mk.sres[1]));
530         memcpy(eapsim_mk.sres[2], sres3->vp_strvalue, sizeof(eapsim_mk.sres[2]));
531
532         Kc1 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_KC1);
533         Kc2 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_KC2);
534         Kc3 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_KC3);
535
536         if(Kc1 == NULL ||
537            Kc2 == NULL ||
538            Kc3 == NULL) {
539                 fprintf(stderr, "radeapclient: needs to have Kc1, 2 and 3 set.\n");
540                 return 0;
541         }
542         memcpy(eapsim_mk.Kc[0], Kc1->vp_strvalue, sizeof(eapsim_mk.Kc[0]));
543         memcpy(eapsim_mk.Kc[1], Kc2->vp_strvalue, sizeof(eapsim_mk.Kc[1]));
544         memcpy(eapsim_mk.Kc[2], Kc3->vp_strvalue, sizeof(eapsim_mk.Kc[2]));
545
546         /* all set, calculate keys */
547         eapsim_calculate_keys(&eapsim_mk);
548
549         if(debug_flag) {
550           eapsim_dump_mk(&eapsim_mk);
551         }
552
553         /* verify the MAC, now that we have all the keys. */
554         if(eapsim_checkmac(req->vps, eapsim_mk.K_aut,
555                            eapsim_mk.nonce_mt, sizeof(eapsim_mk.nonce_mt),
556                            calcmac)) {
557                 printf("MAC check succeed\n");
558         } else {
559                 int i, j;
560                 j=0;
561                 printf("calculated MAC (");
562                 for (i = 0; i < 20; i++) {
563                         if(j==4) {
564                                 printf("_");
565                                 j=0;
566                         }
567                         j++;
568
569                         printf("%02x", calcmac[i]);
570                 }
571                 printf(" did not match\n");
572                 return 0;
573         }
574
575         /* form new response clear of any EAP stuff */
576         cleanresp(rep);
577
578         /* mark the subtype as being EAP-SIM/Response/Start */
579         newvp = paircreate(ATTRIBUTE_EAP_SIM_SUBTYPE, PW_TYPE_INTEGER);
580         newvp->lvalue = eapsim_challenge;
581         pairreplace(&(rep->vps), newvp);
582
583         /*
584          * fill the SIM_MAC with a field that will in fact get appended
585          * to the packet before the MAC is calculated
586          */
587         newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_MAC,
588                            PW_TYPE_OCTETS);
589         memcpy(newvp->vp_strvalue+EAPSIM_SRES_SIZE*0, sres1->vp_strvalue, EAPSIM_SRES_SIZE);
590         memcpy(newvp->vp_strvalue+EAPSIM_SRES_SIZE*1, sres2->vp_strvalue, EAPSIM_SRES_SIZE);
591         memcpy(newvp->vp_strvalue+EAPSIM_SRES_SIZE*2, sres3->vp_strvalue, EAPSIM_SRES_SIZE);
592         newvp->length = EAPSIM_SRES_SIZE*3;
593         pairreplace(&(rep->vps), newvp);
594
595         newvp = paircreate(ATTRIBUTE_EAP_SIM_KEY, PW_TYPE_OCTETS);
596         memcpy(newvp->vp_strvalue,    eapsim_mk.K_aut, EAPSIM_AUTH_SIZE);
597         newvp->length = EAPSIM_AUTH_SIZE;
598         pairreplace(&(rep->vps), newvp);
599
600         return 1;
601 }
602
603 /*
604  * this code runs the EAP-SIM client state machine.
605  * the *request* is from the server.
606  * the *reponse* is to the server.
607  *
608  */
609 static int respond_eap_sim(RADIUS_PACKET *req,
610                            RADIUS_PACKET *resp)
611 {
612         enum eapsim_clientstates state, newstate;
613         enum eapsim_subtype subtype;
614         VALUE_PAIR *vp, *statevp, *radstate, *eapid;
615         char statenamebuf[32], subtypenamebuf[32];
616
617         if ((radstate = paircopy2(req->vps, PW_STATE)) == NULL)
618         {
619                 return 0;
620         }
621
622         if ((eapid = paircopy2(req->vps, ATTRIBUTE_EAP_ID)) == NULL)
623         {
624                 return 0;
625         }
626
627         /* first, dig up the state from the request packet, setting
628          * outselves to be in EAP-SIM-Start state if there is none.
629          */
630
631         if((statevp = pairfind(resp->vps, ATTRIBUTE_EAP_SIM_STATE)) == NULL)
632         {
633                 /* must be initial request */
634                 statevp = paircreate(ATTRIBUTE_EAP_SIM_STATE, PW_TYPE_INTEGER);
635                 statevp->lvalue = eapsim_client_init;
636                 pairreplace(&(resp->vps), statevp);
637         }
638         state = statevp->lvalue;
639
640         /*
641          * map the attributes, and authenticate them.
642          */
643         unmap_eapsim_types(req);
644
645         printf("<+++ EAP-sim decoded packet:\n");
646         vp_printlist(stdout, req->vps);
647
648         if((vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_SUBTYPE)) == NULL)
649         {
650                 return 0;
651         }
652         subtype = vp->lvalue;
653
654         /*
655          * look for the appropriate state, and process incoming message
656          */
657         switch(state) {
658         case eapsim_client_init:
659                 switch(subtype) {
660                 case eapsim_start:
661                         newstate = process_eap_start(req, resp);
662                         break;
663
664                 case eapsim_challenge:
665                 case eapsim_notification:
666                 case eapsim_reauth:
667                 default:
668                         fprintf(stderr, "radeapclient: sim in state %s message %s is illegal. Reply dropped.\n",
669                                 sim_state2name(state, statenamebuf, sizeof(statenamebuf)),
670                                 sim_subtype2name(subtype, subtypenamebuf, sizeof(subtypenamebuf)));
671                         /* invalid state, drop message */
672                         return 0;
673                 }
674                 break;
675
676         case eapsim_client_start:
677                 switch(subtype) {
678                 case eapsim_start:
679                         /* NOT SURE ABOUT THIS ONE, retransmit, I guess */
680                         newstate = process_eap_start(req, resp);
681                         break;
682
683                 case eapsim_challenge:
684                         newstate = process_eap_challenge(req, resp);
685                         break;
686
687                 default:
688                         fprintf(stderr, "radeapclient: sim in state %s message %s is illegal. Reply dropped.\n",
689                                 sim_state2name(state, statenamebuf, sizeof(statenamebuf)),
690                                 sim_subtype2name(subtype, subtypenamebuf, sizeof(subtypenamebuf)));
691                         /* invalid state, drop message */
692                         return 0;
693                 }
694                 break;
695
696
697         default:
698                 fprintf(stderr, "radeapclient: sim in illegal state %s\n",
699                         sim_state2name(state, statenamebuf, sizeof(statenamebuf)));
700                 return 0;
701         }
702
703         /* copy the eap state object in */
704         pairreplace(&(resp->vps), eapid);
705
706         /* update stete info, and send new packet */
707         map_eapsim_types(resp);
708
709         /* copy the radius state object in */
710         pairreplace(&(resp->vps), radstate);
711
712         statevp->lvalue = newstate;
713         return 1;
714 }
715
716 static int respond_eap_md5(RADIUS_PACKET *req,
717                            RADIUS_PACKET *rep)
718 {
719         VALUE_PAIR *vp, *id, *state;
720         int valuesize, namesize;
721         unsigned char identifier;
722         unsigned char *value;
723         unsigned char *name;
724         MD5_CTX context;
725         char    response[16];
726
727         cleanresp(rep);
728
729         if ((state = paircopy2(req->vps, PW_STATE)) == NULL)
730         {
731                 fprintf(stderr, "radeapclient: no state attribute found\n");
732                 return 0;
733         }
734
735         if ((id = paircopy2(req->vps, ATTRIBUTE_EAP_ID)) == NULL)
736         {
737                 fprintf(stderr, "radeapclient: no EAP-ID attribute found\n");
738                 return 0;
739         }
740         identifier = id->lvalue;
741
742         if ((vp = pairfind(req->vps, ATTRIBUTE_EAP_BASE+PW_EAP_MD5)) == NULL)
743         {
744                 fprintf(stderr, "radeapclient: no EAP-MD5 attribute found\n");
745                 return 0;
746         }
747
748         /* got the details of the MD5 challenge */
749         valuesize = vp->vp_octets[0];
750         value = &vp->vp_octets[1];
751         name  = &vp->vp_octets[valuesize+1];
752         namesize = vp->length - (valuesize + 1);
753
754         /* sanitize items */
755         if(valuesize > vp->length)
756         {
757                 fprintf(stderr, "radeapclient: md5 valuesize if too big (%d > %d)\n",
758                         valuesize, vp->length);
759                 return 0;
760         }
761
762         /* now do the CHAP operation ourself, rather than build the
763          * buffer. We could also call rad_chap_encode, but it wants
764          * a CHAP-Challenge, which we don't want to bother with.
765          */
766         lrad_MD5Init(&context);
767         lrad_MD5Update(&context, &identifier, 1);
768         lrad_MD5Update(&context, password, strlen(password));
769         lrad_MD5Update(&context, value, valuesize);
770         lrad_MD5Final(response, &context);
771
772         vp = paircreate(ATTRIBUTE_EAP_BASE+PW_EAP_MD5, PW_TYPE_OCTETS);
773         vp->vp_octets[0]=16;
774         memcpy(&vp->vp_strvalue[1], response, 16);
775         vp->length = 17;
776
777         pairreplace(&(rep->vps), vp);
778
779         pairreplace(&(rep->vps), id);
780
781         /* copy the state object in */
782         pairreplace(&(rep->vps), state);
783
784         return 1;
785 }
786
787
788
789 static int sendrecv_eap(RADIUS_PACKET *rep)
790 {
791         RADIUS_PACKET *req = NULL;
792         VALUE_PAIR *vp, *vpnext;
793         int tried_eap_md5 = 0;
794
795         /*
796          *      Keep a copy of the the User-Password attribute.
797          */
798         if ((vp = pairfind(rep->vps, PW_CLEARTEXT_PASSWORD)) != NULL) {
799                 strlcpy(password, (char *)vp->vp_strvalue, sizeof(vp->vp_strvalue));
800
801         } else  if ((vp = pairfind(rep->vps, PW_USER_PASSWORD)) != NULL) {
802                 strlcpy(password, (char *)vp->vp_strvalue, sizeof(vp->vp_strvalue));
803                 /*
804                  *      Otherwise keep a copy of the CHAP-Password attribute.
805                  */
806         } else if ((vp = pairfind(rep->vps, PW_CHAP_PASSWORD)) != NULL) {
807                 strlcpy(password, (char *)vp->vp_strvalue, sizeof(vp->vp_strvalue));
808         } else {
809                 *password = '\0';
810         }
811
812  again:
813         rep->id++;
814
815         printf("\n+++> About to send encoded packet:\n");
816         vp_printlist(stdout, rep->vps);
817
818         /*
819          * if there are EAP types, encode them into an EAP-Message
820          *
821          */
822         map_eap_types(rep);
823
824         /*
825          *  Fix up Digest-Attributes issues
826          */
827         for (vp = rep->vps; vp != NULL; vp = vp->next) {
828                 switch (vp->attribute) {
829                 default:
830                         break;
831
832                 case PW_DIGEST_REALM:
833                 case PW_DIGEST_NONCE:
834                 case PW_DIGEST_METHOD:
835                 case PW_DIGEST_URI:
836                 case PW_DIGEST_QOP:
837                 case PW_DIGEST_ALGORITHM:
838                 case PW_DIGEST_BODY_DIGEST:
839                 case PW_DIGEST_CNONCE:
840                 case PW_DIGEST_NONCE_COUNT:
841                 case PW_DIGEST_USER_NAME:
842                         /* overlapping! */
843                         memmove(&vp->vp_strvalue[2], &vp->vp_octets[0], vp->length);
844                         vp->vp_octets[0] = vp->attribute - PW_DIGEST_REALM + 1;
845                         vp->length += 2;
846                         vp->vp_octets[1] = vp->length;
847                         vp->attribute = PW_DIGEST_ATTRIBUTES;
848                         break;
849                 }
850         }
851
852         /*
853          *      If we've already sent a packet, free up the old
854          *      one, and ensure that the next packet has a unique
855          *      ID and authentication vector.
856          */
857         if (rep->data) {
858                 free(rep->data);
859                 rep->data = NULL;
860         }
861
862         librad_md5_calc(rep->vector, rep->vector,
863                         sizeof(rep->vector));
864
865         if (*password != '\0') {
866                 if ((vp = pairfind(rep->vps, PW_CLEARTEXT_PASSWORD)) != NULL) {
867                         strlcpy((char *)vp->vp_strvalue, password, sizeof(vp->vp_strvalue));
868                         vp->length = strlen(password);
869
870                 } else if ((vp = pairfind(rep->vps, PW_USER_PASSWORD)) != NULL) {
871                         strlcpy((char *)vp->vp_strvalue, password, sizeof(vp->vp_strvalue));
872                         vp->length = strlen(password);
873
874                 } else if ((vp = pairfind(rep->vps, PW_CHAP_PASSWORD)) != NULL) {
875                         strlcpy((char *)vp->vp_strvalue, password, sizeof(vp->vp_strvalue));
876                         vp->length = strlen(password);
877
878                         rad_chap_encode(rep, (char *) vp->vp_strvalue, rep->id, vp);
879                         vp->length = 17;
880                 }
881         } /* there WAS a password */
882
883         /* send the response, wait for the next request */
884         send_packet(rep, &req);
885
886         /* okay got back the packet, go and decode the EAP-Message. */
887         unmap_eap_types(req);
888
889         printf("<+++ EAP decoded packet:\n");
890         vp_printlist(stdout, req->vps);
891
892         /* now look for the code type. */
893         for (vp = req->vps; vp != NULL; vp = vpnext) {
894                 vpnext = vp->next;
895
896                 switch (vp->attribute) {
897                 default:
898                         break;
899
900                 case ATTRIBUTE_EAP_BASE+PW_EAP_MD5:
901                         if(respond_eap_md5(req, rep) && tried_eap_md5 < 3)
902                         {
903                                 tried_eap_md5++;
904                                 goto again;
905                         }
906                         break;
907
908                 case ATTRIBUTE_EAP_BASE+PW_EAP_SIM:
909                         if(respond_eap_sim(req, rep))
910                         {
911                                 goto again;
912                         }
913                         break;
914                 }
915         }
916
917         return 1;
918 }
919
920
921 int main(int argc, char **argv)
922 {
923         RADIUS_PACKET *req;
924         char *p;
925         int c;
926         int port = 0;
927         char *filename = NULL;
928         FILE *fp;
929         int count = 1;
930         int id;
931
932         id = ((int)getpid() & 0xff);
933         librad_debug = 0;
934
935         radlog_dest = RADLOG_STDERR;
936
937         while ((c = getopt(argc, argv, "c:d:f:hi:qst:r:S:xXv")) != EOF)
938         {
939                 switch(c) {
940                 case 'c':
941                         if (!isdigit((int) *optarg))
942                                 usage();
943                         count = atoi(optarg);
944                         break;
945                 case 'd':
946                         radius_dir = optarg;
947                         break;
948                 case 'f':
949                         filename = optarg;
950                         break;
951                 case 'q':
952                         do_output = 0;
953                         break;
954                 case 'x':
955                         debug_flag++;
956                         librad_debug++;
957                         break;
958
959                 case 'X':
960 #if 0
961                   sha1_data_problems = 1; /* for debugging only */
962 #endif
963                   break;
964
965
966
967                 case 'r':
968                         if (!isdigit((int) *optarg))
969                                 usage();
970                         retries = atoi(optarg);
971                         break;
972                 case 'i':
973                         if (!isdigit((int) *optarg))
974                                 usage();
975                         id = atoi(optarg);
976                         if ((id < 0) || (id > 255)) {
977                                 usage();
978                         }
979                         break;
980                 case 's':
981                         do_summary = 1;
982                         break;
983                 case 't':
984                         if (!isdigit((int) *optarg))
985                                 usage();
986                         timeout = atof(optarg);
987                         break;
988                 case 'v':
989                         printf("radclient: $Id$ built on " __DATE__ " at " __TIME__ "\n");
990                         exit(0);
991                         break;
992                case 'S':
993                        fp = fopen(optarg, "r");
994                        if (!fp) {
995                                fprintf(stderr, "radclient: Error opening %s: %s\n",
996                                        optarg, strerror(errno));
997                                exit(1);
998                        }
999                        if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
1000                                fprintf(stderr, "radclient: Error reading %s: %s\n",
1001                                        optarg, strerror(errno));
1002                                exit(1);
1003                        }
1004                        fclose(fp);
1005
1006                        /* truncate newline */
1007                        p = filesecret + strlen(filesecret) - 1;
1008                        while ((p >= filesecret) &&
1009                               (*p < ' ')) {
1010                                *p = '\0';
1011                                --p;
1012                        }
1013
1014                        if (strlen(filesecret) < 2) {
1015                                fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
1016                                exit(1);
1017                        }
1018                        secret = filesecret;
1019                        break;
1020                 case 'h':
1021                 default:
1022                         usage();
1023                         break;
1024                 }
1025         }
1026         argc -= (optind - 1);
1027         argv += (optind - 1);
1028
1029         if ((argc < 3)  ||
1030             ((secret == NULL) && (argc < 4))) {
1031                 usage();
1032         }
1033
1034         if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
1035                 librad_perror("radclient");
1036                 return 1;
1037         }
1038
1039         if ((req = rad_alloc(1)) == NULL) {
1040                 librad_perror("radclient");
1041                 exit(1);
1042         }
1043
1044 #if 0
1045         {
1046                 FILE *randinit;
1047
1048                 if((randinit = fopen("/dev/urandom", "r")) == NULL)
1049                 {
1050                         perror("/dev/urandom");
1051                 } else {
1052                         fread(randctx.randrsl, 256, 1, randinit);
1053                         fclose(randinit);
1054                 }
1055         }
1056         lrad_randinit(&randctx, 1);
1057 #endif
1058
1059         req->id = id;
1060
1061         /*
1062          *      Strip port from hostname if needed.
1063          */
1064         if ((p = strchr(argv[1], ':')) != NULL) {
1065                 *p++ = 0;
1066                 port = atoi(p);
1067         }
1068
1069         /*
1070          *      See what kind of request we want to send.
1071          */
1072         if (strcmp(argv[2], "auth") == 0) {
1073                 if (port == 0) port = getport("radius");
1074                 if (port == 0) port = PW_AUTH_UDP_PORT;
1075                 req->code = PW_AUTHENTICATION_REQUEST;
1076
1077         } else if (strcmp(argv[2], "acct") == 0) {
1078                 if (port == 0) port = getport("radacct");
1079                 if (port == 0) port = PW_ACCT_UDP_PORT;
1080                 req->code = PW_ACCOUNTING_REQUEST;
1081                 do_summary = 0;
1082
1083         } else if (strcmp(argv[2], "status") == 0) {
1084                 if (port == 0) port = getport("radius");
1085                 if (port == 0) port = PW_AUTH_UDP_PORT;
1086                 req->code = PW_STATUS_SERVER;
1087
1088         } else if (strcmp(argv[2], "disconnect") == 0) {
1089                 if (port == 0) port = PW_POD_UDP_PORT;
1090                 req->code = PW_DISCONNECT_REQUEST;
1091
1092         } else if (isdigit((int) argv[2][0])) {
1093                 if (port == 0) port = getport("radius");
1094                 if (port == 0) port = PW_AUTH_UDP_PORT;
1095                 req->code = atoi(argv[2]);
1096         } else {
1097                 usage();
1098         }
1099
1100         /*
1101          *      Ensure that the configuration is initialized.
1102          */
1103         memset(&mainconfig, 0, sizeof(mainconfig));
1104
1105         /*
1106          *      Resolve hostname.
1107          */
1108         req->dst_port = port;
1109         if (ip_hton(argv[1], AF_INET, &req->dst_ipaddr) < 0) {
1110                 fprintf(stderr, "radclient: Failed to find IP address for host %s\n", argv[1]);
1111                 exit(1);
1112         }
1113
1114         /*
1115          *      Add the secret.
1116          */
1117         if (argv[3]) secret = argv[3];
1118
1119         /*
1120          *      Read valuepairs.
1121          *      Maybe read them, from stdin, if there's no
1122          *      filename, or if the filename is '-'.
1123          */
1124         if (filename && (strcmp(filename, "-") != 0)) {
1125                 fp = fopen(filename, "r");
1126                 if (!fp) {
1127                         fprintf(stderr, "radclient: Error opening %s: %s\n",
1128                                 filename, strerror(errno));
1129                         exit(1);
1130                 }
1131         } else {
1132                 fp = stdin;
1133         }
1134
1135         /*
1136          *      Send request.
1137          */
1138         if ((req->sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1139                 perror("radclient: socket: ");
1140                 exit(1);
1141         }
1142
1143         while(!filedone) {
1144                 if(req->vps) pairfree(&req->vps);
1145
1146                 if ((req->vps = readvp2(fp, &filedone, "radeapclient:"))
1147                     == NULL) {
1148                         break;
1149                 }
1150
1151                 sendrecv_eap(req);
1152         }
1153
1154         if(do_summary) {
1155                 printf("\n\t   Total approved auths:  %d\n", totalapp);
1156                 printf("\t     Total denied auths:  %d\n", totaldeny);
1157         }
1158         return 0;
1159 }