Massively cleaned up #include's, so they're in a consistent
[freeradius.git] / src / modules / rlm_eap / radeapclient.c
1 /*
2  * radeapclient.c       EAP specific radius packet debug tool.
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2000,2006  The FreeRADIUS server project
21  * Copyright 2000  Miquel van Smoorenburg <miquels@cistron.nl>
22  * Copyright 2000  Alan DeKok <aland@ox.org>
23  */
24
25 #include <freeradius-devel/ident.h>
26 RCSID("$Id$")
27
28 #include <freeradius-devel/libradius.h>
29
30 #include <ctype.h>
31
32 #if HAVE_GETOPT_H
33 #       include <getopt.h>
34 #endif
35
36 #include <freeradius-devel/conf.h>
37 #include <freeradius-devel/radpaths.h>
38 #include <freeradius-devel/md5.h>
39
40 #include "eap_types.h"
41 #include "eap_sim.h"
42
43 extern int sha1_data_problems;
44
45 static int retries = 10;
46 static float timeout = 3;
47 static const char *secret = NULL;
48 static int do_output = 1;
49 static int do_summary = 0;
50 static int filedone = 0;
51 static int totalapp = 0;
52 static int totaldeny = 0;
53 static char filesecret[256];
54 const char *radius_dir = RADDBDIR;
55 const char *progname = "radeapclient";
56 /* lrad_randctx randctx; */
57
58
59 radlog_dest_t radlog_dest = RADLOG_STDERR;
60 const char *radlog_dir = NULL;
61 int debug_flag = 0;
62 struct main_config_t mainconfig;
63 char password[256];
64
65 struct eapsim_keys eapsim_mk;
66
67 static void NEVER_RETURNS usage(void)
68 {
69         fprintf(stderr, "Usage: radeapclient [options] server[:port] <command> [<secret>]\n");
70
71         fprintf(stderr, "  <command>    One of auth, acct, status, or disconnect.\n");
72         fprintf(stderr, "  -c count    Send each packet 'count' times.\n");
73         fprintf(stderr, "  -d raddb    Set dictionary directory.\n");
74         fprintf(stderr, "  -f file     Read packets from file, not stdin.\n");
75         fprintf(stderr, "  -r retries  If timeout, retry sending the packet 'retries' times.\n");
76         fprintf(stderr, "  -t timeout  Wait 'timeout' seconds before retrying (may be a floating point number).\n");
77         fprintf(stderr, "  -i id       Set request id to 'id'.  Values may be 0..255\n");
78         fprintf(stderr, "  -S file     read secret from file, not command line.\n");
79         fprintf(stderr, "  -q          Do not print anything out.\n");
80         fprintf(stderr, "  -s          Print out summary information of auth results.\n");
81         fprintf(stderr, "  -v          Show program version information.\n");
82         fprintf(stderr, "  -x          Debugging mode.\n");
83
84         exit(1);
85 }
86
87 int radlog(int lvl, const char *msg, ...)
88 {
89         va_list ap;
90         int r;
91
92         r = lvl; /* shut up compiler */
93
94         va_start(ap, msg);
95         r = vfprintf(stderr, msg, ap);
96         va_end(ap);
97         fputc('\n', stderr);
98
99         return r;
100 }
101
102 int log_debug(const char *msg, ...)
103 {
104         va_list ap;
105         int r;
106
107         va_start(ap, msg);
108         r = vfprintf(stderr, msg, ap);
109         va_end(ap);
110         fputc('\n', stderr);
111
112         return r;
113 }
114
115 static int getport(const char *name)
116 {
117         struct  servent         *svp;
118
119         svp = getservbyname (name, "udp");
120         if (!svp) {
121                 return 0;
122         }
123
124         return ntohs(svp->s_port);
125 }
126
127 static int send_packet(RADIUS_PACKET *req, RADIUS_PACKET **rep)
128 {
129         int i;
130         struct timeval  tv;
131
132         for (i = 0; i < retries; i++) {
133                 fd_set          rdfdesc;
134
135                 rad_send(req, NULL, secret);
136
137                 /* And wait for reply, timing out as necessary */
138                 FD_ZERO(&rdfdesc);
139                 FD_SET(req->sockfd, &rdfdesc);
140
141                 tv.tv_sec = (int)timeout;
142                 tv.tv_usec = 1000000 * (timeout - (int) timeout);
143
144                 /* Something's wrong if we don't get exactly one fd. */
145                 if (select(req->sockfd + 1, &rdfdesc, NULL, NULL, &tv) != 1) {
146                         continue;
147                 }
148
149                 *rep = rad_recv(req->sockfd);
150                 if (*rep != NULL) {
151                         /*
152                          *      If we get a response from a machine
153                          *      which we did NOT send a request to,
154                          *      then complain.
155                          */
156                         if (((*rep)->src_ipaddr.af != req->dst_ipaddr.af) ||
157                             (memcmp(&(*rep)->src_ipaddr.ipaddr,
158                                     &req->dst_ipaddr.ipaddr,
159                                     ((req->dst_ipaddr.af == AF_INET ? /* AF_INET6? */
160                                       sizeof(req->dst_ipaddr.ipaddr.ip4addr) : /* FIXME: AF_INET6 */
161                                       sizeof(req->dst_ipaddr.ipaddr.ip6addr)))) != 0) ||
162                             ((*rep)->src_port != req->dst_port)) {
163                                 char src[128], dst[128];
164
165                                 ip_ntoh(&(*rep)->src_ipaddr, src, sizeof(src));
166                                 ip_ntoh(&req->dst_ipaddr, dst, sizeof(dst));
167                                 fprintf(stderr, "radclient: ERROR: Sent request to host %s port %d, got response from host %s port %d\n!",
168                                         dst, req->dst_port,
169                                         src, (*rep)->src_port);
170                                 exit(1);
171                         }
172                         break;
173                 } else {        /* NULL: couldn't receive the packet */
174                         librad_perror("radclient:");
175                         exit(1);
176                 }
177         }
178
179         /* No response or no data read (?) */
180         if (i == retries) {
181                 fprintf(stderr, "radclient: no response from server\n");
182                 exit(1);
183         }
184
185         /*
186          *      FIXME: Discard the packet & listen for another.
187          *
188          *      Hmm... we should really be using eapol_test, which does
189          *      a lot more than radeapclient.
190          */
191         if (rad_verify(*rep, req, secret) != 0) {
192                 librad_perror("rad_verify");
193                 exit(1);
194         }
195
196         if (rad_decode(*rep, req, secret) != 0) {
197                 librad_perror("rad_decode");
198                 exit(1);
199         }
200
201         /* libradius debug already prints out the value pairs for us */
202         if (!librad_debug && do_output) {
203                 printf("Received response ID %d, code %d, length = %d\n",
204                                 (*rep)->id, (*rep)->code, (*rep)->data_len);
205                 vp_printlist(stdout, (*rep)->vps);
206         }
207         if((*rep)->code == PW_AUTHENTICATION_ACK) {
208                 totalapp++;
209         } else {
210                 totaldeny++;
211         }
212
213         return 0;
214 }
215
216 static void cleanresp(RADIUS_PACKET *resp)
217 {
218         VALUE_PAIR *vpnext, *vp, **last;
219
220
221         /*
222          * maybe should just copy things we care about, or keep
223          * a copy of the original input and start from there again?
224          */
225         pairdelete(&resp->vps, PW_EAP_MESSAGE);
226         pairdelete(&resp->vps, ATTRIBUTE_EAP_BASE+PW_EAP_IDENTITY);
227
228         last = &resp->vps;
229         for(vp = *last; vp != NULL; vp = vpnext)
230         {
231                 vpnext = vp->next;
232
233                 if((vp->attribute > ATTRIBUTE_EAP_BASE &&
234                     vp->attribute <= ATTRIBUTE_EAP_BASE+256) ||
235                    (vp->attribute > ATTRIBUTE_EAP_SIM_BASE &&
236                     vp->attribute <= ATTRIBUTE_EAP_SIM_BASE+256))
237                 {
238                         *last = vpnext;
239                         pairbasicfree(vp);
240                 } else {
241                         last = &vp->next;
242                 }
243         }
244 }
245
246 /*
247  * we got an EAP-Request/Sim/Start message in a legal state.
248  *
249  * pick a supported version, put it into the reply, and insert a nonce.
250  */
251 static int process_eap_start(RADIUS_PACKET *req,
252                              RADIUS_PACKET *rep)
253 {
254         VALUE_PAIR *vp, *newvp;
255         VALUE_PAIR *anyidreq_vp, *fullauthidreq_vp, *permanentidreq_vp;
256         uint16_t *versions, selectedversion;
257         unsigned int i,versioncount;
258
259         /* form new response clear of any EAP stuff */
260         cleanresp(rep);
261
262         if((vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_VERSION_LIST)) == NULL) {
263                 fprintf(stderr, "illegal start message has no VERSION_LIST\n");
264                 return 0;
265         }
266
267         versions = (uint16_t *)vp->vp_strvalue;
268
269         /* verify that the attribute length is big enough for a length field */
270         if(vp->length < 4)
271         {
272                 fprintf(stderr, "start message has illegal VERSION_LIST. Too short: %d\n", vp->length);
273                 return 0;
274         }
275
276         versioncount = ntohs(versions[0])/2;
277         /* verify that the attribute length is big enough for the given number
278          * of versions present.
279          */
280         if((unsigned)vp->length <= (versioncount*2 + 2))
281         {
282                 fprintf(stderr, "start message is too short. Claimed %d versions does not fit in %d bytes\n", versioncount, vp->length);
283                 return 0;
284         }
285
286         /*
287          * record the versionlist for the MK calculation.
288          */
289         eapsim_mk.versionlistlen = versioncount*2;
290         memcpy(eapsim_mk.versionlist, (unsigned char *)(versions+1),
291                eapsim_mk.versionlistlen);
292
293         /* walk the version list, and pick the one we support, which
294          * at present, is 1, EAP_SIM_VERSION.
295          */
296         selectedversion=0;
297         for(i=0; i < versioncount; i++)
298         {
299                 if(ntohs(versions[i+1]) == EAP_SIM_VERSION)
300                 {
301                         selectedversion=EAP_SIM_VERSION;
302                         break;
303                 }
304         }
305         if(selectedversion == 0)
306         {
307                 fprintf(stderr, "eap-sim start message. No compatible version found. We need %d\n", EAP_SIM_VERSION);
308                 for(i=0; i < versioncount; i++)
309                 {
310                         fprintf(stderr, "\tfound version %d\n",
311                                 ntohs(versions[i+1]));
312                 }
313         }
314
315         /*
316          * now make sure that we have only FULLAUTH_ID_REQ.
317          * I think that it actually might not matter - we can answer in
318          * anyway we like, but it is illegal to have more than one
319          * present.
320          */
321         anyidreq_vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_ANY_ID_REQ);
322         fullauthidreq_vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_FULLAUTH_ID_REQ);
323         permanentidreq_vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_PERMANENT_ID_REQ);
324
325         if(fullauthidreq_vp == NULL ||
326            anyidreq_vp != NULL ||
327            permanentidreq_vp != NULL) {
328                 fprintf(stderr, "start message has %sanyidreq, %sfullauthid and %spermanentid. Illegal combination.\n",
329                         (anyidreq_vp != NULL ? "a " : "no "),
330                         (fullauthidreq_vp != NULL ? "a " : "no "),
331                         (permanentidreq_vp != NULL ? "a " : "no "));
332                 return 0;
333         }
334
335         /* okay, we have just any_id_req there, so fill in response */
336
337         /* mark the subtype as being EAP-SIM/Response/Start */
338         newvp = paircreate(ATTRIBUTE_EAP_SIM_SUBTYPE, PW_TYPE_INTEGER);
339         newvp->lvalue = eapsim_start;
340         pairreplace(&(rep->vps), newvp);
341
342         /* insert selected version into response. */
343         newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_SELECTED_VERSION,
344                            PW_TYPE_OCTETS);
345         versions = (uint16_t *)newvp->vp_strvalue;
346         versions[0] = htons(selectedversion);
347         newvp->length = 2;
348         pairreplace(&(rep->vps), newvp);
349
350         /* record the selected version */
351         memcpy(eapsim_mk.versionselect, (unsigned char *)versions, 2);
352
353         vp = newvp = NULL;
354
355         {
356                 uint32_t nonce[4];
357                 /*
358                  * insert a nonce_mt that we make up.
359                  */
360                 newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_NONCE_MT,
361                                    PW_TYPE_OCTETS);
362                 newvp->vp_octets[0]=0;
363                 newvp->vp_octets[1]=0;
364                 newvp->length = 18;  /* 16 bytes of nonce + padding */
365
366                 nonce[0]=lrad_rand();
367                 nonce[1]=lrad_rand();
368                 nonce[2]=lrad_rand();
369                 nonce[3]=lrad_rand();
370                 memcpy(&newvp->vp_octets[2], nonce, 16);
371                 pairreplace(&(rep->vps), newvp);
372
373                 /* also keep a copy of the nonce! */
374                 memcpy(eapsim_mk.nonce_mt, nonce, 16);
375         }
376
377         {
378                 uint16_t *pidlen, idlen;
379
380                 /*
381                  * insert the identity here.
382                  */
383                 vp = pairfind(rep->vps, PW_USER_NAME);
384                 if(vp == NULL)
385                 {
386                         fprintf(stderr, "eap-sim: We need to have a User-Name attribute!\n");
387                         return 0;
388                 }
389                 newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_IDENTITY,
390                                    PW_TYPE_OCTETS);
391                 idlen = strlen(vp->vp_strvalue);
392                 pidlen = (uint16_t *)newvp->vp_strvalue;
393                 *pidlen = htons(idlen);
394                 newvp->length = idlen + 2;
395
396                 memcpy(&newvp->vp_strvalue[2], vp->vp_strvalue, idlen);
397                 pairreplace(&(rep->vps), newvp);
398
399                 /* record it */
400                 memcpy(eapsim_mk.identity, vp->vp_strvalue, idlen);
401                 eapsim_mk.identitylen = idlen;
402         }
403
404         return 1;
405 }
406
407 /*
408  * we got an EAP-Request/Sim/Challenge message in a legal state.
409  *
410  * use the RAND challenge to produce the SRES result, and then
411  * use that to generate a new MAC.
412  *
413  * for the moment, we ignore the RANDs, then just plug in the SRES
414  * values.
415  *
416  */
417 static int process_eap_challenge(RADIUS_PACKET *req,
418                                  RADIUS_PACKET *rep)
419 {
420         VALUE_PAIR *newvp;
421         VALUE_PAIR *mac, *randvp;
422         VALUE_PAIR *sres1,*sres2,*sres3;
423         VALUE_PAIR *Kc1, *Kc2, *Kc3;
424         uint8_t calcmac[20];
425
426         /* look for the AT_MAC and the challenge data */
427         mac   = pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_MAC);
428         randvp= pairfind(req->vps, ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_RAND);
429         if(mac == NULL || rand == NULL) {
430                 fprintf(stderr, "radeapclient: challenge message needs to contain RAND and MAC\n");
431                 return 0;
432         }
433
434         /*
435          * compare RAND with randX, to verify this is the right response
436          * to this challenge.
437          */
438         {
439           VALUE_PAIR *randcfgvp[3];
440           unsigned char *randcfg[3];
441
442           randcfg[0] = &randvp->vp_strvalue[2];
443           randcfg[1] = &randvp->vp_strvalue[2+EAPSIM_RAND_SIZE];
444           randcfg[2] = &randvp->vp_strvalue[2+EAPSIM_RAND_SIZE*2];
445
446           randcfgvp[0] = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_RAND1);
447           randcfgvp[1] = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_RAND2);
448           randcfgvp[2] = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_RAND3);
449
450           if(randcfgvp[0] == NULL ||
451              randcfgvp[1] == NULL ||
452              randcfgvp[2] == NULL) {
453             fprintf(stderr, "radeapclient: needs to have rand1, 2 and 3 set.\n");
454             return 0;
455           }
456
457           if(memcmp(randcfg[0], randcfgvp[0]->vp_strvalue, EAPSIM_RAND_SIZE)!=0 ||
458              memcmp(randcfg[1], randcfgvp[1]->vp_strvalue, EAPSIM_RAND_SIZE)!=0 ||
459              memcmp(randcfg[2], randcfgvp[2]->vp_strvalue, EAPSIM_RAND_SIZE)!=0) {
460             int rnum,i,j;
461
462             fprintf(stderr, "radeapclient: one of rand 1,2,3 didn't match\n");
463             for(rnum = 0; rnum < 3; rnum++) {
464               fprintf(stderr, "received   rand %d: ", rnum);
465               j=0;
466               for (i = 0; i < EAPSIM_RAND_SIZE; i++) {
467                 if(j==4) {
468                   printf("_");
469                   j=0;
470                 }
471                 j++;
472
473                 fprintf(stderr, "%02x", randcfg[rnum][i]);
474               }
475               fprintf(stderr, "\nconfigured rand %d: ", rnum);
476               j=0;
477               for (i = 0; i < EAPSIM_RAND_SIZE; i++) {
478                 if(j==4) {
479                   printf("_");
480                   j=0;
481                 }
482                 j++;
483
484                 fprintf(stderr, "%02x", randcfgvp[rnum]->vp_strvalue[i]);
485               }
486               fprintf(stderr, "\n");
487             }
488             return 0;
489           }
490         }
491
492         /*
493          * now dig up the sres values from the response packet,
494          * which were put there when we read things in.
495          *
496          * Really, they should be calculated from the RAND!
497          *
498          */
499         sres1 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_SRES1);
500         sres2 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_SRES2);
501         sres3 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_SRES3);
502
503         if(sres1 == NULL ||
504            sres2 == NULL ||
505            sres3 == NULL) {
506                 fprintf(stderr, "radeapclient: needs to have sres1, 2 and 3 set.\n");
507                 return 0;
508         }
509         memcpy(eapsim_mk.sres[0], sres1->vp_strvalue, sizeof(eapsim_mk.sres[0]));
510         memcpy(eapsim_mk.sres[1], sres2->vp_strvalue, sizeof(eapsim_mk.sres[1]));
511         memcpy(eapsim_mk.sres[2], sres3->vp_strvalue, sizeof(eapsim_mk.sres[2]));
512
513         Kc1 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_KC1);
514         Kc2 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_KC2);
515         Kc3 = pairfind(rep->vps, ATTRIBUTE_EAP_SIM_KC3);
516
517         if(Kc1 == NULL ||
518            Kc2 == NULL ||
519            Kc3 == NULL) {
520                 fprintf(stderr, "radeapclient: needs to have Kc1, 2 and 3 set.\n");
521                 return 0;
522         }
523         memcpy(eapsim_mk.Kc[0], Kc1->vp_strvalue, sizeof(eapsim_mk.Kc[0]));
524         memcpy(eapsim_mk.Kc[1], Kc2->vp_strvalue, sizeof(eapsim_mk.Kc[1]));
525         memcpy(eapsim_mk.Kc[2], Kc3->vp_strvalue, sizeof(eapsim_mk.Kc[2]));
526
527         /* all set, calculate keys */
528         eapsim_calculate_keys(&eapsim_mk);
529
530         if(debug_flag) {
531           eapsim_dump_mk(&eapsim_mk);
532         }
533
534         /* verify the MAC, now that we have all the keys. */
535         if(eapsim_checkmac(req->vps, eapsim_mk.K_aut,
536                            eapsim_mk.nonce_mt, sizeof(eapsim_mk.nonce_mt),
537                            calcmac)) {
538                 printf("MAC check succeed\n");
539         } else {
540                 int i, j;
541                 j=0;
542                 printf("calculated MAC (");
543                 for (i = 0; i < 20; i++) {
544                         if(j==4) {
545                                 printf("_");
546                                 j=0;
547                         }
548                         j++;
549
550                         printf("%02x", calcmac[i]);
551                 }
552                 printf(" did not match\n");
553                 return 0;
554         }
555
556         /* form new response clear of any EAP stuff */
557         cleanresp(rep);
558
559         /* mark the subtype as being EAP-SIM/Response/Start */
560         newvp = paircreate(ATTRIBUTE_EAP_SIM_SUBTYPE, PW_TYPE_INTEGER);
561         newvp->lvalue = eapsim_challenge;
562         pairreplace(&(rep->vps), newvp);
563
564         /*
565          * fill the SIM_MAC with a field that will in fact get appended
566          * to the packet before the MAC is calculated
567          */
568         newvp = paircreate(ATTRIBUTE_EAP_SIM_BASE+PW_EAP_SIM_MAC,
569                            PW_TYPE_OCTETS);
570         memcpy(newvp->vp_strvalue+EAPSIM_SRES_SIZE*0, sres1->vp_strvalue, EAPSIM_SRES_SIZE);
571         memcpy(newvp->vp_strvalue+EAPSIM_SRES_SIZE*1, sres2->vp_strvalue, EAPSIM_SRES_SIZE);
572         memcpy(newvp->vp_strvalue+EAPSIM_SRES_SIZE*2, sres3->vp_strvalue, EAPSIM_SRES_SIZE);
573         newvp->length = EAPSIM_SRES_SIZE*3;
574         pairreplace(&(rep->vps), newvp);
575
576         newvp = paircreate(ATTRIBUTE_EAP_SIM_KEY, PW_TYPE_OCTETS);
577         memcpy(newvp->vp_strvalue,    eapsim_mk.K_aut, EAPSIM_AUTH_SIZE);
578         newvp->length = EAPSIM_AUTH_SIZE;
579         pairreplace(&(rep->vps), newvp);
580
581         return 1;
582 }
583
584 /*
585  * this code runs the EAP-SIM client state machine.
586  * the *request* is from the server.
587  * the *reponse* is to the server.
588  *
589  */
590 static int respond_eap_sim(RADIUS_PACKET *req,
591                            RADIUS_PACKET *resp)
592 {
593         enum eapsim_clientstates state, newstate;
594         enum eapsim_subtype subtype;
595         VALUE_PAIR *vp, *statevp, *radstate, *eapid;
596         char statenamebuf[32], subtypenamebuf[32];
597
598         if ((radstate = paircopy2(req->vps, PW_STATE)) == NULL)
599         {
600                 return 0;
601         }
602
603         if ((eapid = paircopy2(req->vps, ATTRIBUTE_EAP_ID)) == NULL)
604         {
605                 return 0;
606         }
607
608         /* first, dig up the state from the request packet, setting
609          * outselves to be in EAP-SIM-Start state if there is none.
610          */
611
612         if((statevp = pairfind(resp->vps, ATTRIBUTE_EAP_SIM_STATE)) == NULL)
613         {
614                 /* must be initial request */
615                 statevp = paircreate(ATTRIBUTE_EAP_SIM_STATE, PW_TYPE_INTEGER);
616                 statevp->lvalue = eapsim_client_init;
617                 pairreplace(&(resp->vps), statevp);
618         }
619         state = statevp->lvalue;
620
621         /*
622          * map the attributes, and authenticate them.
623          */
624         unmap_eapsim_types(req);
625
626         printf("<+++ EAP-sim decoded packet:\n");
627         vp_printlist(stdout, req->vps);
628
629         if((vp = pairfind(req->vps, ATTRIBUTE_EAP_SIM_SUBTYPE)) == NULL)
630         {
631                 return 0;
632         }
633         subtype = vp->lvalue;
634
635         /*
636          * look for the appropriate state, and process incoming message
637          */
638         switch(state) {
639         case eapsim_client_init:
640                 switch(subtype) {
641                 case eapsim_start:
642                         newstate = process_eap_start(req, resp);
643                         break;
644
645                 case eapsim_challenge:
646                 case eapsim_notification:
647                 case eapsim_reauth:
648                 default:
649                         fprintf(stderr, "radeapclient: sim in state %s message %s is illegal. Reply dropped.\n",
650                                 sim_state2name(state, statenamebuf, sizeof(statenamebuf)),
651                                 sim_subtype2name(subtype, subtypenamebuf, sizeof(subtypenamebuf)));
652                         /* invalid state, drop message */
653                         return 0;
654                 }
655                 break;
656
657         case eapsim_client_start:
658                 switch(subtype) {
659                 case eapsim_start:
660                         /* NOT SURE ABOUT THIS ONE, retransmit, I guess */
661                         newstate = process_eap_start(req, resp);
662                         break;
663
664                 case eapsim_challenge:
665                         newstate = process_eap_challenge(req, resp);
666                         break;
667
668                 default:
669                         fprintf(stderr, "radeapclient: sim in state %s message %s is illegal. Reply dropped.\n",
670                                 sim_state2name(state, statenamebuf, sizeof(statenamebuf)),
671                                 sim_subtype2name(subtype, subtypenamebuf, sizeof(subtypenamebuf)));
672                         /* invalid state, drop message */
673                         return 0;
674                 }
675                 break;
676
677
678         default:
679                 fprintf(stderr, "radeapclient: sim in illegal state %s\n",
680                         sim_state2name(state, statenamebuf, sizeof(statenamebuf)));
681                 return 0;
682         }
683
684         /* copy the eap state object in */
685         pairreplace(&(resp->vps), eapid);
686
687         /* update stete info, and send new packet */
688         map_eapsim_types(resp);
689
690         /* copy the radius state object in */
691         pairreplace(&(resp->vps), radstate);
692
693         statevp->lvalue = newstate;
694         return 1;
695 }
696
697 static int respond_eap_md5(RADIUS_PACKET *req,
698                            RADIUS_PACKET *rep)
699 {
700         VALUE_PAIR *vp, *id, *state;
701         int valuesize, namesize;
702         unsigned char identifier;
703         unsigned char *value;
704         unsigned char *name;
705         MD5_CTX context;
706         char    response[16];
707
708         cleanresp(rep);
709
710         if ((state = paircopy2(req->vps, PW_STATE)) == NULL)
711         {
712                 fprintf(stderr, "radeapclient: no state attribute found\n");
713                 return 0;
714         }
715
716         if ((id = paircopy2(req->vps, ATTRIBUTE_EAP_ID)) == NULL)
717         {
718                 fprintf(stderr, "radeapclient: no EAP-ID attribute found\n");
719                 return 0;
720         }
721         identifier = id->lvalue;
722
723         if ((vp = pairfind(req->vps, ATTRIBUTE_EAP_BASE+PW_EAP_MD5)) == NULL)
724         {
725                 fprintf(stderr, "radeapclient: no EAP-MD5 attribute found\n");
726                 return 0;
727         }
728
729         /* got the details of the MD5 challenge */
730         valuesize = vp->vp_octets[0];
731         value = &vp->vp_octets[1];
732         name  = &vp->vp_octets[valuesize+1];
733         namesize = vp->length - (valuesize + 1);
734
735         /* sanitize items */
736         if(valuesize > vp->length)
737         {
738                 fprintf(stderr, "radeapclient: md5 valuesize if too big (%d > %d)\n",
739                         valuesize, vp->length);
740                 return 0;
741         }
742
743         /* now do the CHAP operation ourself, rather than build the
744          * buffer. We could also call rad_chap_encode, but it wants
745          * a CHAP-Challenge, which we don't want to bother with.
746          */
747         lrad_MD5Init(&context);
748         lrad_MD5Update(&context, &identifier, 1);
749         lrad_MD5Update(&context, password, strlen(password));
750         lrad_MD5Update(&context, value, valuesize);
751         lrad_MD5Final(response, &context);
752
753         vp = paircreate(ATTRIBUTE_EAP_BASE+PW_EAP_MD5, PW_TYPE_OCTETS);
754         vp->vp_octets[0]=16;
755         memcpy(&vp->vp_strvalue[1], response, 16);
756         vp->length = 17;
757
758         pairreplace(&(rep->vps), vp);
759
760         pairreplace(&(rep->vps), id);
761
762         /* copy the state object in */
763         pairreplace(&(rep->vps), state);
764
765         return 1;
766 }
767
768
769
770 static int sendrecv_eap(RADIUS_PACKET *rep)
771 {
772         RADIUS_PACKET *req = NULL;
773         VALUE_PAIR *vp, *vpnext;
774         int tried_eap_md5 = 0;
775
776         /*
777          *      Keep a copy of the the User-Password attribute.
778          */
779         if ((vp = pairfind(rep->vps, PW_CLEARTEXT_PASSWORD)) != NULL) {
780                 strlcpy(password, (char *)vp->vp_strvalue, sizeof(vp->vp_strvalue));
781
782         } else  if ((vp = pairfind(rep->vps, PW_USER_PASSWORD)) != NULL) {
783                 strlcpy(password, (char *)vp->vp_strvalue, sizeof(vp->vp_strvalue));
784                 /*
785                  *      Otherwise keep a copy of the CHAP-Password attribute.
786                  */
787         } else if ((vp = pairfind(rep->vps, PW_CHAP_PASSWORD)) != NULL) {
788                 strlcpy(password, (char *)vp->vp_strvalue, sizeof(vp->vp_strvalue));
789         } else {
790                 *password = '\0';
791         }
792
793  again:
794         rep->id++;
795
796         printf("\n+++> About to send encoded packet:\n");
797         vp_printlist(stdout, rep->vps);
798
799         /*
800          * if there are EAP types, encode them into an EAP-Message
801          *
802          */
803         map_eap_types(rep);
804
805         /*
806          *  Fix up Digest-Attributes issues
807          */
808         for (vp = rep->vps; vp != NULL; vp = vp->next) {
809                 switch (vp->attribute) {
810                 default:
811                         break;
812
813                 case PW_DIGEST_REALM:
814                 case PW_DIGEST_NONCE:
815                 case PW_DIGEST_METHOD:
816                 case PW_DIGEST_URI:
817                 case PW_DIGEST_QOP:
818                 case PW_DIGEST_ALGORITHM:
819                 case PW_DIGEST_BODY_DIGEST:
820                 case PW_DIGEST_CNONCE:
821                 case PW_DIGEST_NONCE_COUNT:
822                 case PW_DIGEST_USER_NAME:
823                         /* overlapping! */
824                         memmove(&vp->vp_strvalue[2], &vp->vp_octets[0], vp->length);
825                         vp->vp_octets[0] = vp->attribute - PW_DIGEST_REALM + 1;
826                         vp->length += 2;
827                         vp->vp_octets[1] = vp->length;
828                         vp->attribute = PW_DIGEST_ATTRIBUTES;
829                         break;
830                 }
831         }
832
833         /*
834          *      If we've already sent a packet, free up the old
835          *      one, and ensure that the next packet has a unique
836          *      ID and authentication vector.
837          */
838         if (rep->data) {
839                 free(rep->data);
840                 rep->data = NULL;
841         }
842
843         librad_md5_calc(rep->vector, rep->vector,
844                         sizeof(rep->vector));
845
846         if (*password != '\0') {
847                 if ((vp = pairfind(rep->vps, PW_CLEARTEXT_PASSWORD)) != NULL) {
848                         strlcpy((char *)vp->vp_strvalue, password, sizeof(vp->vp_strvalue));
849                         vp->length = strlen(password);
850
851                 } else if ((vp = pairfind(rep->vps, PW_USER_PASSWORD)) != NULL) {
852                         strlcpy((char *)vp->vp_strvalue, password, sizeof(vp->vp_strvalue));
853                         vp->length = strlen(password);
854
855                 } else if ((vp = pairfind(rep->vps, PW_CHAP_PASSWORD)) != NULL) {
856                         strlcpy((char *)vp->vp_strvalue, password, sizeof(vp->vp_strvalue));
857                         vp->length = strlen(password);
858
859                         rad_chap_encode(rep, (char *) vp->vp_strvalue, rep->id, vp);
860                         vp->length = 17;
861                 }
862         } /* there WAS a password */
863
864         /* send the response, wait for the next request */
865         send_packet(rep, &req);
866
867         /* okay got back the packet, go and decode the EAP-Message. */
868         unmap_eap_types(req);
869
870         printf("<+++ EAP decoded packet:\n");
871         vp_printlist(stdout, req->vps);
872
873         /* now look for the code type. */
874         for (vp = req->vps; vp != NULL; vp = vpnext) {
875                 vpnext = vp->next;
876
877                 switch (vp->attribute) {
878                 default:
879                         break;
880
881                 case ATTRIBUTE_EAP_BASE+PW_EAP_MD5:
882                         if(respond_eap_md5(req, rep) && tried_eap_md5 < 3)
883                         {
884                                 tried_eap_md5++;
885                                 goto again;
886                         }
887                         break;
888
889                 case ATTRIBUTE_EAP_BASE+PW_EAP_SIM:
890                         if(respond_eap_sim(req, rep))
891                         {
892                                 goto again;
893                         }
894                         break;
895                 }
896         }
897
898         return 1;
899 }
900
901
902 int main(int argc, char **argv)
903 {
904         RADIUS_PACKET *req;
905         char *p;
906         int c;
907         int port = 0;
908         char *filename = NULL;
909         FILE *fp;
910         int count = 1;
911         int id;
912
913         id = ((int)getpid() & 0xff);
914         librad_debug = 0;
915
916         radlog_dest = RADLOG_STDERR;
917
918         while ((c = getopt(argc, argv, "c:d:f:hi:qst:r:S:xXv")) != EOF)
919         {
920                 switch(c) {
921                 case 'c':
922                         if (!isdigit((int) *optarg))
923                                 usage();
924                         count = atoi(optarg);
925                         break;
926                 case 'd':
927                         radius_dir = optarg;
928                         break;
929                 case 'f':
930                         filename = optarg;
931                         break;
932                 case 'q':
933                         do_output = 0;
934                         break;
935                 case 'x':
936                         debug_flag++;
937                         librad_debug++;
938                         break;
939
940                 case 'X':
941 #if 0
942                   sha1_data_problems = 1; /* for debugging only */
943 #endif
944                   break;
945
946
947
948                 case 'r':
949                         if (!isdigit((int) *optarg))
950                                 usage();
951                         retries = atoi(optarg);
952                         break;
953                 case 'i':
954                         if (!isdigit((int) *optarg))
955                                 usage();
956                         id = atoi(optarg);
957                         if ((id < 0) || (id > 255)) {
958                                 usage();
959                         }
960                         break;
961                 case 's':
962                         do_summary = 1;
963                         break;
964                 case 't':
965                         if (!isdigit((int) *optarg))
966                                 usage();
967                         timeout = atof(optarg);
968                         break;
969                 case 'v':
970                         printf("radclient: $Id$ built on " __DATE__ " at " __TIME__ "\n");
971                         exit(0);
972                         break;
973                case 'S':
974                        fp = fopen(optarg, "r");
975                        if (!fp) {
976                                fprintf(stderr, "radclient: Error opening %s: %s\n",
977                                        optarg, strerror(errno));
978                                exit(1);
979                        }
980                        if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
981                                fprintf(stderr, "radclient: Error reading %s: %s\n",
982                                        optarg, strerror(errno));
983                                exit(1);
984                        }
985                        fclose(fp);
986
987                        /* truncate newline */
988                        p = filesecret + strlen(filesecret) - 1;
989                        while ((p >= filesecret) &&
990                               (*p < ' ')) {
991                                *p = '\0';
992                                --p;
993                        }
994
995                        if (strlen(filesecret) < 2) {
996                                fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
997                                exit(1);
998                        }
999                        secret = filesecret;
1000                        break;
1001                 case 'h':
1002                 default:
1003                         usage();
1004                         break;
1005                 }
1006         }
1007         argc -= (optind - 1);
1008         argv += (optind - 1);
1009
1010         if ((argc < 3)  ||
1011             ((secret == NULL) && (argc < 4))) {
1012                 usage();
1013         }
1014
1015         if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
1016                 librad_perror("radclient");
1017                 return 1;
1018         }
1019
1020         if ((req = rad_alloc(1)) == NULL) {
1021                 librad_perror("radclient");
1022                 exit(1);
1023         }
1024
1025 #if 0
1026         {
1027                 FILE *randinit;
1028
1029                 if((randinit = fopen("/dev/urandom", "r")) == NULL)
1030                 {
1031                         perror("/dev/urandom");
1032                 } else {
1033                         fread(randctx.randrsl, 256, 1, randinit);
1034                         fclose(randinit);
1035                 }
1036         }
1037         lrad_randinit(&randctx, 1);
1038 #endif
1039
1040         req->id = id;
1041
1042         /*
1043          *      Strip port from hostname if needed.
1044          */
1045         if ((p = strchr(argv[1], ':')) != NULL) {
1046                 *p++ = 0;
1047                 port = atoi(p);
1048         }
1049
1050         /*
1051          *      See what kind of request we want to send.
1052          */
1053         if (strcmp(argv[2], "auth") == 0) {
1054                 if (port == 0) port = getport("radius");
1055                 if (port == 0) port = PW_AUTH_UDP_PORT;
1056                 req->code = PW_AUTHENTICATION_REQUEST;
1057
1058         } else if (strcmp(argv[2], "acct") == 0) {
1059                 if (port == 0) port = getport("radacct");
1060                 if (port == 0) port = PW_ACCT_UDP_PORT;
1061                 req->code = PW_ACCOUNTING_REQUEST;
1062                 do_summary = 0;
1063
1064         } else if (strcmp(argv[2], "status") == 0) {
1065                 if (port == 0) port = getport("radius");
1066                 if (port == 0) port = PW_AUTH_UDP_PORT;
1067                 req->code = PW_STATUS_SERVER;
1068
1069         } else if (strcmp(argv[2], "disconnect") == 0) {
1070                 if (port == 0) port = PW_POD_UDP_PORT;
1071                 req->code = PW_DISCONNECT_REQUEST;
1072
1073         } else if (isdigit((int) argv[2][0])) {
1074                 if (port == 0) port = getport("radius");
1075                 if (port == 0) port = PW_AUTH_UDP_PORT;
1076                 req->code = atoi(argv[2]);
1077         } else {
1078                 usage();
1079         }
1080
1081         /*
1082          *      Ensure that the configuration is initialized.
1083          */
1084         memset(&mainconfig, 0, sizeof(mainconfig));
1085
1086         /*
1087          *      Resolve hostname.
1088          */
1089         req->dst_port = port;
1090         if (ip_hton(argv[1], AF_INET, &req->dst_ipaddr) < 0) {
1091                 fprintf(stderr, "radclient: Failed to find IP address for host %s\n", argv[1]);
1092                 exit(1);
1093         }
1094
1095         /*
1096          *      Add the secret.
1097          */
1098         if (argv[3]) secret = argv[3];
1099
1100         /*
1101          *      Read valuepairs.
1102          *      Maybe read them, from stdin, if there's no
1103          *      filename, or if the filename is '-'.
1104          */
1105         if (filename && (strcmp(filename, "-") != 0)) {
1106                 fp = fopen(filename, "r");
1107                 if (!fp) {
1108                         fprintf(stderr, "radclient: Error opening %s: %s\n",
1109                                 filename, strerror(errno));
1110                         exit(1);
1111                 }
1112         } else {
1113                 fp = stdin;
1114         }
1115
1116         /*
1117          *      Send request.
1118          */
1119         if ((req->sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1120                 perror("radclient: socket: ");
1121                 exit(1);
1122         }
1123
1124         while(!filedone) {
1125                 if(req->vps) pairfree(&req->vps);
1126
1127                 if ((req->vps = readvp2(fp, &filedone, "radeapclient:"))
1128                     == NULL) {
1129                         break;
1130                 }
1131
1132                 sendrecv_eap(req);
1133         }
1134
1135         if(do_summary) {
1136                 printf("\n\t   Total approved auths:  %d\n", totalapp);
1137                 printf("\t     Total denied auths:  %d\n", totaldeny);
1138         }
1139         return 0;
1140 }