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