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