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