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