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