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