4581feb771e20f5783856a0329944f8fe571a3a3
[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 /* fr_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 map_eap_types(RADIUS_PACKET *req);
67 static void unmap_eap_types(RADIUS_PACKET *rep);
68 static int map_eapsim_types(RADIUS_PACKET *r);
69 static int unmap_eapsim_types(RADIUS_PACKET *r);
70
71 void debug_pair_list(UNUSED VALUE_PAIR *vp)
72 {
73         return;
74 }
75
76 static void NEVER_RETURNS usage(void)
77 {
78         fprintf(stderr, "Usage: radeapclient [options] server[:port] <command> [<secret>]\n");
79
80         fprintf(stderr, "  <command>    One of auth, acct, status, or disconnect.\n");
81         fprintf(stderr, "  -c count    Send each packet 'count' times.\n");
82         fprintf(stderr, "  -d raddb    Set dictionary directory.\n");
83         fprintf(stderr, "  -f file     Read packets from file, not stdin.\n");
84         fprintf(stderr, "  -r retries  If timeout, retry sending the packet 'retries' times.\n");
85         fprintf(stderr, "  -t timeout  Wait 'timeout' seconds before retrying (may be a floating point number).\n");
86         fprintf(stderr, "  -i id       Set request id to 'id'.  Values may be 0..255\n");
87         fprintf(stderr, "  -S file     read secret from file, not command line.\n");
88         fprintf(stderr, "  -q          Do not print anything out.\n");
89         fprintf(stderr, "  -s          Print out summary information of auth results.\n");
90         fprintf(stderr, "  -v          Show program version information.\n");
91         fprintf(stderr, "  -x          Debugging mode.\n");
92
93         exit(1);
94 }
95
96 int radlog(int lvl, const char *msg, ...)
97 {
98         va_list ap;
99         int r;
100
101         r = lvl; /* shut up compiler */
102
103         va_start(ap, msg);
104         r = vfprintf(stderr, msg, ap);
105         va_end(ap);
106         fputc('\n', stderr);
107
108         return r;
109 }
110
111 int log_debug(const char *msg, ...)
112 {
113         va_list ap;
114         int r;
115
116         va_start(ap, msg);
117         r = vfprintf(stderr, msg, ap);
118         va_end(ap);
119         fputc('\n', stderr);
120
121         return r;
122 }
123
124 void radlog_request(UNUSED int lvl, UNUSED int priority,
125                     UNUSED REQUEST *request, const char *msg, ...)
126 {
127         va_list ap;
128
129         va_start(ap, msg);
130         vfprintf(stderr, msg, ap);
131         va_end(ap);
132         fputc('\n', stderr);
133 }
134
135 static int getport(const char *name)
136 {
137         struct  servent         *svp;
138
139         svp = getservbyname (name, "udp");
140         if (!svp) {
141                 return 0;
142         }
143
144         return ntohs(svp->s_port);
145 }
146
147 #define R_RECV (0)
148 #define R_SENT (1)
149 static void debug_packet(RADIUS_PACKET *packet, int direction)
150 {
151         VALUE_PAIR *vp;
152         char buffer[1024];
153         const char *received, *from;
154         const fr_ipaddr_t *ip;
155         int port;
156
157         if (!packet) return;
158
159         if (direction == 0) {
160                 received = "Received";
161                 from = "from";  /* what else? */
162                 ip = &packet->src_ipaddr;
163                 port = packet->src_port;
164
165         } else {
166                 received = "Sending";
167                 from = "to";    /* hah! */
168                 ip = &packet->dst_ipaddr;
169                 port = packet->dst_port;
170         }
171         
172         /*
173          *      Client-specific debugging re-prints the input
174          *      packet into the client log.
175          *
176          *      This really belongs in a utility library
177          */
178         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
179                 printf("%s %s packet %s host %s port %d, id=%d, length=%d\n",
180                        received, fr_packet_codes[packet->code], from,
181                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
182                        port, packet->id, packet->data_len);
183         } else {
184                 printf("%s packet %s host %s port %d code=%d, id=%d, length=%d\n",
185                        received, from,
186                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
187                        port,
188                        packet->code, packet->id, packet->data_len);
189         }
190
191         for (vp = packet->vps; vp != NULL; vp = vp->next) {
192                 vp_prints(buffer, sizeof(buffer), vp);
193                 printf("\t%s\n", buffer);
194         }
195         fflush(stdout);
196 }
197
198
199 static int send_packet(RADIUS_PACKET *req, RADIUS_PACKET **rep)
200 {
201         int i;
202         struct timeval  tv;
203
204         for (i = 0; i < retries; i++) {
205                 fd_set          rdfdesc;
206
207                 debug_packet(req, R_SENT);
208
209                 rad_send(req, NULL, secret);
210
211                 /* And wait for reply, timing out as necessary */
212                 FD_ZERO(&rdfdesc);
213                 FD_SET(req->sockfd, &rdfdesc);
214
215                 tv.tv_sec = (int)timeout;
216                 tv.tv_usec = 1000000 * (timeout - (int) timeout);
217
218                 /* Something's wrong if we don't get exactly one fd. */
219                 if (select(req->sockfd + 1, &rdfdesc, NULL, NULL, &tv) != 1) {
220                         continue;
221                 }
222
223                 *rep = rad_recv(req->sockfd, 0);
224                 if (*rep != NULL) {
225                         /*
226                          *      If we get a response from a machine
227                          *      which we did NOT send a request to,
228                          *      then complain.
229                          */
230                         if (((*rep)->src_ipaddr.af != req->dst_ipaddr.af) ||
231                             (memcmp(&(*rep)->src_ipaddr.ipaddr,
232                                     &req->dst_ipaddr.ipaddr,
233                                     ((req->dst_ipaddr.af == AF_INET ? /* AF_INET6? */
234                                       sizeof(req->dst_ipaddr.ipaddr.ip4addr) : /* FIXME: AF_INET6 */
235                                       sizeof(req->dst_ipaddr.ipaddr.ip6addr)))) != 0) ||
236                             ((*rep)->src_port != req->dst_port)) {
237                                 char src[128], dst[128];
238
239                                 ip_ntoh(&(*rep)->src_ipaddr, src, sizeof(src));
240                                 ip_ntoh(&req->dst_ipaddr, dst, sizeof(dst));
241                                 fprintf(stderr, "radclient: ERROR: Sent request to host %s port %d, got response from host %s port %d\n!",
242                                         dst, req->dst_port,
243                                         src, (*rep)->src_port);
244                                 exit(1);
245                         }
246                         break;
247                 } else {        /* NULL: couldn't receive the packet */
248                         fr_perror("radclient:");
249                         exit(1);
250                 }
251         }
252
253         /* No response or no data read (?) */
254         if (i == retries) {
255                 fprintf(stderr, "radclient: no response from server\n");
256                 exit(1);
257         }
258
259         /*
260          *      FIXME: Discard the packet & listen for another.
261          *
262          *      Hmm... we should really be using eapol_test, which does
263          *      a lot more than radeapclient.
264          */
265         if (rad_verify(*rep, req, secret) != 0) {
266                 fr_perror("rad_verify");
267                 exit(1);
268         }
269
270         if (rad_decode(*rep, req, secret) != 0) {
271                 fr_perror("rad_decode");
272                 exit(1);
273         }
274
275         /* libradius debug already prints out the value pairs for us */
276         if (!fr_debug_flag && do_output) {
277                 debug_packet(*rep, R_RECV);
278         }
279         if((*rep)->code == PW_AUTHENTICATION_ACK) {
280                 totalapp++;
281         } else if ((*rep)->code == PW_AUTHENTICATION_REJECT) {
282                 totaldeny++;
283         }
284
285         return 0;
286 }
287
288 static void cleanresp(RADIUS_PACKET *resp)
289 {
290         VALUE_PAIR *vpnext, *vp, **last;
291
292
293         /*
294          * maybe should just copy things we care about, or keep
295          * a copy of the original input and start from there again?
296          */
297         pairdelete(&resp->vps, PW_EAP_MESSAGE, 0);
298         pairdelete(&resp->vps, ATTRIBUTE_EAP_BASE+PW_EAP_IDENTITY, 0);
299
300         last = &resp->vps;
301         for(vp = *last; vp != NULL; vp = vpnext)
302         {
303                 vpnext = vp->next;
304
305                 if((vp->attribute > ATTRIBUTE_EAP_BASE &&
306                     vp->attribute <= ATTRIBUTE_EAP_BASE+256) ||
307                    (vp->attribute > ATTRIBUTE_EAP_SIM_BASE &&
308                     vp->attribute <= ATTRIBUTE_EAP_SIM_BASE+256))
309                 {
310                         *last = vpnext;
311                         pairbasicfree(vp);
312                 } else {
313                         last = &vp->next;
314                 }
315         }
316 }
317
318 /*
319  * we got an EAP-Request/Sim/Start message in a legal state.
320  *
321  * pick a supported version, put it into the reply, and insert a nonce.
322  */
323 static int process_eap_start(RADIUS_PACKET *req,
324                              RADIUS_PACKET *rep)
325 {
326         VALUE_PAIR *vp, *newvp;
327         VALUE_PAIR *anyidreq_vp, *fullauthidreq_vp, *permanentidreq_vp;
328         uint16_t *versions, selectedversion;
329         unsigned int i,versioncount;
330
331         /* form new response clear of any EAP stuff */
332         cleanresp(rep);
333
334         if((vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_VERSION_LIST, 0)) == NULL) {
335                 fprintf(stderr, "illegal start message has no VERSION_LIST\n");
336                 return 0;
337         }
338
339         versions = (uint16_t *)vp->vp_strvalue;
340
341         /* verify that the attribute length is big enough for a length field */
342         if(vp->length < 4)
343         {
344                 fprintf(stderr, "start message has illegal VERSION_LIST. Too short: %u\n", (unsigned int) vp->length);
345                 return 0;
346         }
347
348         versioncount = ntohs(versions[0])/2;
349         /* verify that the attribute length is big enough for the given number
350          * of versions present.
351          */
352         if((unsigned)vp->length <= (versioncount*2 + 2))
353         {
354                 fprintf(stderr, "start message is too short. Claimed %d versions does not fit in %u bytes\n", versioncount, (unsigned int) vp->length);
355                 return 0;
356         }
357
358         /*
359          * record the versionlist for the MK calculation.
360          */
361         eapsim_mk.versionlistlen = versioncount*2;
362         memcpy(eapsim_mk.versionlist, (unsigned char *)(versions+1),
363                eapsim_mk.versionlistlen);
364
365         /* walk the version list, and pick the one we support, which
366          * at present, is 1, EAP_SIM_VERSION.
367          */
368         selectedversion=0;
369         for(i=0; i < versioncount; i++)
370         {
371                 if(ntohs(versions[i+1]) == EAP_SIM_VERSION)
372                 {
373                         selectedversion=EAP_SIM_VERSION;
374                         break;
375                 }
376         }
377         if(selectedversion == 0)
378         {
379                 fprintf(stderr, "eap-sim start message. No compatible version found. We need %d\n", EAP_SIM_VERSION);
380                 for(i=0; i < versioncount; i++)
381                 {
382                         fprintf(stderr, "\tfound version %d\n",
383                                 ntohs(versions[i+1]));
384                 }
385         }
386
387         /*
388          * now make sure that we have only FULLAUTH_ID_REQ.
389          * I think that it actually might not matter - we can answer in
390          * anyway we like, but it is illegal to have more than one
391          * present.
392          */
393         anyidreq_vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_ANY_ID_REQ, 0);
394         fullauthidreq_vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_FULLAUTH_ID_REQ, 0);
395         permanentidreq_vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_PERMANENT_ID_REQ, 0);
396
397         if(fullauthidreq_vp == NULL ||
398            anyidreq_vp != NULL ||
399            permanentidreq_vp != NULL) {
400                 fprintf(stderr, "start message has %sanyidreq, %sfullauthid and %spermanentid. Illegal combination.\n",
401                         (anyidreq_vp != NULL ? "a " : "no "),
402                         (fullauthidreq_vp != NULL ? "a " : "no "),
403                         (permanentidreq_vp != NULL ? "a " : "no "));
404                 return 0;
405         }
406
407         /* okay, we have just any_id_req there, so fill in response */
408
409         /* mark the subtype as being EAP-SIM/Response/Start */
410         newvp = paircreate(ATTRIBUTE_EAP_SIM_SUBTYPE, 0, PW_TYPE_INTEGER);
411         newvp->vp_integer = eapsim_start;
412         pairreplace(&(rep->vps), newvp);
413
414         /* insert selected version into response. */
415         newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_SELECTED_VERSION,
416                            0, PW_TYPE_OCTETS);
417         versions = (uint16_t *)newvp->vp_strvalue;
418         versions[0] = htons(selectedversion);
419         newvp->length = 2;
420         pairreplace(&(rep->vps), newvp);
421
422         /* record the selected version */
423         memcpy(eapsim_mk.versionselect, (unsigned char *)versions, 2);
424
425         vp = newvp = NULL;
426
427         {
428                 uint32_t nonce[4];
429                 /*
430                  * insert a nonce_mt that we make up.
431                  */
432                 newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_NONCE_MT,
433                                    0, PW_TYPE_OCTETS);
434                 newvp->vp_octets[0]=0;
435                 newvp->vp_octets[1]=0;
436                 newvp->length = 18;  /* 16 bytes of nonce + padding */
437
438                 nonce[0]=fr_rand();
439                 nonce[1]=fr_rand();
440                 nonce[2]=fr_rand();
441                 nonce[3]=fr_rand();
442                 memcpy(&newvp->vp_octets[2], nonce, 16);
443                 pairreplace(&(rep->vps), newvp);
444
445                 /* also keep a copy of the nonce! */
446                 memcpy(eapsim_mk.nonce_mt, nonce, 16);
447         }
448
449         {
450                 uint16_t *pidlen, idlen;
451
452                 /*
453                  * insert the identity here.
454                  */
455                 vp = pairfind(rep->vps, PW_USER_NAME, 0);
456                 if(vp == NULL)
457                 {
458                         fprintf(stderr, "eap-sim: We need to have a User-Name attribute!\n");
459                         return 0;
460                 }
461                 newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_IDENTITY,
462                                    0, PW_TYPE_OCTETS);
463                 idlen = strlen(vp->vp_strvalue);
464                 pidlen = (uint16_t *)newvp->vp_strvalue;
465                 *pidlen = htons(idlen);
466                 newvp->length = idlen + 2;
467
468                 memcpy(&newvp->vp_strvalue[2], vp->vp_strvalue, idlen);
469                 pairreplace(&(rep->vps), newvp);
470
471                 /* record it */
472                 memcpy(eapsim_mk.identity, vp->vp_strvalue, idlen);
473                 eapsim_mk.identitylen = idlen;
474         }
475
476         return 1;
477 }
478
479 /*
480  * we got an EAP-Request/Sim/Challenge message in a legal state.
481  *
482  * use the RAND challenge to produce the SRES result, and then
483  * use that to generate a new MAC.
484  *
485  * for the moment, we ignore the RANDs, then just plug in the SRES
486  * values.
487  *
488  */
489 static int process_eap_challenge(RADIUS_PACKET *req,
490                                  RADIUS_PACKET *rep)
491 {
492         VALUE_PAIR *newvp;
493         VALUE_PAIR *mac, *randvp;
494         VALUE_PAIR *sres1,*sres2,*sres3;
495         VALUE_PAIR *Kc1, *Kc2, *Kc3;
496         uint8_t calcmac[20];
497
498         /* look for the AT_MAC and the challenge data */
499         mac   = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_MAC, 0);
500         randvp= pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_RAND, 0);
501         if(mac == NULL || randvp == NULL) {
502                 fprintf(stderr, "radeapclient: challenge message needs to contain RAND and MAC\n");
503                 return 0;
504         }
505
506         /*
507          * compare RAND with randX, to verify this is the right response
508          * to this challenge.
509          */
510         {
511           VALUE_PAIR *randcfgvp[3];
512           uint8_t *randcfg[3];
513
514           randcfg[0] = &randvp->vp_octets[2];
515           randcfg[1] = &randvp->vp_octets[2+EAPSIM_RAND_SIZE];
516           randcfg[2] = &randvp->vp_octets[2+EAPSIM_RAND_SIZE*2];
517
518           randcfgvp[0] = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_RAND1, 0);
519           randcfgvp[1] = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_RAND2, 0);
520           randcfgvp[2] = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_RAND3, 0);
521
522           if(randcfgvp[0] == NULL ||
523              randcfgvp[1] == NULL ||
524              randcfgvp[2] == NULL) {
525             fprintf(stderr, "radeapclient: needs to have rand1, 2 and 3 set.\n");
526             return 0;
527           }
528
529           if(memcmp(randcfg[0], randcfgvp[0]->vp_octets, EAPSIM_RAND_SIZE)!=0 ||
530              memcmp(randcfg[1], randcfgvp[1]->vp_octets, EAPSIM_RAND_SIZE)!=0 ||
531              memcmp(randcfg[2], randcfgvp[2]->vp_octets, EAPSIM_RAND_SIZE)!=0) {
532             int rnum,i,j;
533
534             fprintf(stderr, "radeapclient: one of rand 1,2,3 didn't match\n");
535             for(rnum = 0; rnum < 3; rnum++) {
536               fprintf(stderr, "received   rand %d: ", rnum);
537               j=0;
538               for (i = 0; i < EAPSIM_RAND_SIZE; i++) {
539                 if(j==4) {
540                   printf("_");
541                   j=0;
542                 }
543                 j++;
544
545                 fprintf(stderr, "%02x", randcfg[rnum][i]);
546               }
547               fprintf(stderr, "\nconfigured rand %d: ", rnum);
548               j=0;
549               for (i = 0; i < EAPSIM_RAND_SIZE; i++) {
550                 if(j==4) {
551                   printf("_");
552                   j=0;
553                 }
554                 j++;
555
556                 fprintf(stderr, "%02x", randcfgvp[rnum]->vp_octets[i]);
557               }
558               fprintf(stderr, "\n");
559             }
560             return 0;
561           }
562         }
563
564         /*
565          * now dig up the sres values from the response packet,
566          * which were put there when we read things in.
567          *
568          * Really, they should be calculated from the RAND!
569          *
570          */
571         sres1 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_SRES1, 0);
572         sres2 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_SRES2, 0);
573         sres3 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_SRES3, 0);
574
575         if(sres1 == NULL ||
576            sres2 == NULL ||
577            sres3 == NULL) {
578                 fprintf(stderr, "radeapclient: needs to have sres1, 2 and 3 set.\n");
579                 return 0;
580         }
581         memcpy(eapsim_mk.sres[0], sres1->vp_strvalue, sizeof(eapsim_mk.sres[0]));
582         memcpy(eapsim_mk.sres[1], sres2->vp_strvalue, sizeof(eapsim_mk.sres[1]));
583         memcpy(eapsim_mk.sres[2], sres3->vp_strvalue, sizeof(eapsim_mk.sres[2]));
584
585         Kc1 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_KC1, 0);
586         Kc2 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_KC2, 0);
587         Kc3 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_KC3, 0);
588
589         if(Kc1 == NULL ||
590            Kc2 == NULL ||
591            Kc3 == NULL) {
592                 fprintf(stderr, "radeapclient: needs to have Kc1, 2 and 3 set.\n");
593                 return 0;
594         }
595         memcpy(eapsim_mk.Kc[0], Kc1->vp_strvalue, sizeof(eapsim_mk.Kc[0]));
596         memcpy(eapsim_mk.Kc[1], Kc2->vp_strvalue, sizeof(eapsim_mk.Kc[1]));
597         memcpy(eapsim_mk.Kc[2], Kc3->vp_strvalue, sizeof(eapsim_mk.Kc[2]));
598
599         /* all set, calculate keys */
600         eapsim_calculate_keys(&eapsim_mk);
601
602         if(debug_flag) {
603           eapsim_dump_mk(&eapsim_mk);
604         }
605
606         /* verify the MAC, now that we have all the keys. */
607         if(eapsim_checkmac(req->vps, eapsim_mk.K_aut,
608                            eapsim_mk.nonce_mt, sizeof(eapsim_mk.nonce_mt),
609                            calcmac)) {
610                 printf("MAC check succeed\n");
611         } else {
612                 int i, j;
613                 j=0;
614                 printf("calculated MAC (");
615                 for (i = 0; i < 20; i++) {
616                         if(j==4) {
617                                 printf("_");
618                                 j=0;
619                         }
620                         j++;
621
622                         printf("%02x", calcmac[i]);
623                 }
624                 printf(" did not match\n");
625                 return 0;
626         }
627
628         /* form new response clear of any EAP stuff */
629         cleanresp(rep);
630
631         /* mark the subtype as being EAP-SIM/Response/Start */
632         newvp = paircreate(ATTRIBUTE_EAP_SIM_SUBTYPE, 0, PW_TYPE_INTEGER);
633         newvp->vp_integer = eapsim_challenge;
634         pairreplace(&(rep->vps), newvp);
635
636         /*
637          * fill the SIM_MAC with a field that will in fact get appended
638          * to the packet before the MAC is calculated
639          */
640         newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_MAC, 0,
641                            PW_TYPE_OCTETS);
642         memcpy(newvp->vp_strvalue+EAPSIM_SRES_SIZE*0, sres1->vp_strvalue, EAPSIM_SRES_SIZE);
643         memcpy(newvp->vp_strvalue+EAPSIM_SRES_SIZE*1, sres2->vp_strvalue, EAPSIM_SRES_SIZE);
644         memcpy(newvp->vp_strvalue+EAPSIM_SRES_SIZE*2, sres3->vp_strvalue, EAPSIM_SRES_SIZE);
645         newvp->length = EAPSIM_SRES_SIZE*3;
646         pairreplace(&(rep->vps), newvp);
647
648         newvp = paircreate(ATTRIBUTE_EAP_SIM_KEY, 0, PW_TYPE_OCTETS);
649         memcpy(newvp->vp_strvalue,    eapsim_mk.K_aut, EAPSIM_AUTH_SIZE);
650         newvp->length = EAPSIM_AUTH_SIZE;
651         pairreplace(&(rep->vps), newvp);
652
653         return 1;
654 }
655
656 /*
657  * this code runs the EAP-SIM client state machine.
658  * the *request* is from the server.
659  * the *reponse* is to the server.
660  *
661  */
662 static int respond_eap_sim(RADIUS_PACKET *req,
663                            RADIUS_PACKET *resp)
664 {
665         enum eapsim_clientstates state, newstate;
666         enum eapsim_subtype subtype;
667         VALUE_PAIR *vp, *statevp, *radstate, *eapid;
668         char statenamebuf[32], subtypenamebuf[32];
669
670         if ((radstate = paircopy2(req->vps, PW_STATE, 0)) == NULL)
671         {
672                 return 0;
673         }
674
675         if ((eapid = paircopy2(req->vps, ATTRIBUTE_EAP_ID, 0)) == NULL)
676         {
677                 return 0;
678         }
679
680         /* first, dig up the state from the request packet, setting
681          * outselves to be in EAP-SIM-Start state if there is none.
682          */
683
684         if((statevp = pairfind(resp->vps, ATTRIBUTE_EAP_SIM_STATE, 0)) == NULL)
685         {
686                 /* must be initial request */
687                 statevp = paircreate(ATTRIBUTE_EAP_SIM_STATE, 0, PW_TYPE_INTEGER);
688                 statevp->vp_integer = eapsim_client_init;
689                 pairreplace(&(resp->vps), statevp);
690         }
691         state = statevp->vp_integer;
692
693         /*
694          * map the attributes, and authenticate them.
695          */
696         unmap_eapsim_types(req);
697
698         if((vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_SUBTYPE, 0)) == NULL)
699         {
700                 return 0;
701         }
702         subtype = vp->vp_integer;
703
704         /*
705          * look for the appropriate state, and process incoming message
706          */
707         switch(state) {
708         case eapsim_client_init:
709                 switch(subtype) {
710                 case eapsim_start:
711                         newstate = process_eap_start(req, resp);
712                         break;
713
714                 case eapsim_challenge:
715                 case eapsim_notification:
716                 case eapsim_reauth:
717                 default:
718                         fprintf(stderr, "radeapclient: sim in state %s message %s is illegal. Reply dropped.\n",
719                                 sim_state2name(state, statenamebuf, sizeof(statenamebuf)),
720                                 sim_subtype2name(subtype, subtypenamebuf, sizeof(subtypenamebuf)));
721                         /* invalid state, drop message */
722                         return 0;
723                 }
724                 break;
725
726         case eapsim_client_start:
727                 switch(subtype) {
728                 case eapsim_start:
729                         /* NOT SURE ABOUT THIS ONE, retransmit, I guess */
730                         newstate = process_eap_start(req, resp);
731                         break;
732
733                 case eapsim_challenge:
734                         newstate = process_eap_challenge(req, resp);
735                         break;
736
737                 default:
738                         fprintf(stderr, "radeapclient: sim in state %s message %s is illegal. Reply dropped.\n",
739                                 sim_state2name(state, statenamebuf, sizeof(statenamebuf)),
740                                 sim_subtype2name(subtype, subtypenamebuf, sizeof(subtypenamebuf)));
741                         /* invalid state, drop message */
742                         return 0;
743                 }
744                 break;
745
746
747         default:
748                 fprintf(stderr, "radeapclient: sim in illegal state %s\n",
749                         sim_state2name(state, statenamebuf, sizeof(statenamebuf)));
750                 return 0;
751         }
752
753         /* copy the eap state object in */
754         pairreplace(&(resp->vps), eapid);
755
756         /* update stete info, and send new packet */
757         map_eapsim_types(resp);
758
759         /* copy the radius state object in */
760         pairreplace(&(resp->vps), radstate);
761
762         statevp->vp_integer = newstate;
763         return 1;
764 }
765
766 static int respond_eap_md5(RADIUS_PACKET *req,
767                            RADIUS_PACKET *rep)
768 {
769         VALUE_PAIR *vp, *id, *state;
770         size_t valuesize, namesize;
771         uint8_t identifier;
772         uint8_t *value;
773         uint8_t *name;
774         FR_MD5_CTX      context;
775         uint8_t    response[16];
776
777         cleanresp(rep);
778
779         if ((state = paircopy2(req->vps, PW_STATE, 0)) == NULL)
780         {
781                 fprintf(stderr, "radeapclient: no state attribute found\n");
782                 return 0;
783         }
784
785         if ((id = paircopy2(req->vps, ATTRIBUTE_EAP_ID, 0)) == NULL)
786         {
787                 fprintf(stderr, "radeapclient: no EAP-ID attribute found\n");
788                 return 0;
789         }
790         identifier = id->vp_integer;
791
792         if ((vp = pairfind(req->vps, ATTRIBUTE_EAP_BASE+PW_EAP_MD5, 0)) == NULL)
793         {
794                 fprintf(stderr, "radeapclient: no EAP-MD5 attribute found\n");
795                 return 0;
796         }
797
798         /* got the details of the MD5 challenge */
799         valuesize = vp->vp_octets[0];
800         value = &vp->vp_octets[1];
801         name  = &vp->vp_octets[valuesize+1];
802         namesize = vp->length - (valuesize + 1);
803
804         /* sanitize items */
805         if(valuesize > vp->length)
806         {
807                 fprintf(stderr, "radeapclient: md5 valuesize if too big (%u > %u)\n",
808                         (unsigned int) valuesize, (unsigned int) vp->length);
809                 return 0;
810         }
811
812         /* now do the CHAP operation ourself, rather than build the
813          * buffer. We could also call rad_chap_encode, but it wants
814          * a CHAP-Challenge, which we don't want to bother with.
815          */
816         fr_MD5Init(&context);
817         fr_MD5Update(&context, &identifier, 1);
818         fr_MD5Update(&context, (uint8_t *) password, strlen(password));
819         fr_MD5Update(&context, value, valuesize);
820         fr_MD5Final(response, &context);
821
822         vp = paircreate(ATTRIBUTE_EAP_BASE+PW_EAP_MD5, 0, PW_TYPE_OCTETS);
823         vp->vp_octets[0]=16;
824         memcpy(&vp->vp_strvalue[1], response, 16);
825         vp->length = 17;
826
827         pairreplace(&(rep->vps), vp);
828
829         pairreplace(&(rep->vps), id);
830
831         /* copy the state object in */
832         pairreplace(&(rep->vps), state);
833
834         return 1;
835 }
836
837
838
839 static int sendrecv_eap(RADIUS_PACKET *rep)
840 {
841         RADIUS_PACKET *req = NULL;
842         VALUE_PAIR *vp, *vpnext;
843         int tried_eap_md5 = 0;
844
845         /*
846          *      Keep a copy of the the User-Password attribute.
847          */
848         if ((vp = pairfind(rep->vps, PW_CLEARTEXT_PASSWORD, 0)) != NULL) {
849                 strlcpy(password, (char *)vp->vp_strvalue, sizeof(vp->vp_strvalue));
850
851         } else  if ((vp = pairfind(rep->vps, PW_USER_PASSWORD, 0)) != NULL) {
852                 strlcpy(password, (char *)vp->vp_strvalue, sizeof(vp->vp_strvalue));
853                 /*
854                  *      Otherwise keep a copy of the CHAP-Password attribute.
855                  */
856         } else if ((vp = pairfind(rep->vps, PW_CHAP_PASSWORD, 0)) != NULL) {
857                 strlcpy(password, (char *)vp->vp_strvalue, sizeof(vp->vp_strvalue));
858         } else {
859                 *password = '\0';
860         }
861
862  again:
863         rep->id++;
864
865         /*
866          * if there are EAP types, encode them into an EAP-Message
867          *
868          */
869         map_eap_types(rep);
870
871         /*
872          *  Fix up Digest-Attributes issues
873          */
874         for (vp = rep->vps; vp != NULL; vp = vp->next) {
875                 switch (vp->attribute) {
876                 default:
877                         break;
878
879                 case PW_DIGEST_REALM:
880                 case PW_DIGEST_NONCE:
881                 case PW_DIGEST_METHOD:
882                 case PW_DIGEST_URI:
883                 case PW_DIGEST_QOP:
884                 case PW_DIGEST_ALGORITHM:
885                 case PW_DIGEST_BODY_DIGEST:
886                 case PW_DIGEST_CNONCE:
887                 case PW_DIGEST_NONCE_COUNT:
888                 case PW_DIGEST_USER_NAME:
889                         /* overlapping! */
890                         memmove(&vp->vp_strvalue[2], &vp->vp_octets[0], vp->length);
891                         vp->vp_octets[0] = vp->attribute - PW_DIGEST_REALM + 1;
892                         vp->length += 2;
893                         vp->vp_octets[1] = vp->length;
894                         vp->attribute = PW_DIGEST_ATTRIBUTES;
895                         break;
896                 }
897         }
898
899         /*
900          *      If we've already sent a packet, free up the old
901          *      one, and ensure that the next packet has a unique
902          *      ID and authentication vector.
903          */
904         if (rep->data) {
905                 free(rep->data);
906                 rep->data = NULL;
907         }
908
909         fr_md5_calc(rep->vector, rep->vector,
910                         sizeof(rep->vector));
911
912         if (*password != '\0') {
913                 if ((vp = pairfind(rep->vps, PW_CLEARTEXT_PASSWORD, 0)) != NULL) {
914                         strlcpy((char *)vp->vp_strvalue, password, sizeof(vp->vp_strvalue));
915                         vp->length = strlen(password);
916
917                 } else if ((vp = pairfind(rep->vps, PW_USER_PASSWORD, 0)) != NULL) {
918                         strlcpy((char *)vp->vp_strvalue, password, sizeof(vp->vp_strvalue));
919                         vp->length = strlen(password);
920
921                 } else if ((vp = pairfind(rep->vps, PW_CHAP_PASSWORD, 0)) != NULL) {
922                         strlcpy((char *)vp->vp_strvalue, password, sizeof(vp->vp_strvalue));
923                         vp->length = strlen(password);
924
925                         rad_chap_encode(rep, vp->vp_octets, rep->id, vp);
926                         vp->length = 17;
927                 }
928         } /* there WAS a password */
929
930         /* send the response, wait for the next request */
931         send_packet(rep, &req);
932
933         /* okay got back the packet, go and decode the EAP-Message. */
934         unmap_eap_types(req);
935
936         debug_packet(req, R_RECV);
937
938         /* now look for the code type. */
939         for (vp = req->vps; vp != NULL; vp = vpnext) {
940                 vpnext = vp->next;
941
942                 switch (vp->attribute) {
943                 default:
944                         break;
945
946                 case ATTRIBUTE_EAP_BASE+PW_EAP_MD5:
947                         if(respond_eap_md5(req, rep) && tried_eap_md5 < 3)
948                         {
949                                 tried_eap_md5++;
950                                 goto again;
951                         }
952                         break;
953
954                 case ATTRIBUTE_EAP_BASE+PW_EAP_SIM:
955                         if(respond_eap_sim(req, rep))
956                         {
957                                 goto again;
958                         }
959                         break;
960                 }
961         }
962
963         return 1;
964 }
965
966
967 int main(int argc, char **argv)
968 {
969         RADIUS_PACKET *req;
970         char *p;
971         int c;
972         int port = 0;
973         char *filename = NULL;
974         FILE *fp;
975         int count = 1;
976         int id;
977
978         id = ((int)getpid() & 0xff);
979         fr_debug_flag = 0;
980
981         radlog_dest = RADLOG_STDERR;
982
983         while ((c = getopt(argc, argv, "c:d:f:hi:qst:r:S:xXv")) != EOF)
984         {
985                 switch(c) {
986                 case 'c':
987                         if (!isdigit((int) *optarg))
988                                 usage();
989                         count = atoi(optarg);
990                         break;
991                 case 'd':
992                         radius_dir = optarg;
993                         break;
994                 case 'f':
995                         filename = optarg;
996                         break;
997                 case 'q':
998                         do_output = 0;
999                         break;
1000                 case 'x':
1001                         debug_flag++;
1002                         fr_debug_flag++;
1003                         break;
1004
1005                 case 'X':
1006 #if 0
1007                   sha1_data_problems = 1; /* for debugging only */
1008 #endif
1009                   break;
1010
1011
1012
1013                 case 'r':
1014                         if (!isdigit((int) *optarg))
1015                                 usage();
1016                         retries = atoi(optarg);
1017                         break;
1018                 case 'i':
1019                         if (!isdigit((int) *optarg))
1020                                 usage();
1021                         id = atoi(optarg);
1022                         if ((id < 0) || (id > 255)) {
1023                                 usage();
1024                         }
1025                         break;
1026                 case 's':
1027                         do_summary = 1;
1028                         break;
1029                 case 't':
1030                         if (!isdigit((int) *optarg))
1031                                 usage();
1032                         timeout = atof(optarg);
1033                         break;
1034                 case 'v':
1035                         printf("radclient: $Id$ built on " __DATE__ " at " __TIME__ "\n");
1036                         exit(0);
1037                         break;
1038                case 'S':
1039                        fp = fopen(optarg, "r");
1040                        if (!fp) {
1041                                fprintf(stderr, "radclient: Error opening %s: %s\n",
1042                                        optarg, strerror(errno));
1043                                exit(1);
1044                        }
1045                        if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
1046                                fprintf(stderr, "radclient: Error reading %s: %s\n",
1047                                        optarg, strerror(errno));
1048                                exit(1);
1049                        }
1050                        fclose(fp);
1051
1052                        /* truncate newline */
1053                        p = filesecret + strlen(filesecret) - 1;
1054                        while ((p >= filesecret) &&
1055                               (*p < ' ')) {
1056                                *p = '\0';
1057                                --p;
1058                        }
1059
1060                        if (strlen(filesecret) < 2) {
1061                                fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
1062                                exit(1);
1063                        }
1064                        secret = filesecret;
1065                        break;
1066                 case 'h':
1067                 default:
1068                         usage();
1069                         break;
1070                 }
1071         }
1072         argc -= (optind - 1);
1073         argv += (optind - 1);
1074
1075         if ((argc < 3)  ||
1076             ((secret == NULL) && (argc < 4))) {
1077                 usage();
1078         }
1079
1080         if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
1081                 fr_perror("radclient");
1082                 return 1;
1083         }
1084
1085         if ((req = rad_alloc(1)) == NULL) {
1086                 fr_perror("radclient");
1087                 exit(1);
1088         }
1089
1090 #if 0
1091         {
1092                 FILE *randinit;
1093
1094                 if((randinit = fopen("/dev/urandom", "r")) == NULL)
1095                 {
1096                         perror("/dev/urandom");
1097                 } else {
1098                         fread(randctx.randrsl, 256, 1, randinit);
1099                         fclose(randinit);
1100                 }
1101         }
1102         fr_randinit(&randctx, 1);
1103 #endif
1104
1105         req->id = id;
1106
1107         /*
1108          *      Strip port from hostname if needed.
1109          */
1110         if ((p = strchr(argv[1], ':')) != NULL) {
1111                 *p++ = 0;
1112                 port = atoi(p);
1113         }
1114
1115         /*
1116          *      See what kind of request we want to send.
1117          */
1118         if (strcmp(argv[2], "auth") == 0) {
1119                 if (port == 0) port = getport("radius");
1120                 if (port == 0) port = PW_AUTH_UDP_PORT;
1121                 req->code = PW_AUTHENTICATION_REQUEST;
1122
1123         } else if (strcmp(argv[2], "acct") == 0) {
1124                 if (port == 0) port = getport("radacct");
1125                 if (port == 0) port = PW_ACCT_UDP_PORT;
1126                 req->code = PW_ACCOUNTING_REQUEST;
1127                 do_summary = 0;
1128
1129         } else if (strcmp(argv[2], "status") == 0) {
1130                 if (port == 0) port = getport("radius");
1131                 if (port == 0) port = PW_AUTH_UDP_PORT;
1132                 req->code = PW_STATUS_SERVER;
1133
1134         } else if (strcmp(argv[2], "disconnect") == 0) {
1135                 if (port == 0) port = PW_POD_UDP_PORT;
1136                 req->code = PW_DISCONNECT_REQUEST;
1137
1138         } else if (isdigit((int) argv[2][0])) {
1139                 if (port == 0) port = getport("radius");
1140                 if (port == 0) port = PW_AUTH_UDP_PORT;
1141                 req->code = atoi(argv[2]);
1142         } else {
1143                 usage();
1144         }
1145
1146         /*
1147          *      Resolve hostname.
1148          */
1149         req->dst_port = port;
1150         if (ip_hton(argv[1], AF_INET, &req->dst_ipaddr) < 0) {
1151                 fprintf(stderr, "radclient: Failed to find IP address for host %s\n", argv[1]);
1152                 exit(1);
1153         }
1154
1155         /*
1156          *      Add the secret.
1157          */
1158         if (argv[3]) secret = argv[3];
1159
1160         /*
1161          *      Read valuepairs.
1162          *      Maybe read them, from stdin, if there's no
1163          *      filename, or if the filename is '-'.
1164          */
1165         if (filename && (strcmp(filename, "-") != 0)) {
1166                 fp = fopen(filename, "r");
1167                 if (!fp) {
1168                         fprintf(stderr, "radclient: Error opening %s: %s\n",
1169                                 filename, strerror(errno));
1170                         exit(1);
1171                 }
1172         } else {
1173                 fp = stdin;
1174         }
1175
1176         /*
1177          *      Send request.
1178          */
1179         if ((req->sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1180                 perror("radclient: socket: ");
1181                 exit(1);
1182         }
1183
1184         while(!filedone) {
1185                 if(req->vps) pairfree(&req->vps);
1186
1187                 if ((req->vps = readvp2(fp, &filedone, "radeapclient:"))
1188                     == NULL) {
1189                         break;
1190                 }
1191
1192                 sendrecv_eap(req);
1193         }
1194
1195         if(do_summary) {
1196                 printf("\n\t   Total approved auths:  %d\n", totalapp);
1197                 printf("\t     Total denied auths:  %d\n", totaldeny);
1198         }
1199         return 0;
1200 }
1201
1202 /*
1203  * given a radius request with some attributes in the EAP range, build
1204  * them all into a single EAP-Message body.
1205  *
1206  * Note that this function will build multiple EAP-Message bodies
1207  * if there are multiple eligible EAP-types. This is incorrect, as the
1208  * recipient will in fact concatenate them.
1209  *
1210  * XXX - we could break the loop once we process one type. Maybe this
1211  *       just deserves an assert?
1212  *
1213  */
1214 static void map_eap_types(RADIUS_PACKET *req)
1215 {
1216         VALUE_PAIR *vp, *vpnext;
1217         int id, eapcode;
1218         EAP_PACKET ep;
1219         int eap_type;
1220
1221         vp = pairfind(req->vps, ATTRIBUTE_EAP_ID, 0);
1222         if(vp == NULL) {
1223                 id = ((int)getpid() & 0xff);
1224         } else {
1225                 id = vp->vp_integer;
1226         }
1227
1228         vp = pairfind(req->vps, ATTRIBUTE_EAP_CODE, 0);
1229         if(vp == NULL) {
1230                 eapcode = PW_EAP_REQUEST;
1231         } else {
1232                 eapcode = vp->vp_integer;
1233         }
1234
1235
1236         for(vp = req->vps; vp != NULL; vp = vpnext) {
1237                 /* save it in case it changes! */
1238                 vpnext = vp->next;
1239
1240                 if(vp->attribute >= ATTRIBUTE_EAP_BASE &&
1241                    vp->attribute < ATTRIBUTE_EAP_BASE+256) {
1242                         break;
1243                 }
1244         }
1245
1246         if(vp == NULL) {
1247                 return;
1248         }
1249
1250         eap_type = vp->attribute - ATTRIBUTE_EAP_BASE;
1251
1252         switch(eap_type) {
1253         case PW_EAP_IDENTITY:
1254         case PW_EAP_NOTIFICATION:
1255         case PW_EAP_NAK:
1256         case PW_EAP_MD5:
1257         case PW_EAP_OTP:
1258         case PW_EAP_GTC:
1259         case PW_EAP_TLS:
1260         case PW_EAP_LEAP:
1261         case PW_EAP_TTLS:
1262         case PW_EAP_PEAP:
1263         default:
1264                 /*
1265                  * no known special handling, it is just encoded as an
1266                  * EAP-message with the given type.
1267                  */
1268
1269                 /* nuke any existing EAP-Messages */
1270                 pairdelete(&req->vps, PW_EAP_MESSAGE, 0);
1271
1272                 memset(&ep, 0, sizeof(ep));
1273                 ep.code = eapcode;
1274                 ep.id   = id;
1275                 ep.type.type = eap_type;
1276                 ep.type.length = vp->length;
1277                 ep.type.data = malloc(vp->length);
1278                 memcpy(ep.type.data,vp->vp_octets, vp->length);
1279                 eap_basic_compose(req, &ep);
1280         }
1281 }
1282
1283 /*
1284  * given a radius request with an EAP-Message body, decode it specific
1285  * attributes.
1286  */
1287 static void unmap_eap_types(RADIUS_PACKET *rep)
1288 {
1289         VALUE_PAIR *eap1;
1290         eap_packet_t *e;
1291         int len;
1292         int type;
1293
1294         /* find eap message */
1295         e = eap_vp2packet(rep->vps);
1296
1297         /* nothing to do! */
1298         if(e == NULL) return;
1299
1300         /* create EAP-ID and EAP-CODE attributes to start */
1301         eap1 = paircreate(ATTRIBUTE_EAP_ID, 0, PW_TYPE_INTEGER);
1302         eap1->vp_integer = e->id;
1303         pairadd(&(rep->vps), eap1);
1304
1305         eap1 = paircreate(ATTRIBUTE_EAP_CODE, 0, PW_TYPE_INTEGER);
1306         eap1->vp_integer = e->code;
1307         pairadd(&(rep->vps), eap1);
1308
1309         switch(e->code)
1310         {
1311         default:
1312         case PW_EAP_SUCCESS:
1313         case PW_EAP_FAILURE:
1314                 /* no data */
1315                 break;
1316
1317         case PW_EAP_REQUEST:
1318         case PW_EAP_RESPONSE:
1319                 /* there is a type field, which we use to create
1320                  * a new attribute */
1321
1322                 /* the length was decode already into the attribute
1323                  * length, and was checked already. Network byte
1324                  * order, just pull it out using math.
1325                  */
1326                 len = e->length[0]*256 + e->length[1];
1327
1328                 /* verify the length is big enough to hold type */
1329                 if(len < 5)
1330                 {
1331                         free(e);
1332                         return;
1333                 }
1334
1335                 type = e->data[0];
1336
1337                 type += ATTRIBUTE_EAP_BASE;
1338                 len -= 5;
1339
1340                 if(len > MAX_STRING_LEN) {
1341                         len = MAX_STRING_LEN;
1342                 }
1343
1344                 eap1 = paircreate(type, 0, PW_TYPE_OCTETS);
1345                 memcpy(eap1->vp_strvalue, &e->data[1], len);
1346                 eap1->length = len;
1347                 pairadd(&(rep->vps), eap1);
1348                 break;
1349         }
1350
1351         free(e);
1352         return;
1353 }
1354
1355 static int map_eapsim_types(RADIUS_PACKET *r)
1356 {
1357         EAP_PACKET ep;
1358         int ret;
1359
1360         memset(&ep, 0, sizeof(ep));
1361         ret = map_eapsim_basictypes(r, &ep);
1362         if(ret != 1) {
1363                 return ret;
1364         }
1365         eap_basic_compose(r, &ep);
1366
1367         return 1;
1368 }
1369
1370 static int unmap_eapsim_types(RADIUS_PACKET *r)
1371 {
1372         VALUE_PAIR             *esvp;
1373
1374         esvp = pairfind(r->vps, ATTRIBUTE_EAP_BASE+PW_EAP_SIM, 0);
1375         if (esvp == NULL) {
1376                 radlog(L_ERR, "eap: EAP-Sim attribute not found");
1377                 return 0;
1378         }
1379
1380         return unmap_eapsim_basictypes(r, esvp->vp_octets, esvp->length);
1381 }
1382
1383 #ifdef TEST_CASE
1384
1385 #include <assert.h>
1386
1387 const char *radius_dir = RADDBDIR;
1388
1389 int radlog(int lvl, const char *msg, ...)
1390 {
1391         va_list ap;
1392         int r;
1393
1394         va_start(ap, msg);
1395         r = vfprintf(stderr, msg, ap);
1396         va_end(ap);
1397         fputc('\n', stderr);
1398
1399         return r;
1400 }
1401
1402 main(int argc, char *argv[])
1403 {
1404         int filedone;
1405         RADIUS_PACKET *req,*req2;
1406         VALUE_PAIR *vp, *vpkey, *vpextra;
1407         extern unsigned int sha1_data_problems;
1408
1409         req = NULL;
1410         req2 = NULL;
1411         filedone = 0;
1412
1413         if(argc>1) {
1414           sha1_data_problems = 1;
1415         }
1416
1417         if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
1418                 fr_perror("radclient");
1419                 return 1;
1420         }
1421
1422         if ((req = rad_alloc(1)) == NULL) {
1423                 fr_perror("radclient");
1424                 exit(1);
1425         }
1426
1427         if ((req2 = rad_alloc(1)) == NULL) {
1428                 fr_perror("radclient");
1429                 exit(1);
1430         }
1431
1432         while(!filedone) {
1433                 if(req->vps) pairfree(&req->vps);
1434                 if(req2->vps) pairfree(&req2->vps);
1435
1436                 if ((req->vps = readvp2(stdin, &filedone, "eapsimlib:")) == NULL) {
1437                         break;
1438                 }
1439
1440                 if (fr_debug_flag > 1) {
1441                         printf("\nRead:\n");
1442                         vp_printlist(stdout, req->vps);
1443                 }
1444
1445                 map_eapsim_types(req);
1446                 map_eap_types(req);
1447
1448                 if (fr_debug_flag > 1) {
1449                         printf("Mapped to:\n");
1450                         vp_printlist(stdout, req->vps);
1451                 }
1452
1453                 /* find the EAP-Message, copy it to req2 */
1454                 vp = paircopy2(req->vps, PW_EAP_MESSAGE);
1455
1456                 if(vp == NULL) continue;
1457
1458                 pairadd(&req2->vps, vp);
1459
1460                 /* only call unmap for sim types here */
1461                 unmap_eap_types(req2);
1462                 unmap_eapsim_types(req2);
1463
1464                 if (fr_debug_flag > 1) {
1465                         printf("Unmapped to:\n");
1466                         vp_printlist(stdout, req2->vps);
1467                 }
1468
1469                 vp = pairfind(req2->vps,
1470                               ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_MAC);
1471                 vpkey   = pairfind(req->vps, ATTRIBUTE_EAP_SIM_KEY);
1472                 vpextra = pairfind(req->vps, ATTRIBUTE_EAP_SIM_EXTRA);
1473
1474                 if(vp != NULL && vpkey != NULL && vpextra!=NULL) {
1475                         uint8_t calcmac[16];
1476
1477                         /* find the EAP-Message, copy it to req2 */
1478
1479                         memset(calcmac, 0, sizeof(calcmac));
1480                         printf("Confirming MAC...");
1481                         if(eapsim_checkmac(req2->vps, vpkey->vp_strvalue,
1482                                            vpextra->vp_strvalue, vpextra->length,
1483                                            calcmac)) {
1484                                 printf("succeed\n");
1485                         } else {
1486                                 int i, j;
1487
1488                                 printf("calculated MAC (");
1489                                 for (i = 0; i < 20; i++) {
1490                                         if(j==4) {
1491                                                 printf("_");
1492                                                 j=0;
1493                                         }
1494                                         j++;
1495
1496                                         printf("%02x", calcmac[i]);
1497                                 }
1498                                 printf(" did not match\n");
1499                         }
1500                 }
1501
1502                 fflush(stdout);
1503         }
1504 }
1505 #endif
1506