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