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