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