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