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