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