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