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