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