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