http://downloads.netgear.com/files/GPL/GPL_Source_V361j_DM111PSP_series_consumer_rele...
[bcm963xx.git] / userapps / opensource / ppp / pppoe / auth.c
1 /*
2  * auth.c - PPP authentication and phase control.
3  *
4  * Copyright (c) 1993 The Australian National University.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms are permitted
8  * provided that the above copyright notice and this paragraph are
9  * duplicated in all such forms and that any documentation,
10  * advertising materials, and other materials related to such
11  * distribution and use acknowledge that the software was developed
12  * by the Australian National University.  The name of the University
13  * may not be used to endorse or promote products derived from this
14  * software without specific prior written permission.
15  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18  *
19  * Copyright (c) 1989 Carnegie Mellon University.
20  * All rights reserved.
21  *
22  * Redistribution and use in source and binary forms are permitted
23  * provided that the above copyright notice and this paragraph are
24  * duplicated in all such forms and that any documentation,
25  * advertising materials, and other materials related to such
26  * distribution and use acknowledge that the software was developed
27  * by Carnegie Mellon University.  The name of the
28  * University may not be used to endorse or promote products derived
29  * from this software without specific prior written permission.
30  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
32  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
33  */
34
35 #define RCSID   "$Id: auth.c,v 1.6 2006/11/24 03:33:52 andylin Exp $"
36
37 #include <stdio.h>
38 #include <stddef.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 #include <pwd.h>
42 #include <grp.h>
43 #include <string.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/socket.h>
47 #include <time.h>
48 #include <utmp.h>
49 #include <fcntl.h>
50 #if defined(_PATH_LASTLOG) && defined(_linux_)
51 #include <lastlog.h>
52 #endif
53
54 #include <netdb.h>
55 #include <netinet/in.h>
56 #include <arpa/inet.h>
57
58 // brcm
59 #include <syscall.h>
60 #include <syslog.h>
61 #ifdef USE_PAM
62 #include <security/pam_appl.h>
63 #endif
64
65 #ifdef HAS_SHADOW
66 #include <shadow.h>
67 #ifndef PW_PPP
68 #define PW_PPP PW_LOGIN
69 #endif
70 #endif
71
72 #include "pppd.h"
73 #include "fsm.h"
74 #include "lcp.h"
75 #include "ipcp.h"
76 #include "upap.h"
77 #include "chap.h"
78 #ifdef CBCP_SUPPORT
79 #include "cbcp.h"
80 #endif
81 #include "pathnames.h"
82
83 static const char rcsid[] = RCSID;
84 #if defined(ONE_AND_ONE)
85 extern int auth_again;  //defined in main.c
86 extern int is1n1;
87 #endif
88 extern int isp_1n1;
89
90 /* Bits in scan_authfile return value */
91 #define NONWILD_SERVER  1
92 #define NONWILD_CLIENT  2
93
94 #define ISWILD(word)    (word[0] == '*' && word[1] == 0)
95
96 //#if !defined(INCLUDE_EMBHTTPD)
97 extern glbppppid;
98 //#endif
99 #if defined(ODM_LANG_LLL)
100 extern int ppp_session;
101 extern int got_ppp_down;
102 #endif
103
104 /* The name by which the peer authenticated itself to us. */
105 char peer_authname[MAXNAMELEN];
106
107 /* Records which authentication operations haven't completed yet. */
108 static int auth_pending[NUM_PPP];
109
110 /* Set if we have successfully called plogin() */
111 static int logged_in;
112
113 /* List of addresses which the peer may use. */
114 static struct permitted_ip *addresses[NUM_PPP];
115
116 /* Wordlist giving addresses which the peer may use
117    without authenticating itself. */
118 static struct wordlist *noauth_addrs;
119
120 /* Extra options to apply, from the secrets file entry for the peer. */
121 static struct wordlist *extra_options;
122
123 /* Number of network protocols which we have opened. */
124 static int num_np_open;
125
126 /* Number of network protocols which have come up. */
127 static int num_np_up;
128
129 /* Set if we got the contents of passwd[] from the pap-secrets file. */
130 static int passwd_from_file;
131
132 /* Set if we require authentication only because we have a default route. */
133 static bool default_auth;
134
135 /* Hook to enable a plugin to control the idle time limit */
136 int (*idle_time_hook) __P((struct ppp_idle *)) = NULL;
137
138 /* Hook for a plugin to say whether we can possibly authenticate any peer */
139 int (*pap_check_hook) __P((void)) = NULL;
140
141 /* Hook for a plugin to check the PAP user and password */
142 int (*pap_auth_hook) __P((char *user, char *passwd, char **msgp,
143                           struct wordlist **paddrs,
144                           struct wordlist **popts)) = NULL;
145
146 /* Hook for a plugin to know about the PAP user logout */
147 void (*pap_logout_hook) __P((void)) = NULL;
148
149 /* Hook for a plugin to get the PAP password for authenticating us */
150 int (*pap_passwd_hook) __P((char *user, char *passwd)) = NULL;
151
152 /*
153  * This is used to ensure that we don't start an auth-up/down
154  * script while one is already running.
155  */
156 enum script_state {
157     s_down,
158     s_up
159 };
160
161 static enum script_state auth_state = s_down;
162 static enum script_state auth_script_state = s_down;
163 static pid_t auth_script_pid = 0;
164
165 static int used_login;          /* peer authenticated against login database */
166
167 /*
168  * Option variables.
169  */
170 bool uselogin = 0;              /* Use /etc/passwd for checking PAP */
171 bool cryptpap = 0;              /* Passwords in pap-secrets are encrypted */
172 bool refuse_pap = 0;            /* Don't wanna auth. ourselves with PAP */
173 bool refuse_chap = 0;           /* Don't wanna auth. ourselves with CHAP */
174 bool usehostname = 0;           /* Use hostname for our_name */
175 bool auth_required = 0;         /* Always require authentication from peer */
176 bool allow_any_ip = 0;          /* Allow peer to use any IP address */
177 bool explicit_remote = 0;       /* User specified explicit remote name */
178 char remote_name[MAXNAMELEN];   /* Peer's name for authentication */
179
180 static char *uafname;           /* name of most recent +ua file */
181
182 /* Bits in auth_pending[] */
183 #define PAP_WITHPEER    1
184 #define PAP_PEER        2
185 #define CHAP_WITHPEER   4
186 #define CHAP_PEER       8
187
188 extern char *crypt __P((const char *, const char *));
189
190 /* Prototypes for procedures local to this file. */
191
192 static void network_phase __P((int));
193 static void check_idle __P((void *));
194 // brcm
195 static void check_link __P((void *));
196 static void check_lan_link __P((void *));
197 static void connect_time_expired __P((void *));
198 static int  plogin __P((char *, char *, char **));
199 static void plogout __P((void));
200 static int  null_login __P((int));
201 static int  get_pap_passwd __P((char *));
202 static int  have_pap_secret __P((int *));
203 static int  have_chap_secret __P((char *, char *, int, int *));
204 static int  ip_addr_check __P((u_int32_t, struct permitted_ip *));
205 static int  scan_authfile __P((FILE *, char *, char *, char *,
206                                struct wordlist **, struct wordlist **,
207                                char *));
208 static void free_wordlist __P((struct wordlist *));
209 static void auth_script __P((char *));
210 static void auth_script_done __P((void *));
211 static void set_allowed_addrs __P((int, struct wordlist *, struct wordlist *));
212 static int  some_ip_ok __P((struct wordlist *));
213 static int  setupapfile __P((char **));
214 static int  privgroup __P((char **));
215 static int  set_noauth_addr __P((char **));
216 static void check_access __P((FILE *, char *));
217 static int  wordlist_count __P((struct wordlist *));
218
219 /*
220  * Authentication-related options.
221  */
222 option_t auth_options[] = {
223     { "auth", o_bool, &auth_required,
224       "Require authentication from peer", OPT_PRIO | 1 },
225     { "noauth", o_bool, &auth_required,
226       "Don't require peer to authenticate", OPT_PRIOSUB | OPT_PRIV,
227       &allow_any_ip },
228     { "require-pap", o_bool, &lcp_wantoptions[0].neg_upap,
229       "Require PAP authentication from peer",
230       OPT_PRIOSUB | 1, &auth_required },
231     { "+pap", o_bool, &lcp_wantoptions[0].neg_upap,
232       "Require PAP authentication from peer",
233       OPT_ALIAS | OPT_PRIOSUB | 1, &auth_required },
234     { "require-chap", o_bool, &lcp_wantoptions[0].neg_chap,
235       "Require CHAP authentication from peer",
236       OPT_PRIOSUB | 1, &auth_required },
237     { "+chap", o_bool, &lcp_wantoptions[0].neg_chap,
238       "Require CHAP authentication from peer",
239       OPT_ALIAS | OPT_PRIOSUB | 1, &auth_required },
240
241     { "refuse-pap", o_bool, &refuse_pap,
242       "Don't agree to auth to peer with PAP", 1 },
243     { "-pap", o_bool, &refuse_pap,
244       "Don't allow PAP authentication with peer", OPT_ALIAS | 1 },
245
246     { "refuse-chap", o_bool, &refuse_chap,
247       "Don't agree to auth to peer with CHAP", 1 },
248     { "-chap", o_bool, &refuse_chap,
249       "Don't allow CHAP authentication with peer", OPT_ALIAS | 1 },
250
251     { "name", o_string, our_name,
252       "Set local name for authentication",
253       OPT_PRIO | OPT_PRIV | OPT_STATIC, NULL, MAXNAMELEN },
254
255     { "+ua", o_special, (void *)setupapfile,
256       "Get PAP user and password from file",
257       OPT_PRIO | OPT_A2STRVAL, &uafname },
258
259     { "user", o_string, user,
260       "Set name for auth with peer", OPT_PRIO | OPT_STATIC, NULL, MAXNAMELEN },
261
262     { "password", o_string, passwd,
263       "Password for authenticating us to the peer",
264       OPT_PRIO | OPT_STATIC | OPT_HIDE, NULL, MAXSECRETLEN },
265
266     { "usehostname", o_bool, &usehostname,
267       "Must use hostname for authentication", 1 },
268
269     { "remotename", o_string, remote_name,
270       "Set remote name for authentication", OPT_PRIO | OPT_STATIC,
271       &explicit_remote, MAXNAMELEN },
272
273     { "login", o_bool, &uselogin,
274       "Use system password database for PAP", 1 },
275
276     { "papcrypt", o_bool, &cryptpap,
277       "PAP passwords are encrypted", 1 },
278
279     { "privgroup", o_special, (void *)privgroup,
280       "Allow group members to use privileged options", OPT_PRIV | OPT_A2LIST },
281
282     { "allow-ip", o_special, (void *)set_noauth_addr,
283       "Set IP address(es) which can be used without authentication",
284       OPT_PRIV | OPT_A2LIST },
285
286     { NULL }
287 };
288
289 /*
290  * setupapfile - specifies UPAP info for authenticating with peer.
291  */
292 static int
293 setupapfile(argv)
294     char **argv;
295 {
296     FILE *ufile;
297     int l;
298     char u[MAXNAMELEN], p[MAXSECRETLEN];
299     char *fname;
300
301     lcp_allowoptions[0].neg_upap = 1;
302
303     /* open user info file */
304     fname = strdup(*argv);
305     if (fname == NULL)
306         novm("+ua file name");
307     seteuid(getuid());
308     ufile = fopen(fname, "r");
309     seteuid(0);
310     if (ufile == NULL) {
311         option_error("unable to open user login data file %s", fname);
312         return 0;
313     }
314     check_access(ufile, fname);
315     uafname = fname;
316
317     /* get username */
318     if (fgets(u, MAXNAMELEN - 1, ufile) == NULL || fgets(p, MAXSECRETLEN - 1, ufile) == NULL){
319         option_error("unable to read user login data file %s", fname);
320         return 0;
321     }
322     fclose(ufile);
323
324     /* get rid of newlines */
325     l = strlen(u);
326     if (l > 0 && u[l-1] == '\n')
327         u[l-1] = 0;
328     l = strlen(p);
329     if (l > 0 && p[l-1] == '\n')
330         p[l-1] = 0;
331
332     if (override_value("user", option_priority, fname))
333         strlcpy(user, u, sizeof(user));
334     if (override_value("passwd", option_priority, fname))
335         strlcpy(passwd, p, sizeof(passwd));
336
337     return (1);
338 }
339
340
341 /*
342  * privgroup - allow members of the group to have privileged access.
343  */
344 static int
345 privgroup(argv)
346     char **argv;
347 {
348     struct group *g;
349     int i;
350
351     g = getgrnam(*argv);
352     if (g == 0) {
353         option_error("group %s is unknown", *argv);
354         return 0;
355     }
356     for (i = 0; i < ngroups; ++i) {
357         if (groups[i] == g->gr_gid) {
358             privileged = 1;
359             break;
360         }
361     }
362     return 1;
363 }
364
365
366 /*
367  * set_noauth_addr - set address(es) that can be used without authentication.
368  * Equivalent to specifying an entry like `"" * "" addr' in pap-secrets.
369  */
370 static int
371 set_noauth_addr(argv)
372     char **argv;
373 {
374     char *addr = *argv;
375     int l = strlen(addr) + 1;
376     struct wordlist *wp;
377
378     wp = (struct wordlist *) malloc(sizeof(struct wordlist) + l);
379     if (wp == NULL)
380         novm("allow-ip argument");
381     wp->word = (char *) (wp + 1);
382     wp->next = noauth_addrs;
383     BCOPY(addr, wp->word, l);
384     noauth_addrs = wp;
385     return 1;
386 }
387
388
389 /*
390  * An Open on LCP has requested a change from Dead to Establish phase.
391  * Do what's necessary to bring the physical layer up.
392  */
393 void
394 link_required(unit)
395     int unit;
396 {
397 }
398
399 /*
400  * LCP has terminated the link; go to the Dead phase and take the
401  * physical layer down.
402  */
403 void
404 link_terminated(unit)
405     int unit;
406 {
407     if (phase == PHASE_DEAD)
408         return;
409     if (pap_logout_hook) {
410         pap_logout_hook();
411     } else {
412         if (logged_in)
413             plogout();
414     }
415     new_phase(PHASE_DEAD);
416     notice("Connection terminated.");
417 }
418
419 /*
420  * LCP has gone down; it will either die or try to re-establish.
421  */
422 void
423 link_down(unit)
424     int unit;
425 {
426     int i;
427     struct protent *protp;
428
429     auth_state = s_down;
430     if (auth_script_state == s_up && auth_script_pid == 0) {
431         update_link_stats(unit);
432         auth_script_state = s_down;
433         auth_script(_PATH_AUTHDOWN);
434     }
435     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
436         if (!protp->enabled_flag)
437             continue;
438         if (protp->protocol != PPP_LCP && protp->lowerdown != NULL)
439             (*protp->lowerdown)(unit);
440         if (protp->protocol < 0xC000 && protp->close != NULL)
441             (*protp->close)(unit, "LCP down");
442     }
443     num_np_open = 0;
444     num_np_up = 0;
445     if (phase != PHASE_DEAD)
446         new_phase(PHASE_TERMINATE);
447 }
448
449 /*==== add by Andrew to limit the times of authentication ====*/
450 int isRetriesTimesOut(unit)
451         int unit;
452 {
453     lcp_options *ho = &lcp_hisoptions[unit];
454         int isTimesOut = 0;
455
456     if (ho->neg_chap) {
457                 chap_state *cstate = &chap[unit];
458                 if(cstate->retries <= 0)
459                         isTimesOut = 1;
460     } else if (ho->neg_upap) {
461                 upap_state *u = &upap[unit];
462                 if(u->us_retries <= 0)
463                         isTimesOut = 1;
464     }
465         return isTimesOut;
466 }
467 /*==== end ====*/
468
469 /*
470  * The link is established.
471  * Proceed to the Dead, Authenticate or Network phase as appropriate.
472  */
473 void
474 link_established(unit)
475     int unit;
476 {
477     int auth;
478     lcp_options *wo = &lcp_wantoptions[unit];
479     lcp_options *go = &lcp_gotoptions[unit];
480     lcp_options *ho = &lcp_hisoptions[unit];
481     int i;
482     struct protent *protp;
483     char cmd[60];
484
485         /*==== add by Andrew to limit the times of authentication ====*/
486 //#if defined (PPP_AUTH_LIMIT)
487 #if 0
488         if(isRetriesTimesOut(unit)) {
489                 //system("echo '0:the times of retry is exhausted' > /var/pppmesg");
490                 lcp_close(unit, "retries times is out");
491                 status = EXIT_PEER_AUTH_FAILED;
492 #ifdef BBB_XML_API //Wilson add, (04/18/2005)
493                 FILE *fp=NULL;
494                 fp = fopen("/var/pppStatus", "w+");
495                 if(fp){
496                 fprintf(fp, "1,1");
497                         fclose(fp);
498                 }
499 #endif //endif BBB_XML_API
500 #if defined(ODM_LANG_LLL)
501               FILE *wsnfp=NULL;
502                 if (ppp_session == PPPOE){
503                         wsnfp = fopen("/var/btaolstatus", "w");
504                         if(wsnfp){
505                             fprintf(wsnfp, "%d", 2);
506                             fclose(wsnfp);
507                         }
508                         sprintf(cmd,"kill -9 %d",glbppppid);
509                         system(cmd);
510                 }
511 #else//ODM_LANG_LLL
512                 //sprintf(cmd,"echo 1 > /var/af_%s",req_name);
513                 //system(cmd);
514                 sprintf(cmd,"kill -9 %d",glbppppid);
515                 system(cmd);
516                 //exit(1);
517 #endif//ODM_LANG_LLL
518         }
519 #endif//PPP_AUTH_LIMIT
520         /*==== end ====*/
521
522     /*
523      * Tell higher-level protocols that LCP is up.
524      */
525     for (i = 0; (protp = protocols[i]) != NULL; ++i)
526         if (protp->protocol != PPP_LCP && protp->enabled_flag && protp->lowerup != NULL)
527             (*protp->lowerup)(unit);
528
529     if (auth_required && !(go->neg_chap || go->neg_upap)) {
530         /*
531          * We wanted the peer to authenticate itself, and it refused:
532          * if we have some address(es) it can use without auth, fine,
533          * otherwise treat it as though it authenticated with PAP using
534          * a username * of "" and a password of "".  If that's not OK,
535          * boot it out.
536          */
537         if (noauth_addrs != NULL) {
538             set_allowed_addrs(unit, NULL, NULL);
539         } else if (!wo->neg_upap || uselogin || !null_login(unit)) {
540             warn("peer refused to authenticate: terminating link");
541             lcp_close(unit, "peer refused to authenticate");
542             status = EXIT_PEER_AUTH_FAILED;
543             return;
544         }
545     }
546
547     new_phase(PHASE_AUTHENTICATE);
548     used_login = 0;
549     auth = 0;
550     if (go->neg_chap) {
551         ChapAuthPeer(unit, our_name, go->chap_mdtype);
552         auth |= CHAP_PEER;
553     } else if (go->neg_upap) {
554         upap_authpeer(unit);
555         auth |= PAP_PEER;
556     }
557     if (ho->neg_chap) {
558         ChapAuthWithPeer(unit, user, ho->chap_mdtype);
559         auth |= CHAP_WITHPEER;
560     } else if (ho->neg_upap) {
561 //      Ported from 2.10.1--06/02/2003 continue Auth for Null Password
562 //              if (passwd[0] == 0) {
563 //                  passwd_from_file = 1;
564 //                  if (!get_pap_passwd(passwd))
565 //                      error("No secret found for PAP login");
566 //              }
567         upap_authwithpeer(unit, user, passwd);
568         auth |= PAP_WITHPEER;
569     }
570     auth_pending[unit] = auth;
571
572     if (!auth)
573         network_phase(unit);
574 }
575
576 /*
577  * Proceed to the network phase.
578  */
579 static void
580 network_phase(unit)
581     int unit;
582 {
583     lcp_options *go = &lcp_gotoptions[unit];
584
585     /*
586      * If the peer had to authenticate, run the auth-up script now.
587      */
588     if (go->neg_chap || go->neg_upap) {
589         auth_state = s_up;
590         if (auth_script_state == s_down && auth_script_pid == 0) {
591             auth_script_state = s_up;
592             auth_script(_PATH_AUTHUP);
593         }
594     }
595
596 #ifdef CBCP_SUPPORT
597     /*
598      * If we negotiated callback, do it now.
599      */
600     if (go->neg_cbcp) {
601         new_phase(PHASE_CALLBACK);
602         (*cbcp_protent.open)(unit);
603         return;
604     }
605 #endif
606
607     /*
608      * Process extra options from the secrets file
609      */
610 // brcm
611 #if 0
612     if (extra_options) {
613         options_from_list(extra_options, 1);
614         free_wordlist(extra_options);
615         extra_options = 0;
616     }
617 #endif
618     start_networks();
619 }
620
621 void
622 start_networks()
623 {
624     int i;
625     struct protent *protp;
626
627     new_phase(PHASE_NETWORK);
628
629 #ifdef HAVE_MULTILINK
630     if (multilink) {
631         if (mp_join_bundle()) {
632             if (updetach && !nodetach)
633                 detach();
634             return;
635         }
636     }
637 #endif /* HAVE_MULTILINK */
638
639 #ifdef PPP_FILTER
640     if (!demand)
641         set_filters(&pass_filter, &active_filter);
642 #endif
643     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
644         if (protp->protocol < 0xC000 && protp->enabled_flag && protp->open != NULL) {
645             (*protp->open)(0);
646             if (protp->protocol != PPP_CCP)
647                 ++num_np_open;
648         }
649         }
650
651     if (num_np_open == 0)
652         /* nothing to do */
653         lcp_close(0, "No network protocols running");
654 }
655
656 /*
657  * The peer has failed to authenticate himself using `protocol'.
658  */
659 void
660 auth_peer_fail(unit, protocol)
661     int unit, protocol;
662 {
663     /*
664      * Authentication failure: take the link down
665      */
666     lcp_close(unit, "Authentication failed");
667     status = EXIT_PEER_AUTH_FAILED;
668 }
669
670 /*
671  * The peer has been successfully authenticated using `protocol'.
672  */
673 void
674 auth_peer_success(unit, protocol, name, namelen)
675     int unit, protocol;
676     char *name;
677     int namelen;
678 {
679     int bit;
680
681     switch (protocol) {
682     case PPP_CHAP:
683         bit = CHAP_PEER;
684         break;
685     case PPP_PAP:
686         bit = PAP_PEER;
687         break;
688     default:
689         warn("auth_peer_success: unknown protocol %x", protocol);
690         return;
691     }
692
693     /*
694      * Save the authenticated name of the peer for later.
695      */
696     if (namelen > sizeof(peer_authname) - 1)
697         namelen = sizeof(peer_authname) - 1;
698     BCOPY(name, peer_authname, namelen);
699     peer_authname[namelen] = 0;
700     script_setenv("PEERNAME", peer_authname, 0);
701
702     /*
703      * If there is no more authentication still to be done,
704      * proceed to the network (or callback) phase.
705      */
706     if ((auth_pending[unit] &= ~bit) == 0)
707         network_phase(unit);
708 }
709
710 /*
711  * We have failed to authenticate ourselves to the peer using `protocol'.
712  */
713 void
714 auth_withpeer_fail(unit, protocol)
715     int unit, protocol;
716 {
717     if (passwd_from_file)
718         BZERO(passwd, MAXSECRETLEN);
719     /*
720      * We've failed to authenticate ourselves to our peer.
721      * Some servers keep sending CHAP challenges, but there
722      * is no point in persisting without any way to get updated
723      * authentication secrets.
724      */
725     lcp_close(unit, "Failed to authenticate ourselves to peer");
726 #if defined(ONE_AND_ONE)
727         if(isp_1n1 && is1n1) {
728         upap_state *u = &upap[unit];
729         if(u->us_1n1stage==1) {
730                 auth_again = 1;
731         } else {
732         status = EXIT_AUTH_TOPEER_FAILED;
733         printf("PPP: Authentication failed.\n");
734             create_msg(BCM_PPPOE_AUTH_FAILED);
735         syslog(LOG_ERR,"User name and password authentication failed.\n");
736         }
737         }else {
738         status = EXIT_AUTH_TOPEER_FAILED;
739         printf("PPP: Authentication failed.\n");
740             create_msg(BCM_PPPOE_AUTH_FAILED);
741         syslog(LOG_ERR,"User name and password authentication failed.\n");
742         }
743 #else
744     status = EXIT_AUTH_TOPEER_FAILED;
745 // brcm
746 //    if ((strlen(user) > 0) || autoscanP2) {
747     printf("PPP: Authentication failed.\n");
748     create_msg(BCM_PPPOE_AUTH_FAILED);
749     //syslog(LOG_ERR,"User name and password authentication failed.\n");
750     syslog(LOG_ERR,"PPP Authentication Failed\n");
751 //    }
752 //#ifdef BBB_XML_API //Wilson add, (04/18/2005)
753 #if defined(SUPPORT_XML_API) //Wilson add, (03/14/2006)
754     FILE *fp=NULL;
755     fp = fopen("/var/pppStatus", "w+");
756     if(fp){
757         fprintf(fp, "1,1");
758         fclose(fp);
759     }
760 #endif //end#if defined(BBB_XML_API) || defined(SUPPORT_XML_API) //Wilson add, (03/14/2006)
761 #if defined(SUPPORT_TR69C) //Wilson add, (09/01/2006)
762         FILE *fd=NULL;
763         char filePath[128]={0,};
764         sprintf(filePath, "/var/%s_LastError", session_path);
765         fd = fopen(filePath, "w+");
766         if(fd){
767                 fprintf(fd, "ERROR_AUTHENTICATION_FAILURE");
768                 fclose(fd);
769         }
770 #endif //endif SUPPORT_TR69C
771     //marked by Charles 07/03/2003 to allow continous retry
772     //persist=0;
773 #endif
774 }
775
776 /*
777  * We have successfully authenticated ourselves with the peer using `protocol'.
778  */
779 void
780 auth_withpeer_success(unit, protocol)
781     int unit, protocol;
782 {
783     int bit;
784
785     switch (protocol) {
786     case PPP_CHAP:
787         bit = CHAP_WITHPEER;
788         syslog(LOG_NOTICE,"PPP Authentication Successful\n");
789         break;
790     case PPP_PAP:
791         if (passwd_from_file)
792             BZERO(passwd, MAXSECRETLEN);
793         bit = PAP_WITHPEER;
794         syslog(LOG_NOTICE,"PPP Authentication Successful\n");
795         break;
796     default:
797         warn("auth_withpeer_success: unknown protocol %x", protocol);
798         bit = 0;
799     }
800
801     /*
802      * If there is no more authentication still being done,
803      * proceed to the network (or callback) phase.
804      */
805     if ((auth_pending[unit] &= ~bit) == 0)
806         network_phase(unit);
807 }
808
809
810 /*
811  * np_up - a network protocol has come up.
812  */
813 void
814 np_up(unit, proto)
815     int unit, proto;
816 {
817     int tlim;
818
819     if (num_np_up == 0) {
820         /*
821          * At this point we consider that the link has come up successfully.
822          */
823         status = EXIT_OK;
824         unsuccess = 0;
825         new_phase(PHASE_RUNNING);
826
827         if (idle_time_hook != 0)
828             tlim = (*idle_time_hook)(NULL);
829         else
830             tlim = idle_time_limit;
831         if (tlim > 0)
832             TIMEOUT(check_idle, NULL, tlim);
833
834         // brcm
835         TIMEOUT(check_link, NULL, 3);
836
837         // brcm
838         if (ipext)
839             TIMEOUT(check_lan_link, NULL, 5);
840
841         /*
842          * Set a timeout to close the connection once the maximum
843          * connect time has expired.
844          */
845         if (maxconnect > 0)
846             TIMEOUT(connect_time_expired, 0, maxconnect);
847
848         /*
849          * Detach now, if the updetach option was given.
850          */
851         if (updetach && !nodetach)
852             detach();
853     }
854     ++num_np_up;
855 }
856
857 /*
858  * np_down - a network protocol has gone down.
859  */
860 void
861 np_down(unit, proto)
862     int unit, proto;
863 {
864     if (--num_np_up == 0) {
865         UNTIMEOUT(check_idle, NULL);
866         // brcm
867         UNTIMEOUT(check_link, NULL);
868         if (ipext)
869             UNTIMEOUT(check_lan_link, NULL);
870         new_phase(PHASE_NETWORK);
871     }
872 }
873
874 /*
875  * np_finished - a network protocol has finished using the link.
876  */
877 void
878 np_finished(unit, proto)
879     int unit, proto;
880 {
881     if (--num_np_open <= 0) {
882         /* no further use for the link: shut up shop. */
883         lcp_close(0, "No network protocols running");
884     }
885 }
886
887 /*
888  * check_idle - check whether the link has been idle for long
889  * enough that we can shut it down.
890  */
891 static void
892 check_idle(arg)
893     void *arg;
894 {
895     struct ppp_idle idle;
896     time_t itime;
897     int tlim;
898 #if defined(SUPPORT_TR69C) //Wilson add, (09/01/2006)
899         FILE *fp=NULL;
900         char filePath[128]={0,};
901 #endif
902
903     if (!get_idle_time(0, &idle))
904         return;
905     if (idle_time_hook != 0) {
906         tlim = idle_time_hook(&idle);
907     } else {
908         tlim = idle_time_limit - idle.xmit_idle;
909         /***************************************************
910          * idle timer will only consider LAN-->WAN traffic *
911          * comment it according Brcm patch                 *
912          *                              Andrew(02/12/2004) *
913          ***************************************************/
914         //itime = MIN(idle.xmit_idle, idle.recv_idle);
915         //tlim = idle_time_limit - itime;
916         /***************************************************/
917     }
918     if (tlim <= 0) {
919         /* link is idle: shut it down. */
920         notice("Terminating connection due to lack of activity.");
921         lcp_close(0, "Link inactive");
922         need_holdoff = 0;
923         status = EXIT_IDLE_TIMEOUT;
924         // brcm
925         redisconn = 0;
926         sprintf(oldsession, "%s", "");
927 #if defined(SUPPORT_TR69C) //Wilson add, (09/01/2006)
928         sprintf(filePath, "/var/%s_LastError", session_path);
929         fp = fopen(filePath, "w+");
930         if(fp){
931                 fprintf(fp, "ERROR_IDLE_DISCONNECT");
932                 fclose(fp);
933         }
934 #endif //endif SUPPORT_TR69C
935     } else {
936         TIMEOUT(check_idle, NULL, tlim);
937     }
938 }
939
940 // brcm
941 int link_up()
942 {
943 /*
944     FILE * fd = NULL;
945     if ((fd=fopen("/var/run/wanup", "r"))) {
946         fclose(fd);
947         return 1;
948     }
949     else
950         return 0;
951 */
952     FILE * fd = NULL;
953     char path[128]="";
954     char data[8];
955
956     sprintf(path, "%s/%s/%s", "/proc/var/fyi/wan", session_path, "wanup");
957     //printf("=== %s ===\n", path);
958
959     if (fd=fopen(path, "r")) {
960         fgets(data, 8, fd);
961         fclose(fd);
962         //printf("data=%x\n", data[0]);
963         if (strstr(data, "1"))
964             return 1;
965         else
966             return 0;
967     }
968     else
969         return 0;
970 }
971
972
973 // brcm
974 static void
975 check_link(arg)
976     void *arg;
977 {
978     if (!link_up()) {
979         /* link is idle: shut it down. */
980         notice("Terminating connection due to link down.");
981         lcp_close(0, "Link down");
982         need_holdoff = 0;
983         status = EXIT_IDLE_TIMEOUT;
984     } else {
985         UNTIMEOUT(check_link, NULL);
986         TIMEOUT(check_link, NULL, 3);
987     }
988 }
989
990 int lan_pending_cur=0;
991 int lan_pending_max=36;
992 int lan_state=0;
993
994
995 int lan_link_up()
996 {
997     FILE * fd = NULL;
998     if ((fd=fopen("/var/run/ethup", "r"))) {
999         fclose(fd);
1000         lan_state=1;
1001         return 1;
1002     }
1003     else if ((fd=fopen("/var/run/usbup", "r"))) {
1004         fclose(fd);
1005         lan_state=1;
1006         return 1;
1007     }else if ((fd=fopen("/var/run/wlup", "r"))) { //Paul add, 8/22/2006 check wlan is enabled or not
1008         fclose(fd);
1009         lan_state=1;
1010         return 1;
1011     }
1012     else {
1013         lan_state=0;
1014         return 0;
1015     }
1016 }
1017
1018
1019 static void
1020 check_lan_link(arg)
1021     void *arg;
1022 {
1023     if (!lan_link_up()) {
1024         lan_pending_cur++;
1025         //printf("LAN link down %d ....\n", lan_pending_cur);
1026         if (lan_pending_cur >= lan_pending_max) {
1027             /* link is idle: shut it down. */
1028             lan_pending_cur=0;
1029             notice("Terminating connection due to link down.");
1030             lcp_close(0, "Link down");
1031             need_holdoff = 0;
1032             status = EXIT_IDLE_TIMEOUT;
1033         }
1034         UNTIMEOUT(check_lan_link, NULL);
1035         TIMEOUT(check_lan_link, NULL, 5);
1036     } else {
1037         //printf("LAN link up ....\n");
1038         lan_pending_cur=0;
1039         UNTIMEOUT(check_lan_link, NULL);
1040         TIMEOUT(check_lan_link, NULL, 5);
1041     }
1042 }
1043
1044 /*
1045  * connect_time_expired - log a message and close the connection.
1046  */
1047 static void
1048 connect_time_expired(arg)
1049     void *arg;
1050 {
1051     info("Connect time expired");
1052     lcp_close(0, "Connect time expired");       /* Close connection */
1053     status = EXIT_CONNECT_TIME;
1054 }
1055
1056 /*
1057  * auth_check_options - called to check authentication options.
1058  */
1059 void
1060 auth_check_options()
1061 {
1062     lcp_options *wo = &lcp_wantoptions[0];
1063     int can_auth;
1064     int lacks_ip;
1065
1066     /* Default our_name to hostname, and user to our_name */
1067     if (our_name[0] == 0 || usehostname)
1068         strlcpy(our_name, hostname, sizeof(our_name));
1069     if (user[0] == 0)
1070         strlcpy(user, our_name, sizeof(user));
1071
1072     /*
1073      * If we have a default route, require the peer to authenticate
1074      * unless the noauth option was given or the real user is root.
1075      */
1076     if (!auth_required && !allow_any_ip && have_route_to(0) && !privileged) {
1077         auth_required = 1;
1078         default_auth = 1;
1079     }
1080
1081     /* If authentication is required, ask peer for CHAP or PAP. */
1082     if (auth_required) {
1083         allow_any_ip = 0;
1084         if (!wo->neg_chap && !wo->neg_upap) {
1085             wo->neg_chap = 1;
1086             wo->neg_upap = 1;
1087         }
1088     } else {
1089         wo->neg_chap = 0;
1090         wo->neg_upap = 0;
1091     }
1092
1093     /*
1094      * Check whether we have appropriate secrets to use
1095      * to authenticate the peer.
1096      */
1097     lacks_ip = 0;
1098     can_auth = wo->neg_upap && (uselogin || have_pap_secret(&lacks_ip));
1099     if (!can_auth && wo->neg_chap) {
1100         can_auth = have_chap_secret((explicit_remote? remote_name: NULL),
1101                                     our_name, 1, &lacks_ip);
1102     }
1103
1104     if (auth_required && !can_auth && noauth_addrs == NULL) {
1105         if (default_auth) {
1106             option_error(
1107 "By default the remote system is required to authenticate itself");
1108             option_error(
1109 "(because this system has a default route to the internet)");
1110         } else if (explicit_remote)
1111             option_error(
1112 "The remote system (%s) is required to authenticate itself",
1113                          remote_name);
1114         else
1115             option_error(
1116 "The remote system is required to authenticate itself");
1117         option_error(
1118 "but I couldn't find any suitable secret (password) for it to use to do so.");
1119         if (lacks_ip)
1120             option_error(
1121 "(None of the available passwords would let it use an IP address.)");
1122
1123         exit(1);
1124     }
1125 }
1126
1127 /*
1128  * auth_reset - called when LCP is starting negotiations to recheck
1129  * authentication options, i.e. whether we have appropriate secrets
1130  * to use for authenticating ourselves and/or the peer.
1131  */
1132 void
1133 auth_reset(unit)
1134     int unit;
1135 {
1136     lcp_options *go = &lcp_gotoptions[unit];
1137     lcp_options *ao = &lcp_allowoptions[0];
1138
1139     // Ported from 2.10.1---Jack Suen 06/02/2003  Let Null Password also to do Auth State
1140     ao->neg_upap = !refuse_pap;
1141     ao->neg_chap = !refuse_chap;
1142     return;
1143
1144     ao->neg_upap = !refuse_pap && (passwd[0] != 0 || get_pap_passwd(NULL));
1145     ao->neg_chap = !refuse_chap
1146         && (passwd[0] != 0
1147             || have_chap_secret(user, (explicit_remote? remote_name: NULL),
1148                                 0, NULL));
1149
1150     if (go->neg_upap && !uselogin && !have_pap_secret(NULL))
1151         go->neg_upap = 0;
1152     if (go->neg_chap) {
1153         if (!have_chap_secret((explicit_remote? remote_name: NULL),
1154                               our_name, 1, NULL))
1155             go->neg_chap = 0;
1156     }
1157 }
1158
1159
1160 /*
1161  * check_passwd - Check the user name and passwd against the PAP secrets
1162  * file.  If requested, also check against the system password database,
1163  * and login the user if OK.
1164  *
1165  * returns:
1166  *      UPAP_AUTHNAK: Authentication failed.
1167  *      UPAP_AUTHACK: Authentication succeeded.
1168  * In either case, msg points to an appropriate message.
1169  */
1170 int
1171 check_passwd(unit, auser, userlen, apasswd, passwdlen, msg)
1172     int unit;
1173     char *auser;
1174     int userlen;
1175     char *apasswd;
1176     int passwdlen;
1177     char **msg;
1178 {
1179     int ret;
1180     char *filename;
1181     FILE *f;
1182     struct wordlist *addrs = NULL, *opts = NULL;
1183     char passwd[256], user[256];
1184     char secret[MAXWORDLEN];
1185     static int attempts = 0;
1186
1187     /*
1188      * Make copies of apasswd and auser, then null-terminate them.
1189      * If there are unprintable characters in the password, make
1190      * them visible.
1191      */
1192     slprintf(passwd, sizeof(passwd), "%.*v", passwdlen, apasswd);
1193     slprintf(user, sizeof(user), "%.*v", userlen, auser);
1194     *msg = "";
1195
1196     /*
1197      * Check if a plugin wants to handle this.
1198      */
1199     if (pap_auth_hook) {
1200         ret = (*pap_auth_hook)(user, passwd, msg, &addrs, &opts);
1201         if (ret >= 0) {
1202             if (ret)
1203                 set_allowed_addrs(unit, addrs, opts);
1204             BZERO(passwd, sizeof(passwd));
1205             if (addrs != 0)
1206                 free_wordlist(addrs);
1207             return ret? UPAP_AUTHACK: UPAP_AUTHNAK;
1208         }
1209     }
1210
1211     /*
1212      * Open the file of pap secrets and scan for a suitable secret
1213      * for authenticating this user.
1214      */
1215     filename = _PATH_UPAPFILE;
1216     addrs = opts = NULL;
1217     ret = UPAP_AUTHNAK;
1218     f = fopen(filename, "r");
1219     if (f == NULL) {
1220         error("Can't open PAP password file %s: %m", filename);
1221
1222     } else {
1223         check_access(f, filename);
1224         if (scan_authfile(f, user, our_name, secret, &addrs, &opts, filename) < 0) {
1225             warn("no PAP secret found for %s", user);
1226         } else {
1227             /*
1228              * If the secret is "@login", it means to check
1229              * the password against the login database.
1230              */
1231             int login_secret = strcmp(secret, "@login") == 0;
1232             ret = UPAP_AUTHACK;
1233             if (uselogin || login_secret) {
1234                 /* login option or secret is @login */
1235                 ret = plogin(user, passwd, msg);
1236                 if (ret == UPAP_AUTHNAK)
1237                     warn("PAP login failure for %s", user);
1238                 else
1239                     used_login = 1;
1240             }
1241             if (secret[0] != 0 && !login_secret) {
1242                 /* password given in pap-secrets - must match */
1243                 if ((cryptpap || strcmp(passwd, secret) != 0)
1244                     && strcmp(crypt(passwd, secret), secret) != 0) {
1245                     ret = UPAP_AUTHNAK;
1246                     warn("PAP authentication failure for %s", user);
1247                 }
1248             }
1249         }
1250         fclose(f);
1251     }
1252
1253     if (ret == UPAP_AUTHNAK) {
1254         if (**msg == 0)
1255             *msg = "Login incorrect";
1256         /*
1257          * XXX can we ever get here more than once??
1258          * Frustrate passwd stealer programs.
1259          * Allow 10 tries, but start backing off after 3 (stolen from login).
1260          * On 10'th, drop the connection.
1261          */
1262         if (attempts++ >= 10) {
1263             warn("%d LOGIN FAILURES ON %s, %s", attempts, devnam, user);
1264             lcp_close(unit, "login failed");
1265         }
1266         if (attempts > 3)
1267             sleep((u_int) (attempts - 3) * 5);
1268         if (opts != NULL)
1269             free_wordlist(opts);
1270
1271     } else {
1272         attempts = 0;                   /* Reset count */
1273         if (**msg == 0)
1274             *msg = "Login ok";
1275         set_allowed_addrs(unit, addrs, opts);
1276     }
1277
1278     if (addrs != NULL)
1279         free_wordlist(addrs);
1280     BZERO(passwd, sizeof(passwd));
1281     BZERO(secret, sizeof(secret));
1282
1283     return ret;
1284 }
1285
1286 /*
1287  * This function is needed for PAM.
1288  */
1289
1290 #ifdef USE_PAM
1291 /* Static variables used to communicate between the conversation function
1292  * and the server_login function
1293  */
1294 static char *PAM_username;
1295 static char *PAM_password;
1296 static int PAM_error = 0;
1297 static pam_handle_t *pamh = NULL;
1298
1299 /* PAM conversation function
1300  * Here we assume (for now, at least) that echo on means login name, and
1301  * echo off means password.
1302  */
1303
1304 static int PAM_conv (int num_msg, const struct pam_message **msg,
1305                     struct pam_response **resp, void *appdata_ptr)
1306 {
1307     int replies = 0;
1308     struct pam_response *reply = NULL;
1309
1310 #define COPY_STRING(s) (s) ? strdup(s) : NULL
1311
1312     reply = malloc(sizeof(struct pam_response) * num_msg);
1313     if (!reply) return PAM_CONV_ERR;
1314
1315     for (replies = 0; replies < num_msg; replies++) {
1316         switch (msg[replies]->msg_style) {
1317             case PAM_PROMPT_ECHO_ON:
1318                 reply[replies].resp_retcode = PAM_SUCCESS;
1319                 reply[replies].resp = COPY_STRING(PAM_username);
1320                 /* PAM frees resp */
1321                 break;
1322             case PAM_PROMPT_ECHO_OFF:
1323                 reply[replies].resp_retcode = PAM_SUCCESS;
1324                 reply[replies].resp = COPY_STRING(PAM_password);
1325                 /* PAM frees resp */
1326                 break;
1327             case PAM_TEXT_INFO:
1328                 /* fall through */
1329             case PAM_ERROR_MSG:
1330                 /* ignore it, but pam still wants a NULL response... */
1331                 reply[replies].resp_retcode = PAM_SUCCESS;
1332                 reply[replies].resp = NULL;
1333                 break;
1334             default:
1335                 /* Must be an error of some sort... */
1336                 free (reply);
1337                 PAM_error = 1;
1338                 return PAM_CONV_ERR;
1339         }
1340     }
1341     *resp = reply;
1342     return PAM_SUCCESS;
1343 }
1344
1345 static struct pam_conv PAM_conversation = {
1346     &PAM_conv,
1347     NULL
1348 };
1349 #endif  /* USE_PAM */
1350
1351 /*
1352  * plogin - Check the user name and password against the system
1353  * password database, and login the user if OK.
1354  *
1355  * returns:
1356  *      UPAP_AUTHNAK: Login failed.
1357  *      UPAP_AUTHACK: Login succeeded.
1358  * In either case, msg points to an appropriate message.
1359  */
1360
1361 static int plogin(user, passwd, msg)
1362     char *user;
1363     char *passwd;
1364     char **msg;
1365 {
1366     char *tty;
1367
1368 #ifdef USE_PAM
1369     int pam_error;
1370
1371     pam_error = pam_start ("ppp", user, &PAM_conversation, &pamh);
1372     if (pam_error != PAM_SUCCESS) {
1373         *msg = (char *) pam_strerror (pamh, pam_error);
1374         reopen_log();
1375         return UPAP_AUTHNAK;
1376     }
1377     /*
1378      * Define the fields for the credential validation
1379      */
1380
1381     PAM_username = user;
1382     PAM_password = passwd;
1383     PAM_error = 0;
1384     pam_set_item (pamh, PAM_TTY, devnam); /* this might be useful to some modules */
1385
1386     /*
1387      * Validate the user
1388      */
1389     pam_error = pam_authenticate (pamh, PAM_SILENT);
1390     if (pam_error == PAM_SUCCESS && !PAM_error) {
1391         pam_error = pam_acct_mgmt (pamh, PAM_SILENT);
1392         if (pam_error == PAM_SUCCESS)
1393             pam_open_session (pamh, PAM_SILENT);
1394     }
1395
1396     *msg = (char *) pam_strerror (pamh, pam_error);
1397
1398     /*
1399      * Clean up the mess
1400      */
1401     reopen_log();       /* apparently the PAM stuff does closelog() */
1402     PAM_username = NULL;
1403     PAM_password = NULL;
1404     if (pam_error != PAM_SUCCESS)
1405         return UPAP_AUTHNAK;
1406 #else /* #ifdef USE_PAM */
1407
1408 /*
1409  * Use the non-PAM methods directly
1410  */
1411
1412 #ifdef HAS_SHADOW
1413     struct spwd *spwd;
1414     struct spwd *getspnam();
1415 #endif
1416     struct passwd *pw = getpwnam(user);
1417
1418     endpwent();
1419     if (pw == NULL)
1420         return (UPAP_AUTHNAK);
1421
1422 #ifdef HAS_SHADOW
1423     spwd = getspnam(user);
1424     endspent();
1425     if (spwd) {
1426         /* check the age of the password entry */
1427         long now = time(NULL) / 86400L;
1428
1429         if ((spwd->sp_expire > 0 && now >= spwd->sp_expire)
1430             || ((spwd->sp_max >= 0 && spwd->sp_max < 10000)
1431                 && spwd->sp_lstchg >= 0
1432                 && now >= spwd->sp_lstchg + spwd->sp_max)) {
1433             warn("Password for %s has expired", user);
1434             return (UPAP_AUTHNAK);
1435         }
1436         pw->pw_passwd = spwd->sp_pwdp;
1437     }
1438 #endif
1439
1440     /*
1441      * If no passwd, don't let them login.
1442      */
1443     if (pw->pw_passwd == NULL || strlen(pw->pw_passwd) < 2
1444         || strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd) != 0)
1445         return (UPAP_AUTHNAK);
1446
1447 #endif /* #ifdef USE_PAM */
1448
1449     /*
1450      * Write a wtmp entry for this user.
1451      */
1452
1453     tty = devnam;
1454     if (strncmp(tty, "/dev/", 5) == 0)
1455         tty += 5;
1456     logwtmp(tty, user, remote_name);            /* Add wtmp login entry */
1457
1458 #if defined(_PATH_LASTLOG) && !defined(USE_PAM)
1459     if (pw != (struct passwd *)NULL) {
1460             struct lastlog ll;
1461             int fd;
1462
1463             if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
1464                 (void)lseek(fd, (off_t)(pw->pw_uid * sizeof(ll)), SEEK_SET);
1465                 memset((void *)&ll, 0, sizeof(ll));
1466                 (void)time(&ll.ll_time);
1467                 (void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
1468                 (void)write(fd, (char *)&ll, sizeof(ll));
1469                 (void)close(fd);
1470             }
1471     }
1472 #endif /* _PATH_LASTLOG and not USE_PAM */
1473
1474     info("user %s logged in", user);
1475     logged_in = 1;
1476
1477     return (UPAP_AUTHACK);
1478 }
1479
1480 /*
1481  * plogout - Logout the user.
1482  */
1483 static void
1484 plogout()
1485 {
1486 #ifdef USE_PAM
1487     int pam_error;
1488
1489     if (pamh != NULL) {
1490         pam_error = pam_close_session (pamh, PAM_SILENT);
1491         pam_end (pamh, pam_error);
1492         pamh = NULL;
1493     }
1494     /* Apparently the pam stuff does closelog(). */
1495     reopen_log();
1496 #else /* ! USE_PAM */
1497     char *tty;
1498
1499     tty = devnam;
1500     if (strncmp(tty, "/dev/", 5) == 0)
1501         tty += 5;
1502     logwtmp(tty, "", "");               /* Wipe out utmp logout entry */
1503 #endif /* ! USE_PAM */
1504     logged_in = 0;
1505 }
1506
1507
1508 /*
1509  * null_login - Check if a username of "" and a password of "" are
1510  * acceptable, and iff so, set the list of acceptable IP addresses
1511  * and return 1.
1512  */
1513 static int
1514 null_login(unit)
1515     int unit;
1516 {
1517     char *filename;
1518     FILE *f;
1519     int i, ret;
1520     struct wordlist *addrs, *opts;
1521     char secret[MAXWORDLEN];
1522
1523     /*
1524      * Open the file of pap secrets and scan for a suitable secret.
1525      */
1526     filename = _PATH_UPAPFILE;
1527     addrs = NULL;
1528     f = fopen(filename, "r");
1529     if (f == NULL)
1530         return 0;
1531     check_access(f, filename);
1532
1533     i = scan_authfile(f, "", our_name, secret, &addrs, &opts, filename);
1534     ret = i >= 0 && secret[0] == 0;
1535     BZERO(secret, sizeof(secret));
1536
1537     if (ret)
1538         set_allowed_addrs(unit, addrs, opts);
1539     else if (opts != 0)
1540         free_wordlist(opts);
1541     if (addrs != 0)
1542         free_wordlist(addrs);
1543
1544     fclose(f);
1545     return ret;
1546 }
1547
1548
1549 /*
1550  * get_pap_passwd - get a password for authenticating ourselves with
1551  * our peer using PAP.  Returns 1 on success, 0 if no suitable password
1552  * could be found.
1553  * Assumes passwd points to MAXSECRETLEN bytes of space (if non-null).
1554  */
1555 static int
1556 get_pap_passwd(passwd)
1557     char *passwd;
1558 {
1559     char *filename;
1560     FILE *f;
1561     int ret;
1562     char secret[MAXWORDLEN];
1563
1564     /*
1565      * Check whether a plugin wants to supply this.
1566      */
1567     if (pap_passwd_hook) {
1568         ret = (*pap_passwd_hook)(user, passwd);
1569         if (ret >= 0)
1570             return ret;
1571     }
1572
1573     filename = _PATH_UPAPFILE;
1574     f = fopen(filename, "r");
1575     if (f == NULL)
1576         return 0;
1577     check_access(f, filename);
1578     ret = scan_authfile(f, user,
1579                         (remote_name[0]? remote_name: NULL),
1580                         secret, NULL, NULL, filename);
1581     fclose(f);
1582     if (ret < 0)
1583         return 0;
1584     if (passwd != NULL)
1585         strlcpy(passwd, secret, MAXSECRETLEN);
1586     BZERO(secret, sizeof(secret));
1587     return 1;
1588 }
1589
1590
1591 /*
1592  * have_pap_secret - check whether we have a PAP file with any
1593  * secrets that we could possibly use for authenticating the peer.
1594  */
1595 static int
1596 have_pap_secret(lacks_ipp)
1597     int *lacks_ipp;
1598 {
1599     FILE *f;
1600     int ret;
1601     char *filename;
1602     struct wordlist *addrs;
1603
1604     /* let the plugin decide, if there is one */
1605     if (pap_check_hook) {
1606         ret = (*pap_check_hook)();
1607         if (ret >= 0)
1608             return ret;
1609     }
1610
1611     filename = _PATH_UPAPFILE;
1612     f = fopen(filename, "r");
1613     if (f == NULL)
1614         return 0;
1615
1616     ret = scan_authfile(f, (explicit_remote? remote_name: NULL), our_name, NULL, &addrs, NULL, filename);
1617     fclose(f);
1618     if (ret >= 0 && !some_ip_ok(addrs)) {
1619         if (lacks_ipp != 0)
1620             *lacks_ipp = 1;
1621         ret = -1;
1622     }
1623     if (addrs != 0)
1624         free_wordlist(addrs);
1625
1626     return ret >= 0;
1627 }
1628
1629
1630 /*
1631  * have_chap_secret - check whether we have a CHAP file with a
1632  * secret that we could possibly use for authenticating `client'
1633  * on `server'.  Either can be the null string, meaning we don't
1634  * know the identity yet.
1635  */
1636 static int
1637 have_chap_secret(client, server, need_ip, lacks_ipp)
1638     char *client;
1639     char *server;
1640     int need_ip;
1641     int *lacks_ipp;
1642 {
1643     FILE *f;
1644     int ret;
1645     char *filename;
1646     struct wordlist *addrs;
1647
1648     filename = _PATH_CHAPFILE;
1649     f = fopen(filename, "r");
1650     if (f == NULL)
1651         return 0;
1652
1653     if (client != NULL && client[0] == 0)
1654         client = NULL;
1655     else if (server != NULL && server[0] == 0)
1656         server = NULL;
1657
1658     ret = scan_authfile(f, client, server, NULL, &addrs, NULL, filename);
1659     fclose(f);
1660     if (ret >= 0 && need_ip && !some_ip_ok(addrs)) {
1661         if (lacks_ipp != 0)
1662             *lacks_ipp = 1;
1663         ret = -1;
1664     }
1665     if (addrs != 0)
1666         free_wordlist(addrs);
1667
1668     return ret >= 0;
1669 }
1670
1671
1672 /*
1673  * get_secret - open the CHAP secret file and return the secret
1674  * for authenticating the given client on the given server.
1675  * (We could be either client or server).
1676  */
1677 int
1678 get_secret(unit, client, server, secret, secret_len, am_server)
1679     int unit;
1680     char *client;
1681     char *server;
1682     char *secret;
1683     int *secret_len;
1684     int am_server;
1685 {
1686     FILE *f;
1687     int ret, len;
1688     char *filename;
1689     struct wordlist *addrs, *opts;
1690     char secbuf[MAXWORDLEN];
1691
1692     if (!am_server && passwd[0] != 0) {
1693         strlcpy(secbuf, passwd, sizeof(secbuf));
1694     } else {
1695         filename = _PATH_CHAPFILE;
1696         addrs = NULL;
1697         secbuf[0] = 0;
1698
1699         f = fopen(filename, "r");
1700         if (f == NULL) {
1701             error("Can't open chap secret file %s: %m", filename);
1702             return 0;
1703         }
1704         check_access(f, filename);
1705
1706         ret = scan_authfile(f, client, server, secbuf, &addrs, &opts, filename);
1707         fclose(f);
1708         if (ret < 0)
1709             return 0;
1710
1711         if (am_server)
1712             set_allowed_addrs(unit, addrs, opts);
1713         else if (opts != 0)
1714             free_wordlist(opts);
1715         if (addrs != 0)
1716             free_wordlist(addrs);
1717     }
1718
1719     len = strlen(secbuf);
1720     if (len > MAXSECRETLEN) {
1721         error("Secret for %s on %s is too long", client, server);
1722         len = MAXSECRETLEN;
1723     }
1724     BCOPY(secbuf, secret, len);
1725     BZERO(secbuf, sizeof(secbuf));
1726     *secret_len = len;
1727
1728     return 1;
1729 }
1730
1731 /*
1732  * set_allowed_addrs() - set the list of allowed addresses.
1733  * Also looks for `--' indicating options to apply for this peer
1734  * and leaves the following words in extra_options.
1735  */
1736 static void
1737 set_allowed_addrs(unit, addrs, opts)
1738     int unit;
1739     struct wordlist *addrs;
1740     struct wordlist *opts;
1741 {
1742     int n;
1743     struct wordlist *ap, **plink;
1744     struct permitted_ip *ip;
1745     char *ptr_word, *ptr_mask;
1746     struct hostent *hp;
1747     struct netent *np;
1748     u_int32_t a, mask, ah, offset;
1749     struct ipcp_options *wo = &ipcp_wantoptions[unit];
1750     u_int32_t suggested_ip = 0;
1751
1752     if (addresses[unit] != NULL)
1753         free(addresses[unit]);
1754     addresses[unit] = NULL;
1755     if (extra_options != NULL)
1756         free_wordlist(extra_options);
1757     extra_options = opts;
1758
1759     /*
1760      * Count the number of IP addresses given.
1761      */
1762     n = wordlist_count(addrs) + wordlist_count(noauth_addrs);
1763     if (n == 0)
1764         return;
1765     ip = (struct permitted_ip *) malloc((n + 1) * sizeof(struct permitted_ip));
1766     if (ip == 0)
1767         return;
1768
1769     /* temporarily append the noauth_addrs list to addrs */
1770     for (plink = &addrs; *plink != NULL; plink = &(*plink)->next)
1771         ;
1772     *plink = noauth_addrs;
1773
1774     n = 0;
1775     for (ap = addrs; ap != NULL; ap = ap->next) {
1776         /* "-" means no addresses authorized, "*" means any address allowed */
1777         ptr_word = ap->word;
1778         if (strcmp(ptr_word, "-") == 0)
1779             break;
1780         if (strcmp(ptr_word, "*") == 0) {
1781             ip[n].permit = 1;
1782             ip[n].base = ip[n].mask = 0;
1783             ++n;
1784             break;
1785         }
1786
1787         ip[n].permit = 1;
1788         if (*ptr_word == '!') {
1789             ip[n].permit = 0;
1790             ++ptr_word;
1791         }
1792
1793         mask = ~ (u_int32_t) 0;
1794         offset = 0;
1795         ptr_mask = strchr (ptr_word, '/');
1796         if (ptr_mask != NULL) {
1797             int bit_count;
1798             char *endp;
1799
1800             bit_count = (int) strtol (ptr_mask+1, &endp, 10);
1801             if (bit_count <= 0 || bit_count > 32) {
1802                 warn("invalid address length %v in auth. address list",
1803                      ptr_mask+1);
1804                 continue;
1805             }
1806             bit_count = 32 - bit_count; /* # bits in host part */
1807             if (*endp == '+') {
1808                 offset = ifunit + 1;
1809                 ++endp;
1810             }
1811             if (*endp != 0) {
1812                 warn("invalid address length syntax: %v", ptr_mask+1);
1813                 continue;
1814             }
1815             *ptr_mask = '\0';
1816             mask <<= bit_count;
1817         }
1818
1819         hp = gethostbyname(ptr_word);
1820         if (hp != NULL && hp->h_addrtype == AF_INET) {
1821             a = *(u_int32_t *)hp->h_addr;
1822         } else {
1823             np = getnetbyname (ptr_word);
1824             if (np != NULL && np->n_addrtype == AF_INET) {
1825                 a = htonl (*(u_int32_t *)np->n_net);
1826                 if (ptr_mask == NULL) {
1827                     /* calculate appropriate mask for net */
1828                     ah = ntohl(a);
1829                     if (IN_CLASSA(ah))
1830                         mask = IN_CLASSA_NET;
1831                     else if (IN_CLASSB(ah))
1832                         mask = IN_CLASSB_NET;
1833                     else if (IN_CLASSC(ah))
1834                         mask = IN_CLASSC_NET;
1835                 }
1836             } else {
1837                 a = inet_addr (ptr_word);
1838             }
1839         }
1840
1841         if (ptr_mask != NULL)
1842             *ptr_mask = '/';
1843
1844         if (a == (u_int32_t)-1L) {
1845             warn("unknown host %s in auth. address list", ap->word);
1846             continue;
1847         }
1848         if (offset != 0) {
1849             if (offset >= ~mask) {
1850                 warn("interface unit %d too large for subnet %v",
1851                      ifunit, ptr_word);
1852                 continue;
1853             }
1854             a = htonl((ntohl(a) & mask) + offset);
1855             mask = ~(u_int32_t)0;
1856         }
1857         ip[n].mask = htonl(mask);
1858         ip[n].base = a & ip[n].mask;
1859         ++n;
1860         if (~mask == 0 && suggested_ip == 0)
1861             suggested_ip = a;
1862     }
1863     *plink = NULL;
1864
1865     ip[n].permit = 0;           /* make the last entry forbid all addresses */
1866     ip[n].base = 0;             /* to terminate the list */
1867     ip[n].mask = 0;
1868
1869     addresses[unit] = ip;
1870
1871     /*
1872      * If the address given for the peer isn't authorized, or if
1873      * the user hasn't given one, AND there is an authorized address
1874      * which is a single host, then use that if we find one.
1875      */
1876     if (suggested_ip != 0
1877         && (wo->hisaddr == 0 || !auth_ip_addr(unit, wo->hisaddr))) {
1878         wo->hisaddr = suggested_ip;
1879         /*
1880          * Do we insist on this address?  No, if there are other
1881          * addresses authorized than the suggested one.
1882          */
1883         if (n > 1)
1884             wo->accept_remote = 1;
1885     }
1886 }
1887
1888 /*
1889  * auth_ip_addr - check whether the peer is authorized to use
1890  * a given IP address.  Returns 1 if authorized, 0 otherwise.
1891  */
1892 int
1893 auth_ip_addr(unit, addr)
1894     int unit;
1895     u_int32_t addr;
1896 {
1897     int ok;
1898
1899     /* don't allow loopback or multicast address */
1900     if (bad_ip_adrs(addr))
1901         return 0;
1902
1903     if (addresses[unit] != NULL) {
1904         ok = ip_addr_check(addr, addresses[unit]);
1905         if (ok >= 0)
1906             return ok;
1907     }
1908     if (auth_required)
1909         return 0;               /* no addresses authorized */
1910     return allow_any_ip || privileged || !have_route_to(addr);
1911 }
1912
1913 static int
1914 ip_addr_check(addr, addrs)
1915     u_int32_t addr;
1916     struct permitted_ip *addrs;
1917 {
1918     for (; ; ++addrs)
1919         if ((addr & addrs->mask) == addrs->base)
1920             return addrs->permit;
1921 }
1922
1923 /*
1924  * bad_ip_adrs - return 1 if the IP address is one we don't want
1925  * to use, such as an address in the loopback net or a multicast address.
1926  * addr is in network byte order.
1927  */
1928 int
1929 bad_ip_adrs(addr)
1930     u_int32_t addr;
1931 {
1932     addr = ntohl(addr);
1933     return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
1934         || IN_MULTICAST(addr) || IN_BADCLASS(addr);
1935 }
1936
1937 /*
1938  * some_ip_ok - check a wordlist to see if it authorizes any
1939  * IP address(es).
1940  */
1941 static int
1942 some_ip_ok(addrs)
1943     struct wordlist *addrs;
1944 {
1945     for (; addrs != 0; addrs = addrs->next) {
1946         if (addrs->word[0] == '-')
1947             break;
1948         if (addrs->word[0] != '!')
1949             return 1;           /* some IP address is allowed */
1950     }
1951     return 0;
1952 }
1953
1954 /*
1955  * check_access - complain if a secret file has too-liberal permissions.
1956  */
1957 static void
1958 check_access(f, filename)
1959     FILE *f;
1960     char *filename;
1961 {
1962     struct stat sbuf;
1963
1964     if (fstat(fileno(f), &sbuf) < 0) {
1965         warn("cannot stat secret file %s: %m", filename);
1966     } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1967         warn("Warning - secret file %s has world and/or group access",
1968              filename);
1969     }
1970 }
1971
1972
1973 /*
1974  * scan_authfile - Scan an authorization file for a secret suitable
1975  * for authenticating `client' on `server'.  The return value is -1
1976  * if no secret is found, otherwise >= 0.  The return value has
1977  * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
1978  * NONWILD_SERVER set if the secret didn't have "*" for the server.
1979  * Any following words on the line up to a "--" (i.e. address authorization
1980  * info) are placed in a wordlist and returned in *addrs.  Any
1981  * following words (extra options) are placed in a wordlist and
1982  * returned in *opts.
1983  * We assume secret is NULL or points to MAXWORDLEN bytes of space.
1984  */
1985 static int
1986 scan_authfile(f, client, server, secret, addrs, opts, filename)
1987     FILE *f;
1988     char *client;
1989     char *server;
1990     char *secret;
1991     struct wordlist **addrs;
1992     struct wordlist **opts;
1993     char *filename;
1994 {
1995     int newline, xxx;
1996     int got_flag, best_flag;
1997     FILE *sf;
1998     struct wordlist *ap, *addr_list, *alist, **app;
1999     char word[MAXWORDLEN];
2000     char atfile[MAXWORDLEN];
2001     char lsecret[MAXWORDLEN];
2002
2003     if (addrs != NULL)
2004         *addrs = NULL;
2005     if (opts != NULL)
2006         *opts = NULL;
2007     addr_list = NULL;
2008     if (!getword(f, word, &newline, filename))
2009         return -1;              /* file is empty??? */
2010     newline = 1;
2011     best_flag = -1;
2012     for (;;) {
2013         /*
2014          * Skip until we find a word at the start of a line.
2015          */
2016         while (!newline && getword(f, word, &newline, filename))
2017             ;
2018         if (!newline)
2019             break;              /* got to end of file */
2020
2021         /*
2022          * Got a client - check if it's a match or a wildcard.
2023          */
2024         got_flag = 0;
2025         if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
2026             newline = 0;
2027             continue;
2028         }
2029         if (!ISWILD(word))
2030             got_flag = NONWILD_CLIENT;
2031
2032         /*
2033          * Now get a server and check if it matches.
2034          */
2035         if (!getword(f, word, &newline, filename))
2036             break;
2037         if (newline)
2038             continue;
2039         if (!ISWILD(word)) {
2040             if (server != NULL && strcmp(word, server) != 0)
2041                 continue;
2042             got_flag |= NONWILD_SERVER;
2043         }
2044
2045         /*
2046          * Got some sort of a match - see if it's better than what
2047          * we have already.
2048          */
2049         if (got_flag <= best_flag)
2050             continue;
2051
2052         /*
2053          * Get the secret.
2054          */
2055         if (!getword(f, word, &newline, filename))
2056             break;
2057         if (newline)
2058             continue;
2059
2060         if (secret != NULL) {
2061             /*
2062              * Special syntax: @/pathname means read secret from file.
2063              */
2064             if (word[0] == '@' && word[1] == '/') {
2065                 strlcpy(atfile, word+1, sizeof(atfile));
2066                 if ((sf = fopen(atfile, "r")) == NULL) {
2067                     warn("can't open indirect secret file %s", atfile);
2068                     continue;
2069                 }
2070                 check_access(sf, atfile);
2071                 if (!getword(sf, word, &xxx, atfile)) {
2072                     warn("no secret in indirect secret file %s", atfile);
2073                     fclose(sf);
2074                     continue;
2075                 }
2076                 fclose(sf);
2077             }
2078             strlcpy(lsecret, word, sizeof(lsecret));
2079         }
2080
2081         /*
2082          * Now read address authorization info and make a wordlist.
2083          */
2084         app = &alist;
2085         for (;;) {
2086             if (!getword(f, word, &newline, filename) || newline)
2087                 break;
2088             ap = (struct wordlist *)
2089                     malloc(sizeof(struct wordlist) + strlen(word) + 1);
2090             if (ap == NULL)
2091                 novm("authorized addresses");
2092             ap->word = (char *) (ap + 1);
2093             strcpy(ap->word, word);
2094             *app = ap;
2095             app = &ap->next;
2096         }
2097         *app = NULL;
2098
2099         /*
2100          * This is the best so far; remember it.
2101          */
2102         best_flag = got_flag;
2103         if (addr_list)
2104             free_wordlist(addr_list);
2105         addr_list = alist;
2106         if (secret != NULL)
2107             strlcpy(secret, lsecret, MAXWORDLEN);
2108
2109         if (!newline)
2110             break;
2111     }
2112
2113     /* scan for a -- word indicating the start of options */
2114     for (app = &addr_list; (ap = *app) != NULL; app = &ap->next)
2115         if (strcmp(ap->word, "--") == 0)
2116             break;
2117     /* ap = start of options */
2118     if (ap != NULL) {
2119         ap = ap->next;          /* first option */
2120         free(*app);                     /* free the "--" word */
2121         *app = NULL;            /* terminate addr list */
2122     }
2123     if (opts != NULL)
2124         *opts = ap;
2125     else if (ap != NULL)
2126         free_wordlist(ap);
2127     if (addrs != NULL)
2128         *addrs = addr_list;
2129     else if (addr_list != NULL)
2130         free_wordlist(addr_list);
2131
2132     return best_flag;
2133 }
2134
2135 /*
2136  * wordlist_count - return the number of items in a wordlist
2137  */
2138 static int
2139 wordlist_count(wp)
2140     struct wordlist *wp;
2141 {
2142     int n;
2143
2144     for (n = 0; wp != NULL; wp = wp->next)
2145         ++n;
2146     return n;
2147 }
2148
2149 /*
2150  * free_wordlist - release memory allocated for a wordlist.
2151  */
2152 static void
2153 free_wordlist(wp)
2154     struct wordlist *wp;
2155 {
2156     struct wordlist *next;
2157
2158     while (wp != NULL) {
2159         next = wp->next;
2160         free(wp);
2161         wp = next;
2162     }
2163 }
2164
2165 /*
2166  * auth_script_done - called when the auth-up or auth-down script
2167  * has finished.
2168  */
2169 static void
2170 auth_script_done(arg)
2171     void *arg;
2172 {
2173     auth_script_pid = 0;
2174     switch (auth_script_state) {
2175     case s_up:
2176         if (auth_state == s_down) {
2177             auth_script_state = s_down;
2178             auth_script(_PATH_AUTHDOWN);
2179         }
2180         break;
2181     case s_down:
2182         if (auth_state == s_up) {
2183             auth_script_state = s_up;
2184             auth_script(_PATH_AUTHUP);
2185         }
2186         break;
2187     }
2188 }
2189
2190 /*
2191  * auth_script - execute a script with arguments
2192  * interface-name peer-name real-user tty speed
2193  */
2194 static void
2195 auth_script(script)
2196     char *script;
2197 {
2198     char strspeed[32];
2199     struct passwd *pw;
2200     char struid[32];
2201     char *user_name;
2202     char *argv[8];
2203
2204     if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
2205         user_name = pw->pw_name;
2206     else {
2207         slprintf(struid, sizeof(struid), "%d", getuid());
2208         user_name = struid;
2209     }
2210     slprintf(strspeed, sizeof(strspeed), "%d", baud_rate);
2211
2212     argv[0] = script;
2213     argv[1] = ifname;
2214     argv[2] = peer_authname;
2215     argv[3] = user_name;
2216     argv[4] = devnam;
2217     argv[5] = strspeed;
2218     argv[6] = NULL;
2219
2220     auth_script_pid = run_program(script, argv, 0, auth_script_done, NULL);
2221 }