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