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