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