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