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