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