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