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