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