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