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