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