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