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