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