]> git.ozlabs.org Git - ppp.git/blob - pppd/auth.c
changes to linux interface for new kernel driver,
[ppp.git] / pppd / auth.c
1 /*
2  * auth.c - PPP authentication and phase control.
3  *
4  * Copyright (c) 1993 The Australian National University.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms are permitted
8  * provided that the above copyright notice and this paragraph are
9  * duplicated in all such forms and that any documentation,
10  * advertising materials, and other materials related to such
11  * distribution and use acknowledge that the software was developed
12  * by the Australian National University.  The name of the University
13  * may not be used to endorse or promote products derived from this
14  * software without specific prior written permission.
15  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18  *
19  * Copyright (c) 1989 Carnegie Mellon University.
20  * All rights reserved.
21  *
22  * Redistribution and use in source and binary forms are permitted
23  * provided that the above copyright notice and this paragraph are
24  * duplicated in all such forms and that any documentation,
25  * advertising materials, and other materials related to such
26  * distribution and use acknowledge that the software was developed
27  * by Carnegie Mellon University.  The name of the
28  * University may not be used to endorse or promote products derived
29  * from this software without specific prior written permission.
30  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
32  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
33  */
34
35 #define RCSID   "$Id: auth.c,v 1.62 2000/03/27 06:02:59 paulus Exp $"
36
37 #include <stdio.h>
38 #include <stddef.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 #include <pwd.h>
42 #include <grp.h>
43 #include <string.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/socket.h>
47 #include <utmp.h>
48 #include <fcntl.h>
49 #if defined(_PATH_LASTLOG) && defined(_linux_)
50 #include <lastlog.h>
51 #endif
52
53 #include <netdb.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56
57 #ifdef USE_PAM
58 #include <security/pam_appl.h>
59 #endif
60
61 #ifdef HAS_SHADOW
62 #include <shadow.h>
63 #ifndef PW_PPP
64 #define PW_PPP PW_LOGIN
65 #endif
66 #endif
67
68 #include "pppd.h"
69 #include "fsm.h"
70 #include "lcp.h"
71 #include "ipcp.h"
72 #include "upap.h"
73 #include "chap.h"
74 #ifdef CBCP_SUPPORT
75 #include "cbcp.h"
76 #endif
77 #include "pathnames.h"
78
79 static const char rcsid[] = RCSID;
80
81 /* Bits in scan_authfile return value */
82 #define NONWILD_SERVER  1
83 #define NONWILD_CLIENT  2
84
85 #define ISWILD(word)    (word[0] == '*' && word[1] == 0)
86
87 /* The name by which the peer authenticated itself to us. */
88 char peer_authname[MAXNAMELEN];
89
90 /* Records which authentication operations haven't completed yet. */
91 static int auth_pending[NUM_PPP];
92
93 /* Set if we have successfully called plogin() */
94 static int logged_in;
95
96 /* List of addresses which the peer may use. */
97 static struct permitted_ip *addresses[NUM_PPP];
98
99 /* Wordlist giving addresses which the peer may use
100    without authenticating itself. */
101 static struct wordlist *noauth_addrs;
102
103 /* Extra options to apply, from the secrets file entry for the peer. */
104 static struct wordlist *extra_options;
105
106 /* Number of network protocols which we have opened. */
107 static int num_np_open;
108
109 /* Number of network protocols which have come up. */
110 static int num_np_up;
111
112 /* Set if we got the contents of passwd[] from the pap-secrets file. */
113 static int passwd_from_file;
114
115 /* Set if we require authentication only because we have a default route. */
116 static bool default_auth;
117
118 /* Hook to enable a plugin to control the idle time limit */
119 int (*idle_time_hook) __P((struct ppp_idle *)) = NULL;
120
121 /* Hook for a plugin to say whether we can possibly authenticate any peer */
122 int (*pap_check_hook) __P((void)) = NULL;
123
124 /* Hook for a plugin to check the PAP user and password */
125 int (*pap_auth_hook) __P((char *user, char *passwd, char **msgp,
126                           struct wordlist **paddrs,
127                           struct wordlist **popts)) = NULL;
128
129 /* Hook for a plugin to know about the PAP user logout */
130 void (*pap_logout_hook) __P((void)) = NULL;
131
132 /* Hook for a plugin to get the PAP password for authenticating us */
133 int (*pap_passwd_hook) __P((char *user, char *passwd)) = NULL;
134
135 /*
136  * This is used to ensure that we don't start an auth-up/down
137  * script while one is already running.
138  */
139 enum script_state {
140     s_down,
141     s_up
142 };
143
144 static enum script_state auth_state = s_down;
145 static enum script_state auth_script_state = s_down;
146 static pid_t auth_script_pid = 0;
147
148 /*
149  * Option variables.
150  */
151 bool uselogin = 0;              /* Use /etc/passwd for checking PAP */
152 bool cryptpap = 0;              /* Passwords in pap-secrets are encrypted */
153 bool refuse_pap = 0;            /* Don't wanna auth. ourselves with PAP */
154 bool refuse_chap = 0;           /* Don't wanna auth. ourselves with CHAP */
155 bool usehostname = 0;           /* Use hostname for our_name */
156 bool auth_required = 0;         /* Always require authentication from peer */
157 bool allow_any_ip = 0;          /* Allow peer to use any IP address */
158 bool explicit_remote = 0;       /* User specified explicit remote name */
159 char remote_name[MAXNAMELEN];   /* Peer's name for authentication */
160
161 /* Bits in auth_pending[] */
162 #define PAP_WITHPEER    1
163 #define PAP_PEER        2
164 #define CHAP_WITHPEER   4
165 #define CHAP_PEER       8
166
167 extern char *crypt __P((const char *, const char *));
168
169 /* Prototypes for procedures local to this file. */
170
171 static void network_phase __P((int));
172 static void check_idle __P((void *));
173 static void connect_time_expired __P((void *));
174 static int  plogin __P((char *, char *, char **));
175 static void plogout __P((void));
176 static int  null_login __P((int));
177 static int  get_pap_passwd __P((char *));
178 static int  have_pap_secret __P((int *));
179 static int  have_chap_secret __P((char *, char *, int, int *));
180 static int  ip_addr_check __P((u_int32_t, struct permitted_ip *));
181 static int  scan_authfile __P((FILE *, char *, char *, char *,
182                                struct wordlist **, struct wordlist **,
183                                char *));
184 static void free_wordlist __P((struct wordlist *));
185 static void auth_script __P((char *));
186 static void auth_script_done __P((void *));
187 static void set_allowed_addrs __P((int, struct wordlist *, struct wordlist *));
188 static int  some_ip_ok __P((struct wordlist *));
189 static int  setupapfile __P((char **));
190 static int  privgroup __P((char **));
191 static int  set_noauth_addr __P((char **));
192 static void check_access __P((FILE *, char *));
193
194 /*
195  * Authentication-related options.
196  */
197 option_t auth_options[] = {
198     { "require-pap", o_bool, &lcp_wantoptions[0].neg_upap,
199       "Require PAP authentication from peer", 1, &auth_required },
200     { "+pap", o_bool, &lcp_wantoptions[0].neg_upap,
201       "Require PAP authentication from peer", 1, &auth_required },
202     { "refuse-pap", o_bool, &refuse_pap,
203       "Don't agree to auth to peer with PAP", 1 },
204     { "-pap", o_bool, &refuse_pap,
205       "Don't allow PAP authentication with peer", 1 },
206     { "require-chap", o_bool, &lcp_wantoptions[0].neg_chap,
207       "Require CHAP authentication from peer", 1, &auth_required },
208     { "+chap", o_bool, &lcp_wantoptions[0].neg_chap,
209       "Require CHAP authentication from peer", 1, &auth_required },
210     { "refuse-chap", o_bool, &refuse_chap,
211       "Don't agree to auth to peer with CHAP", 1 },
212     { "-chap", o_bool, &refuse_chap,
213       "Don't allow CHAP authentication with peer", 1 },
214     { "name", o_string, our_name,
215       "Set local name for authentication",
216       OPT_PRIV|OPT_STATIC, NULL, MAXNAMELEN },
217     { "user", o_string, user,
218       "Set name for auth with peer", OPT_STATIC, NULL, MAXNAMELEN },
219     { "usehostname", o_bool, &usehostname,
220       "Must use hostname for authentication", 1 },
221     { "remotename", o_string, remote_name,
222       "Set remote name for authentication", OPT_STATIC,
223       &explicit_remote, MAXNAMELEN },
224     { "auth", o_bool, &auth_required,
225       "Require authentication from peer", 1 },
226     { "noauth", o_bool, &auth_required,
227       "Don't require peer to authenticate", OPT_PRIV, &allow_any_ip },
228     {  "login", o_bool, &uselogin,
229       "Use system password database for PAP", 1 },
230     { "papcrypt", o_bool, &cryptpap,
231       "PAP passwords are encrypted", 1 },
232     { "+ua", o_special, setupapfile,
233       "Get PAP user and password from file" },
234     { "password", o_string, passwd,
235       "Password for authenticating us to the peer", OPT_STATIC,
236       NULL, MAXSECRETLEN },
237     { "privgroup", o_special, privgroup,
238       "Allow group members to use privileged options", OPT_PRIV },
239     { "allow-ip", o_special, set_noauth_addr,
240       "Set IP address(es) which can be used without authentication",
241       OPT_PRIV },
242     { NULL }
243 };
244
245 /*
246  * setupapfile - specifies UPAP info for authenticating with peer.
247  */
248 static int
249 setupapfile(argv)
250     char **argv;
251 {
252     FILE * ufile;
253     int l;
254
255     lcp_allowoptions[0].neg_upap = 1;
256
257     /* open user info file */
258     seteuid(getuid());
259     ufile = fopen(*argv, "r");
260     seteuid(0);
261     if (ufile == NULL) {
262         option_error("unable to open user login data file %s", *argv);
263         return 0;
264     }
265     check_access(ufile, *argv);
266
267     /* get username */
268     if (fgets(user, MAXNAMELEN - 1, ufile) == NULL
269         || fgets(passwd, MAXSECRETLEN - 1, ufile) == NULL){
270         option_error("unable to read user login data file %s", *argv);
271         return 0;
272     }
273     fclose(ufile);
274
275     /* get rid of newlines */
276     l = strlen(user);
277     if (l > 0 && user[l-1] == '\n')
278         user[l-1] = 0;
279     l = strlen(passwd);
280     if (l > 0 && passwd[l-1] == '\n')
281         passwd[l-1] = 0;
282
283     return (1);
284 }
285
286
287 /*
288  * privgroup - allow members of the group to have privileged access.
289  */
290 static int
291 privgroup(argv)
292     char **argv;
293 {
294     struct group *g;
295     int i;
296
297     g = getgrnam(*argv);
298     if (g == 0) {
299         option_error("group %s is unknown", *argv);
300         return 0;
301     }
302     for (i = 0; i < ngroups; ++i) {
303         if (groups[i] == g->gr_gid) {
304             privileged = 1;
305             break;
306         }
307     }
308     return 1;
309 }
310
311
312 /*
313  * set_noauth_addr - set address(es) that can be used without authentication.
314  * Equivalent to specifying an entry like `"" * "" addr' in pap-secrets.
315  */
316 static int
317 set_noauth_addr(argv)
318     char **argv;
319 {
320     char *addr = *argv;
321     int l = strlen(addr);
322     struct wordlist *wp;
323
324     wp = (struct wordlist *) malloc(sizeof(struct wordlist) + l + 1);
325     if (wp == NULL)
326         novm("allow-ip argument");
327     wp->word = (char *) (wp + 1);
328     wp->next = noauth_addrs;
329     BCOPY(addr, wp->word, l);
330     noauth_addrs = wp;
331     return 1;
332 }
333
334
335 /*
336  * An Open on LCP has requested a change from Dead to Establish phase.
337  * Do what's necessary to bring the physical layer up.
338  */
339 void
340 link_required(unit)
341     int unit;
342 {
343 }
344
345 /*
346  * LCP has terminated the link; go to the Dead phase and take the
347  * physical layer down.
348  */
349 void
350 link_terminated(unit)
351     int unit;
352 {
353     if (phase == PHASE_DEAD)
354         return;
355     if (pap_logout_hook) {
356         pap_logout_hook();
357     } else {
358         if (logged_in)
359             plogout();
360     }
361     new_phase(PHASE_DEAD);
362     notice("Connection terminated.");
363 }
364
365 /*
366  * LCP has gone down; it will either die or try to re-establish.
367  */
368 void
369 link_down(unit)
370     int unit;
371 {
372     int i;
373     struct protent *protp;
374
375     auth_state = s_down;
376     if (auth_script_state == s_up && auth_script_pid == 0) {
377         update_link_stats(unit);
378         auth_script_state = s_down;
379         auth_script(_PATH_AUTHDOWN);
380     }
381     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
382         if (!protp->enabled_flag)
383             continue;
384         if (protp->protocol != PPP_LCP && protp->lowerdown != NULL)
385             (*protp->lowerdown)(unit);
386         if (protp->protocol < 0xC000 && protp->close != NULL)
387             (*protp->close)(unit, "LCP down");
388     }
389     num_np_open = 0;
390     num_np_up = 0;
391     if (phase != PHASE_DEAD)
392         new_phase(PHASE_TERMINATE);
393 }
394
395 /*
396  * The link is established.
397  * Proceed to the Dead, Authenticate or Network phase as appropriate.
398  */
399 void
400 link_established(unit)
401     int unit;
402 {
403     int auth;
404     lcp_options *wo = &lcp_wantoptions[unit];
405     lcp_options *go = &lcp_gotoptions[unit];
406     lcp_options *ho = &lcp_hisoptions[unit];
407     int i;
408     struct protent *protp;
409
410     /*
411      * Tell higher-level protocols that LCP is up.
412      */
413     for (i = 0; (protp = protocols[i]) != NULL; ++i)
414         if (protp->protocol != PPP_LCP && protp->enabled_flag
415             && protp->lowerup != NULL)
416             (*protp->lowerup)(unit);
417
418     if (auth_required && !(go->neg_chap || go->neg_upap)) {
419         /*
420          * We wanted the peer to authenticate itself, and it refused:
421          * if we have some address(es) it can use without auth, fine,
422          * otherwise treat it as though it authenticated with PAP using
423          * a username * of "" and a password of "".  If that's not OK,
424          * boot it out.
425          */
426         if (noauth_addrs != NULL) {
427             set_allowed_addrs(unit, noauth_addrs, NULL);
428         } else if (!wo->neg_upap || !null_login(unit)) {
429             warn("peer refused to authenticate: terminating link");
430             lcp_close(unit, "peer refused to authenticate");
431             status = EXIT_PEER_AUTH_FAILED;
432             return;
433         }
434     }
435
436     new_phase(PHASE_AUTHENTICATE);
437     auth = 0;
438     if (go->neg_chap) {
439         ChapAuthPeer(unit, our_name, go->chap_mdtype);
440         auth |= CHAP_PEER;
441     } else if (go->neg_upap) {
442         upap_authpeer(unit);
443         auth |= PAP_PEER;
444     }
445     if (ho->neg_chap) {
446         ChapAuthWithPeer(unit, user, ho->chap_mdtype);
447         auth |= CHAP_WITHPEER;
448     } else if (ho->neg_upap) {
449         if (passwd[0] == 0) {
450             passwd_from_file = 1;
451             if (!get_pap_passwd(passwd))
452                 error("No secret found for PAP login");
453         }
454         upap_authwithpeer(unit, user, passwd);
455         auth |= PAP_WITHPEER;
456     }
457     auth_pending[unit] = auth;
458
459     if (!auth)
460         network_phase(unit);
461 }
462
463 /*
464  * Proceed to the network phase.
465  */
466 static void
467 network_phase(unit)
468     int unit;
469 {
470     lcp_options *go = &lcp_gotoptions[unit];
471
472     /*
473      * If the peer had to authenticate, run the auth-up script now.
474      */
475     if (go->neg_chap || go->neg_upap) {
476         auth_state = s_up;
477         if (auth_script_state == s_down && auth_script_pid == 0) {
478             auth_script_state = s_up;
479             auth_script(_PATH_AUTHUP);
480         }
481     }
482
483 #ifdef CBCP_SUPPORT
484     /*
485      * If we negotiated callback, do it now.
486      */
487     if (go->neg_cbcp) {
488         new_phase(PHASE_CALLBACK);
489         (*cbcp_protent.open)(unit);
490         return;
491     }
492 #endif
493
494     /*
495      * Process extra options from the secrets file
496      */
497     if (extra_options) {
498         options_from_list(extra_options, 1);
499         free_wordlist(extra_options);
500         extra_options = 0;
501     }
502     start_networks();
503 }
504
505 void
506 start_networks()
507 {
508     int i;
509     struct protent *protp;
510
511     new_phase(PHASE_NETWORK);
512
513 #if 0
514     if (!demand)
515         set_filters(&pass_filter, &active_filter);
516 #endif
517     for (i = 0; (protp = protocols[i]) != NULL; ++i)
518         if (protp->protocol < 0xC000 && protp->enabled_flag
519             && protp->open != NULL) {
520             (*protp->open)(0);
521             if (protp->protocol != PPP_CCP)
522                 ++num_np_open;
523         }
524
525     if (num_np_open == 0)
526         /* nothing to do */
527         lcp_close(0, "No network protocols running");
528 }
529
530 /*
531  * The peer has failed to authenticate himself using `protocol'.
532  */
533 void
534 auth_peer_fail(unit, protocol)
535     int unit, protocol;
536 {
537     /*
538      * Authentication failure: take the link down
539      */
540     lcp_close(unit, "Authentication failed");
541     status = EXIT_PEER_AUTH_FAILED;
542 }
543
544 /*
545  * The peer has been successfully authenticated using `protocol'.
546  */
547 void
548 auth_peer_success(unit, protocol, name, namelen)
549     int unit, protocol;
550     char *name;
551     int namelen;
552 {
553     int bit;
554
555     switch (protocol) {
556     case PPP_CHAP:
557         bit = CHAP_PEER;
558         break;
559     case PPP_PAP:
560         bit = PAP_PEER;
561         break;
562     default:
563         warn("auth_peer_success: unknown protocol %x", protocol);
564         return;
565     }
566
567     /*
568      * Save the authenticated name of the peer for later.
569      */
570     if (namelen > sizeof(peer_authname) - 1)
571         namelen = sizeof(peer_authname) - 1;
572     BCOPY(name, peer_authname, namelen);
573     peer_authname[namelen] = 0;
574     script_setenv("PEERNAME", peer_authname);
575
576     /*
577      * If there is no more authentication still to be done,
578      * proceed to the network (or callback) phase.
579      */
580     if ((auth_pending[unit] &= ~bit) == 0)
581         network_phase(unit);
582 }
583
584 /*
585  * We have failed to authenticate ourselves to the peer using `protocol'.
586  */
587 void
588 auth_withpeer_fail(unit, protocol)
589     int unit, protocol;
590 {
591     if (passwd_from_file)
592         BZERO(passwd, MAXSECRETLEN);
593     /*
594      * We've failed to authenticate ourselves to our peer.
595      * Some servers keep sending CHAP challenges, but there
596      * is no point in persisting without any way to get updated
597      * authentication secrets.
598      */
599     lcp_close(unit, "Failed to authenticate ourselves to peer");
600     status = EXIT_AUTH_TOPEER_FAILED;
601 }
602
603 /*
604  * We have successfully authenticated ourselves with the peer using `protocol'.
605  */
606 void
607 auth_withpeer_success(unit, protocol)
608     int unit, protocol;
609 {
610     int bit;
611
612     switch (protocol) {
613     case PPP_CHAP:
614         bit = CHAP_WITHPEER;
615         break;
616     case PPP_PAP:
617         if (passwd_from_file)
618             BZERO(passwd, MAXSECRETLEN);
619         bit = PAP_WITHPEER;
620         break;
621     default:
622         warn("auth_withpeer_success: unknown protocol %x", protocol);
623         bit = 0;
624     }
625
626     /*
627      * If there is no more authentication still being done,
628      * proceed to the network (or callback) phase.
629      */
630     if ((auth_pending[unit] &= ~bit) == 0)
631         network_phase(unit);
632 }
633
634
635 /*
636  * np_up - a network protocol has come up.
637  */
638 void
639 np_up(unit, proto)
640     int unit, proto;
641 {
642     int tlim;
643
644     if (num_np_up == 0) {
645         /*
646          * At this point we consider that the link has come up successfully.
647          */
648         status = EXIT_OK;
649         unsuccess = 0;
650         new_phase(PHASE_RUNNING);
651
652         if (idle_time_hook != 0)
653             tlim = (*idle_time_hook)(NULL);
654         else
655             tlim = idle_time_limit;
656         if (tlim > 0)
657             TIMEOUT(check_idle, NULL, tlim);
658
659         /*
660          * Set a timeout to close the connection once the maximum
661          * connect time has expired.
662          */
663         if (maxconnect > 0)
664             TIMEOUT(connect_time_expired, 0, maxconnect);
665
666         /*
667          * Detach now, if the updetach option was given.
668          */
669         if (updetach && !nodetach)
670             detach();
671     }
672     ++num_np_up;
673 }
674
675 /*
676  * np_down - a network protocol has gone down.
677  */
678 void
679 np_down(unit, proto)
680     int unit, proto;
681 {
682     if (--num_np_up == 0) {
683         UNTIMEOUT(check_idle, NULL);
684         new_phase(PHASE_NETWORK);
685     }
686 }
687
688 /*
689  * np_finished - a network protocol has finished using the link.
690  */
691 void
692 np_finished(unit, proto)
693     int unit, proto;
694 {
695     if (--num_np_open <= 0) {
696         /* no further use for the link: shut up shop. */
697         lcp_close(0, "No network protocols running");
698     }
699 }
700
701 /*
702  * check_idle - check whether the link has been idle for long
703  * enough that we can shut it down.
704  */
705 static void
706 check_idle(arg)
707     void *arg;
708 {
709     struct ppp_idle idle;
710     time_t itime;
711     int tlim;
712
713     if (!get_idle_time(0, &idle))
714         return;
715     if (idle_time_hook != 0) {
716         tlim = idle_time_hook(&idle);
717     } else {
718         itime = MIN(idle.xmit_idle, idle.recv_idle);
719         tlim = idle_time_limit - itime;
720     }
721     if (tlim <= 0) {
722         /* link is idle: shut it down. */
723         notice("Terminating connection due to lack of activity.");
724         lcp_close(0, "Link inactive");
725         need_holdoff = 0;
726         status = EXIT_IDLE_TIMEOUT;
727     } else {
728         TIMEOUT(check_idle, NULL, tlim);
729     }
730 }
731
732 /*
733  * connect_time_expired - log a message and close the connection.
734  */
735 static void
736 connect_time_expired(arg)
737     void *arg;
738 {
739     info("Connect time expired");
740     lcp_close(0, "Connect time expired");       /* Close connection */
741     status = EXIT_CONNECT_TIME;
742 }
743
744 /*
745  * auth_check_options - called to check authentication options.
746  */
747 void
748 auth_check_options()
749 {
750     lcp_options *wo = &lcp_wantoptions[0];
751     int can_auth;
752     int lacks_ip;
753
754     /* Default our_name to hostname, and user to our_name */
755     if (our_name[0] == 0 || usehostname)
756         strlcpy(our_name, hostname, sizeof(our_name));
757     if (user[0] == 0)
758         strlcpy(user, our_name, sizeof(user));
759
760     /*
761      * If we have a default route, require the peer to authenticate
762      * unless the noauth option was given or the real user is root.
763      */
764     if (!auth_required && !allow_any_ip && have_route_to(0) && !privileged) {
765         auth_required = 1;
766         default_auth = 1;
767     }
768
769     /* If authentication is required, ask peer for CHAP or PAP. */
770     if (auth_required) {
771         if (!wo->neg_chap && !wo->neg_upap) {
772             wo->neg_chap = 1;
773             wo->neg_upap = 1;
774         }
775     } else {
776         wo->neg_chap = 0;
777         wo->neg_upap = 0;
778     }
779
780     /*
781      * Check whether we have appropriate secrets to use
782      * to authenticate the peer.
783      */
784     lacks_ip = 0;
785     can_auth = wo->neg_upap && (uselogin || have_pap_secret(&lacks_ip));
786     if (!can_auth && wo->neg_chap) {
787         can_auth = have_chap_secret((explicit_remote? remote_name: NULL),
788                                     our_name, 1, &lacks_ip);
789     }
790
791     if (auth_required && !can_auth && noauth_addrs == NULL) {
792         if (default_auth) {
793             option_error(
794 "By default the remote system is required to authenticate itself");
795             option_error(
796 "(because this system has a default route to the internet)");
797         } else if (explicit_remote)
798             option_error(
799 "The remote system (%s) is required to authenticate itself",
800                          remote_name);
801         else
802             option_error(
803 "The remote system is required to authenticate itself");
804         option_error(
805 "but I couldn't find any suitable secret (password) for it to use to do so.");
806         if (lacks_ip)
807             option_error(
808 "(None of the available passwords would let it use an IP address.)");
809
810         exit(1);
811     }
812 }
813
814 /*
815  * auth_reset - called when LCP is starting negotiations to recheck
816  * authentication options, i.e. whether we have appropriate secrets
817  * to use for authenticating ourselves and/or the peer.
818  */
819 void
820 auth_reset(unit)
821     int unit;
822 {
823     lcp_options *go = &lcp_gotoptions[unit];
824     lcp_options *ao = &lcp_allowoptions[0];
825
826     ao->neg_upap = !refuse_pap && (passwd[0] != 0 || get_pap_passwd(NULL));
827     ao->neg_chap = !refuse_chap
828         && (passwd[0] != 0
829             || have_chap_secret(user, (explicit_remote? remote_name: NULL),
830                                 0, NULL));
831
832     if (go->neg_upap && !uselogin && !have_pap_secret(NULL))
833         go->neg_upap = 0;
834     if (go->neg_chap) {
835         if (!have_chap_secret((explicit_remote? remote_name: NULL),
836                               our_name, 1, NULL))
837             go->neg_chap = 0;
838     }
839 }
840
841
842 /*
843  * check_passwd - Check the user name and passwd against the PAP secrets
844  * file.  If requested, also check against the system password database,
845  * and login the user if OK.
846  *
847  * returns:
848  *      UPAP_AUTHNAK: Authentication failed.
849  *      UPAP_AUTHACK: Authentication succeeded.
850  * In either case, msg points to an appropriate message.
851  */
852 int
853 check_passwd(unit, auser, userlen, apasswd, passwdlen, msg)
854     int unit;
855     char *auser;
856     int userlen;
857     char *apasswd;
858     int passwdlen;
859     char **msg;
860 {
861     int ret;
862     char *filename;
863     FILE *f;
864     struct wordlist *addrs = NULL, *opts = NULL;
865     char passwd[256], user[256];
866     char secret[MAXWORDLEN];
867     static int attempts = 0;
868
869     /*
870      * Make copies of apasswd and auser, then null-terminate them.
871      * If there are unprintable characters in the password, make
872      * them visible.
873      */
874     slprintf(passwd, sizeof(passwd), "%.*v", passwdlen, apasswd);
875     slprintf(user, sizeof(user), "%.*v", userlen, auser);
876     *msg = "";
877
878     /*
879      * Check if a plugin wants to handle this.
880      */
881     if (pap_auth_hook) {
882         ret = (*pap_auth_hook)(user, passwd, msg, &addrs, &opts);
883         if (ret >= 0) {
884             if (ret)
885                 set_allowed_addrs(unit, addrs, opts);
886             BZERO(passwd, sizeof(passwd));
887             if (addrs != 0)
888                 free_wordlist(addrs);
889             return ret? UPAP_AUTHACK: UPAP_AUTHNAK;
890         }
891     }
892
893     /*
894      * Open the file of pap secrets and scan for a suitable secret
895      * for authenticating this user.
896      */
897     filename = _PATH_UPAPFILE;
898     addrs = opts = NULL;
899     ret = UPAP_AUTHNAK;
900     f = fopen(filename, "r");
901     if (f == NULL) {
902         error("Can't open PAP password file %s: %m", filename);
903
904     } else {
905         check_access(f, filename);
906         if (scan_authfile(f, user, our_name, secret, &addrs, &opts, filename) < 0) {
907             warn("no PAP secret found for %s", user);
908         } else if (secret[0] != 0) {
909             /* password given in pap-secrets - must match */
910             if ((!cryptpap && strcmp(passwd, secret) == 0)
911                 || strcmp(crypt(passwd, secret), secret) == 0)
912                 ret = UPAP_AUTHACK;
913             else
914                 warn("PAP authentication failure for %s", user);
915         } else if (uselogin) {
916             /* empty password in pap-secrets and login option */
917             ret = plogin(user, passwd, msg);
918             if (ret == UPAP_AUTHNAK)
919                 warn("PAP login failure for %s", user);
920         } else {
921             /* empty password in pap-secrets and login option not used */
922             ret = UPAP_AUTHACK;
923         }
924         fclose(f);
925     }
926
927     if (ret == UPAP_AUTHNAK) {
928         if (**msg == 0)
929             *msg = "Login incorrect";
930         /*
931          * XXX can we ever get here more than once??
932          * Frustrate passwd stealer programs.
933          * Allow 10 tries, but start backing off after 3 (stolen from login).
934          * On 10'th, drop the connection.
935          */
936         if (attempts++ >= 10) {
937             warn("%d LOGIN FAILURES ON %s, %s", attempts, devnam, user);
938             lcp_close(unit, "login failed");
939         }
940         if (attempts > 3)
941             sleep((u_int) (attempts - 3) * 5);
942         if (opts != NULL)
943             free_wordlist(opts);
944
945     } else {
946         attempts = 0;                   /* Reset count */
947         if (**msg == 0)
948             *msg = "Login ok";
949         set_allowed_addrs(unit, addrs, opts);
950     }
951
952     if (addrs != NULL)
953         free_wordlist(addrs);
954     BZERO(passwd, sizeof(passwd));
955     BZERO(secret, sizeof(secret));
956
957     return ret;
958 }
959
960 /*
961  * This function is needed for PAM.
962  */
963
964 #ifdef USE_PAM
965 /* Static variables used to communicate between the conversation function
966  * and the server_login function 
967  */
968 static char *PAM_username;
969 static char *PAM_password;
970 static int PAM_error = 0;
971 static pam_handle_t *pamh = NULL;
972
973 /* PAM conversation function
974  * Here we assume (for now, at least) that echo on means login name, and
975  * echo off means password.
976  */
977
978 static int PAM_conv (int num_msg, const struct pam_message **msg,
979                     struct pam_response **resp, void *appdata_ptr)
980 {
981     int replies = 0;
982     struct pam_response *reply = NULL;
983
984 #define COPY_STRING(s) (s) ? strdup(s) : NULL
985
986     reply = malloc(sizeof(struct pam_response) * num_msg);
987     if (!reply) return PAM_CONV_ERR;
988
989     for (replies = 0; replies < num_msg; replies++) {
990         switch (msg[replies]->msg_style) {
991             case PAM_PROMPT_ECHO_ON:
992                 reply[replies].resp_retcode = PAM_SUCCESS;
993                 reply[replies].resp = COPY_STRING(PAM_username);
994                 /* PAM frees resp */
995                 break;
996             case PAM_PROMPT_ECHO_OFF:
997                 reply[replies].resp_retcode = PAM_SUCCESS;
998                 reply[replies].resp = COPY_STRING(PAM_password);
999                 /* PAM frees resp */
1000                 break;
1001             case PAM_TEXT_INFO:
1002                 /* fall through */
1003             case PAM_ERROR_MSG:
1004                 /* ignore it, but pam still wants a NULL response... */
1005                 reply[replies].resp_retcode = PAM_SUCCESS;
1006                 reply[replies].resp = NULL;
1007                 break;
1008             default:       
1009                 /* Must be an error of some sort... */
1010                 free (reply);
1011                 PAM_error = 1;
1012                 return PAM_CONV_ERR;
1013         }
1014     }
1015     *resp = reply;     
1016     return PAM_SUCCESS;
1017 }
1018
1019 static struct pam_conv PAM_conversation = {
1020     &PAM_conv,
1021     NULL
1022 };
1023 #endif  /* USE_PAM */
1024
1025 /*
1026  * plogin - Check the user name and password against the system
1027  * password database, and login the user if OK.
1028  *
1029  * returns:
1030  *      UPAP_AUTHNAK: Login failed.
1031  *      UPAP_AUTHACK: Login succeeded.
1032  * In either case, msg points to an appropriate message.
1033  */
1034
1035 static int
1036 plogin(user, passwd, msg)
1037     char *user;
1038     char *passwd;
1039     char **msg;
1040 {
1041     char *tty;
1042
1043 #ifdef USE_PAM
1044     int pam_error;
1045
1046     pam_error = pam_start ("ppp", user, &PAM_conversation, &pamh);
1047     if (pam_error != PAM_SUCCESS) {
1048         *msg = (char *) pam_strerror (pamh, pam_error);
1049         reopen_log();
1050         return UPAP_AUTHNAK;
1051     }
1052     /*
1053      * Define the fields for the credential validation
1054      */
1055      
1056     PAM_username = user;
1057     PAM_password = passwd;
1058     PAM_error = 0;
1059     pam_set_item (pamh, PAM_TTY, devnam); /* this might be useful to some modules */
1060
1061     /*
1062      * Validate the user
1063      */
1064     pam_error = pam_authenticate (pamh, PAM_SILENT);
1065     if (pam_error == PAM_SUCCESS && !PAM_error) {    
1066         pam_error = pam_acct_mgmt (pamh, PAM_SILENT);
1067         if (pam_error == PAM_SUCCESS)
1068             pam_open_session (pamh, PAM_SILENT);
1069     }
1070
1071     *msg = (char *) pam_strerror (pamh, pam_error);
1072
1073     /*
1074      * Clean up the mess
1075      */
1076     reopen_log();       /* apparently the PAM stuff does closelog() */
1077     PAM_username = NULL;
1078     PAM_password = NULL;
1079     if (pam_error != PAM_SUCCESS)
1080         return UPAP_AUTHNAK;
1081 #else /* #ifdef USE_PAM */
1082
1083 /*
1084  * Use the non-PAM methods directly
1085  */
1086
1087 #ifdef HAS_SHADOW
1088     struct spwd *spwd;
1089     struct spwd *getspnam();
1090 #endif
1091     struct passwd *pw = getpwnam(user);
1092
1093     endpwent();
1094     if (pw == NULL)
1095         return (UPAP_AUTHNAK);
1096
1097 #ifdef HAS_SHADOW
1098     spwd = getspnam(user);
1099     endspent();
1100     if (spwd) {
1101         /* check the age of the password entry */
1102         long now = time(NULL) / 86400L;
1103
1104         if ((spwd->sp_expire > 0 && now >= spwd->sp_expire)
1105             || ((spwd->sp_max >= 0 && spwd->sp_max < 10000)
1106                 && spwd->sp_lstchg >= 0
1107                 && now >= spwd->sp_lstchg + spwd->sp_max)) {
1108             warn("Password for %s has expired", user);
1109             return (UPAP_AUTHNAK);
1110         }
1111         pw->pw_passwd = spwd->sp_pwdp;
1112     }
1113 #endif
1114
1115     /*
1116      * If no passwd, don't let them login.
1117      */
1118     if (pw->pw_passwd == NULL || strlen(pw->pw_passwd) < 2
1119         || strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd) != 0)
1120         return (UPAP_AUTHNAK);
1121
1122 #endif /* #ifdef USE_PAM */
1123
1124     /*
1125      * Write a wtmp entry for this user.
1126      */
1127
1128     tty = devnam;
1129     if (strncmp(tty, "/dev/", 5) == 0)
1130         tty += 5;
1131     logwtmp(tty, user, remote_name);            /* Add wtmp login entry */
1132
1133 #if defined(_PATH_LASTLOG) && !defined(USE_PAM)
1134     if (pw != (struct passwd *)NULL) {
1135             struct lastlog ll;
1136             int fd;
1137
1138             if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
1139                 (void)lseek(fd, (off_t)(pw->pw_uid * sizeof(ll)), SEEK_SET);
1140                 memset((void *)&ll, 0, sizeof(ll));
1141                 (void)time(&ll.ll_time);
1142                 (void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
1143                 (void)write(fd, (char *)&ll, sizeof(ll));
1144                 (void)close(fd);
1145             }
1146     }
1147 #endif /* _PATH_LASTLOG and not USE_PAM */
1148
1149     info("user %s logged in", user);
1150     logged_in = 1;
1151
1152     return (UPAP_AUTHACK);
1153 }
1154
1155 /*
1156  * plogout - Logout the user.
1157  */
1158 static void
1159 plogout()
1160 {
1161 #ifdef USE_PAM
1162     int pam_error;
1163
1164     if (pamh != NULL) {
1165         pam_error = pam_close_session (pamh, PAM_SILENT);
1166         pam_end (pamh, pam_error);
1167         pamh = NULL;
1168     }
1169     /* Apparently the pam stuff does closelog(). */
1170     reopen_log();
1171 #else /* ! USE_PAM */   
1172     char *tty;
1173
1174     tty = devnam;
1175     if (strncmp(tty, "/dev/", 5) == 0)
1176         tty += 5;
1177     logwtmp(tty, "", "");               /* Wipe out utmp logout entry */
1178 #endif /* ! USE_PAM */
1179     logged_in = 0;
1180 }
1181
1182
1183 /*
1184  * null_login - Check if a username of "" and a password of "" are
1185  * acceptable, and iff so, set the list of acceptable IP addresses
1186  * and return 1.
1187  */
1188 static int
1189 null_login(unit)
1190     int unit;
1191 {
1192     char *filename;
1193     FILE *f;
1194     int i, ret;
1195     struct wordlist *addrs, *opts;
1196     char secret[MAXWORDLEN];
1197
1198     /*
1199      * Open the file of pap secrets and scan for a suitable secret.
1200      */
1201     filename = _PATH_UPAPFILE;
1202     addrs = NULL;
1203     f = fopen(filename, "r");
1204     if (f == NULL)
1205         return 0;
1206     check_access(f, filename);
1207
1208     i = scan_authfile(f, "", our_name, secret, &addrs, &opts, filename);
1209     ret = i >= 0 && secret[0] == 0;
1210     BZERO(secret, sizeof(secret));
1211
1212     if (ret)
1213         set_allowed_addrs(unit, addrs, opts);
1214     else if (opts != 0)
1215         free_wordlist(opts);
1216     if (addrs != 0)
1217         free_wordlist(addrs);
1218
1219     fclose(f);
1220     return ret;
1221 }
1222
1223
1224 /*
1225  * get_pap_passwd - get a password for authenticating ourselves with
1226  * our peer using PAP.  Returns 1 on success, 0 if no suitable password
1227  * could be found.
1228  * Assumes passwd points to MAXSECRETLEN bytes of space (if non-null).
1229  */
1230 static int
1231 get_pap_passwd(passwd)
1232     char *passwd;
1233 {
1234     char *filename;
1235     FILE *f;
1236     int ret;
1237     char secret[MAXWORDLEN];
1238
1239     /*
1240      * Check whether a plugin wants to supply this.
1241      */
1242     if (pap_passwd_hook) {
1243         ret = (*pap_passwd_hook)(user, passwd);
1244         if (ret >= 0)
1245             return ret;
1246     }
1247
1248     filename = _PATH_UPAPFILE;
1249     f = fopen(filename, "r");
1250     if (f == NULL)
1251         return 0;
1252     check_access(f, filename);
1253     ret = scan_authfile(f, user,
1254                         (remote_name[0]? remote_name: NULL),
1255                         secret, NULL, NULL, filename);
1256     fclose(f);
1257     if (ret < 0)
1258         return 0;
1259     if (passwd != NULL)
1260         strlcpy(passwd, secret, MAXSECRETLEN);
1261     BZERO(secret, sizeof(secret));
1262     return 1;
1263 }
1264
1265
1266 /*
1267  * have_pap_secret - check whether we have a PAP file with any
1268  * secrets that we could possibly use for authenticating the peer.
1269  */
1270 static int
1271 have_pap_secret(lacks_ipp)
1272     int *lacks_ipp;
1273 {
1274     FILE *f;
1275     int ret;
1276     char *filename;
1277     struct wordlist *addrs;
1278
1279     /* let the plugin decide, if there is one */
1280     if (pap_check_hook) {
1281         ret = (*pap_check_hook)();
1282         if (ret >= 0)
1283             return ret;
1284     }
1285
1286     filename = _PATH_UPAPFILE;
1287     f = fopen(filename, "r");
1288     if (f == NULL)
1289         return 0;
1290
1291     ret = scan_authfile(f, (explicit_remote? remote_name: NULL), our_name,
1292                         NULL, &addrs, NULL, filename);
1293     fclose(f);
1294     if (ret >= 0 && !some_ip_ok(addrs)) {
1295         if (lacks_ipp != 0)
1296             *lacks_ipp = 1;
1297         ret = -1;
1298     }
1299     if (addrs != 0)
1300         free_wordlist(addrs);
1301
1302     return ret >= 0;
1303 }
1304
1305
1306 /*
1307  * have_chap_secret - check whether we have a CHAP file with a
1308  * secret that we could possibly use for authenticating `client'
1309  * on `server'.  Either can be the null string, meaning we don't
1310  * know the identity yet.
1311  */
1312 static int
1313 have_chap_secret(client, server, need_ip, lacks_ipp)
1314     char *client;
1315     char *server;
1316     int need_ip;
1317     int *lacks_ipp;
1318 {
1319     FILE *f;
1320     int ret;
1321     char *filename;
1322     struct wordlist *addrs;
1323
1324     filename = _PATH_CHAPFILE;
1325     f = fopen(filename, "r");
1326     if (f == NULL)
1327         return 0;
1328
1329     if (client != NULL && client[0] == 0)
1330         client = NULL;
1331     else if (server != NULL && server[0] == 0)
1332         server = NULL;
1333
1334     ret = scan_authfile(f, client, server, NULL, &addrs, NULL, filename);
1335     fclose(f);
1336     if (ret >= 0 && need_ip && !some_ip_ok(addrs)) {
1337         if (lacks_ipp != 0)
1338             *lacks_ipp = 1;
1339         ret = -1;
1340     }
1341     if (addrs != 0)
1342         free_wordlist(addrs);
1343
1344     return ret >= 0;
1345 }
1346
1347
1348 /*
1349  * get_secret - open the CHAP secret file and return the secret
1350  * for authenticating the given client on the given server.
1351  * (We could be either client or server).
1352  */
1353 int
1354 get_secret(unit, client, server, secret, secret_len, am_server)
1355     int unit;
1356     char *client;
1357     char *server;
1358     char *secret;
1359     int *secret_len;
1360     int am_server;
1361 {
1362     FILE *f;
1363     int ret, len;
1364     char *filename;
1365     struct wordlist *addrs, *opts;
1366     char secbuf[MAXWORDLEN];
1367
1368     if (!am_server && passwd[0] != 0) {
1369         strlcpy(secbuf, passwd, sizeof(secbuf));
1370     } else {
1371         filename = _PATH_CHAPFILE;
1372         addrs = NULL;
1373         secbuf[0] = 0;
1374
1375         f = fopen(filename, "r");
1376         if (f == NULL) {
1377             error("Can't open chap secret file %s: %m", filename);
1378             return 0;
1379         }
1380         check_access(f, filename);
1381
1382         ret = scan_authfile(f, client, server, secbuf, &addrs, &opts, filename);
1383         fclose(f);
1384         if (ret < 0)
1385             return 0;
1386
1387         if (am_server)
1388             set_allowed_addrs(unit, addrs, opts);
1389         else if (opts != 0)
1390             free_wordlist(opts);
1391         if (addrs != 0)
1392             free_wordlist(addrs);
1393     }
1394
1395     len = strlen(secbuf);
1396     if (len > MAXSECRETLEN) {
1397         error("Secret for %s on %s is too long", client, server);
1398         len = MAXSECRETLEN;
1399     }
1400     BCOPY(secbuf, secret, len);
1401     BZERO(secbuf, sizeof(secbuf));
1402     *secret_len = len;
1403
1404     return 1;
1405 }
1406
1407 /*
1408  * set_allowed_addrs() - set the list of allowed addresses.
1409  * Also looks for `--' indicating options to apply for this peer
1410  * and leaves the following words in extra_options.
1411  */
1412 static void
1413 set_allowed_addrs(unit, addrs, opts)
1414     int unit;
1415     struct wordlist *addrs;
1416     struct wordlist *opts;
1417 {
1418     int n;
1419     struct wordlist *ap, **pap;
1420     struct permitted_ip *ip;
1421     char *ptr_word, *ptr_mask;
1422     struct hostent *hp;
1423     struct netent *np;
1424     u_int32_t a, mask, ah, offset;
1425     struct ipcp_options *wo = &ipcp_wantoptions[unit];
1426     u_int32_t suggested_ip = 0;
1427
1428     if (addresses[unit] != NULL)
1429         free(addresses[unit]);
1430     addresses[unit] = NULL;
1431     if (extra_options != NULL)
1432         free_wordlist(extra_options);
1433     extra_options = opts;
1434
1435     /*
1436      * Count the number of IP addresses given.
1437      */
1438     for (n = 0, pap = &addrs; (ap = *pap) != NULL; pap = &ap->next)
1439         ++n;
1440     if (n == 0)
1441         return;
1442     ip = (struct permitted_ip *) malloc((n + 1) * sizeof(struct permitted_ip));
1443     if (ip == 0)
1444         return;
1445
1446     n = 0;
1447     for (ap = addrs; ap != NULL; ap = ap->next) {
1448         /* "-" means no addresses authorized, "*" means any address allowed */
1449         ptr_word = ap->word;
1450         if (strcmp(ptr_word, "-") == 0)
1451             break;
1452         if (strcmp(ptr_word, "*") == 0) {
1453             ip[n].permit = 1;
1454             ip[n].base = ip[n].mask = 0;
1455             ++n;
1456             break;
1457         }
1458
1459         ip[n].permit = 1;
1460         if (*ptr_word == '!') {
1461             ip[n].permit = 0;
1462             ++ptr_word;
1463         }
1464
1465         mask = ~ (u_int32_t) 0;
1466         offset = 0;
1467         ptr_mask = strchr (ptr_word, '/');
1468         if (ptr_mask != NULL) {
1469             int bit_count;
1470             char *endp;
1471
1472             bit_count = (int) strtol (ptr_mask+1, &endp, 10);
1473             if (bit_count <= 0 || bit_count > 32) {
1474                 warn("invalid address length %v in auth. address list",
1475                      ptr_mask+1);
1476                 continue;
1477             }
1478             bit_count = 32 - bit_count; /* # bits in host part */
1479             if (*endp == '+') {
1480                 offset = ifunit + 1;
1481                 ++endp;
1482             }
1483             if (*endp != 0) {
1484                 warn("invalid address length syntax: %v", ptr_mask+1);
1485                 continue;
1486             }
1487             *ptr_mask = '\0';
1488             mask <<= bit_count;
1489         }
1490
1491         hp = gethostbyname(ptr_word);
1492         if (hp != NULL && hp->h_addrtype == AF_INET) {
1493             a = *(u_int32_t *)hp->h_addr;
1494         } else {
1495             np = getnetbyname (ptr_word);
1496             if (np != NULL && np->n_addrtype == AF_INET) {
1497                 a = htonl (*(u_int32_t *)np->n_net);
1498                 if (ptr_mask == NULL) {
1499                     /* calculate appropriate mask for net */
1500                     ah = ntohl(a);
1501                     if (IN_CLASSA(ah))
1502                         mask = IN_CLASSA_NET;
1503                     else if (IN_CLASSB(ah))
1504                         mask = IN_CLASSB_NET;
1505                     else if (IN_CLASSC(ah))
1506                         mask = IN_CLASSC_NET;
1507                 }
1508             } else {
1509                 a = inet_addr (ptr_word);
1510             }
1511         }
1512
1513         if (ptr_mask != NULL)
1514             *ptr_mask = '/';
1515
1516         if (a == (u_int32_t)-1L) {
1517             warn("unknown host %s in auth. address list", ap->word);
1518             continue;
1519         }
1520         if (offset != 0) {
1521             if (offset >= ~mask) {
1522                 warn("interface unit %d too large for subnet %v",
1523                      ifunit, ptr_word);
1524                 continue;
1525             }
1526             a = htonl((ntohl(a) & mask) + offset);
1527             mask = ~(u_int32_t)0;
1528         }
1529         ip[n].mask = htonl(mask);
1530         ip[n].base = a & ip[n].mask;
1531         ++n;
1532         if (~mask == 0 && suggested_ip == 0)
1533             suggested_ip = a;
1534     }
1535
1536     ip[n].permit = 0;           /* make the last entry forbid all addresses */
1537     ip[n].base = 0;             /* to terminate the list */
1538     ip[n].mask = 0;
1539
1540     addresses[unit] = ip;
1541
1542     /*
1543      * If the address given for the peer isn't authorized, or if
1544      * the user hasn't given one, AND there is an authorized address
1545      * which is a single host, then use that if we find one.
1546      */
1547     if (suggested_ip != 0
1548         && (wo->hisaddr == 0 || !auth_ip_addr(unit, wo->hisaddr)))
1549         wo->hisaddr = suggested_ip;
1550 }
1551
1552 /*
1553  * auth_ip_addr - check whether the peer is authorized to use
1554  * a given IP address.  Returns 1 if authorized, 0 otherwise.
1555  */
1556 int
1557 auth_ip_addr(unit, addr)
1558     int unit;
1559     u_int32_t addr;
1560 {
1561     int ok;
1562
1563     /* don't allow loopback or multicast address */
1564     if (bad_ip_adrs(addr))
1565         return 0;
1566
1567     if (addresses[unit] != NULL) {
1568         ok = ip_addr_check(addr, addresses[unit]);
1569         if (ok >= 0)
1570             return ok;
1571     }
1572     if (auth_required)
1573         return 0;               /* no addresses authorized */
1574     return allow_any_ip || privileged || !have_route_to(addr);
1575 }
1576
1577 static int
1578 ip_addr_check(addr, addrs)
1579     u_int32_t addr;
1580     struct permitted_ip *addrs;
1581 {
1582     for (; ; ++addrs)
1583         if ((addr & addrs->mask) == addrs->base)
1584             return addrs->permit;
1585 }
1586
1587 /*
1588  * bad_ip_adrs - return 1 if the IP address is one we don't want
1589  * to use, such as an address in the loopback net or a multicast address.
1590  * addr is in network byte order.
1591  */
1592 int
1593 bad_ip_adrs(addr)
1594     u_int32_t addr;
1595 {
1596     addr = ntohl(addr);
1597     return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
1598         || IN_MULTICAST(addr) || IN_BADCLASS(addr);
1599 }
1600
1601 /*
1602  * some_ip_ok - check a wordlist to see if it authorizes any
1603  * IP address(es).
1604  */
1605 static int
1606 some_ip_ok(addrs)
1607     struct wordlist *addrs;
1608 {
1609     for (; addrs != 0; addrs = addrs->next) {
1610         if (addrs->word[0] == '-')
1611             break;
1612         if (addrs->word[0] != '!')
1613             return 1;           /* some IP address is allowed */
1614     }
1615     return 0;
1616 }
1617
1618 /*
1619  * check_access - complain if a secret file has too-liberal permissions.
1620  */
1621 static void
1622 check_access(f, filename)
1623     FILE *f;
1624     char *filename;
1625 {
1626     struct stat sbuf;
1627
1628     if (fstat(fileno(f), &sbuf) < 0) {
1629         warn("cannot stat secret file %s: %m", filename);
1630     } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1631         warn("Warning - secret file %s has world and/or group access",
1632              filename);
1633     }
1634 }
1635
1636
1637 /*
1638  * scan_authfile - Scan an authorization file for a secret suitable
1639  * for authenticating `client' on `server'.  The return value is -1
1640  * if no secret is found, otherwise >= 0.  The return value has
1641  * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
1642  * NONWILD_SERVER set if the secret didn't have "*" for the server.
1643  * Any following words on the line up to a "--" (i.e. address authorization
1644  * info) are placed in a wordlist and returned in *addrs.  Any
1645  * following words (extra options) are placed in a wordlist and
1646  * returned in *opts.
1647  * We assume secret is NULL or points to MAXWORDLEN bytes of space.
1648  */
1649 static int
1650 scan_authfile(f, client, server, secret, addrs, opts, filename)
1651     FILE *f;
1652     char *client;
1653     char *server;
1654     char *secret;
1655     struct wordlist **addrs;
1656     struct wordlist **opts;
1657     char *filename;
1658 {
1659     int newline, xxx;
1660     int got_flag, best_flag;
1661     FILE *sf;
1662     struct wordlist *ap, *addr_list, *alist, **app;
1663     char word[MAXWORDLEN];
1664     char atfile[MAXWORDLEN];
1665     char lsecret[MAXWORDLEN];
1666
1667     if (addrs != NULL)
1668         *addrs = NULL;
1669     if (opts != NULL)
1670         *opts = NULL;
1671     addr_list = NULL;
1672     if (!getword(f, word, &newline, filename))
1673         return -1;              /* file is empty??? */
1674     newline = 1;
1675     best_flag = -1;
1676     for (;;) {
1677         /*
1678          * Skip until we find a word at the start of a line.
1679          */
1680         while (!newline && getword(f, word, &newline, filename))
1681             ;
1682         if (!newline)
1683             break;              /* got to end of file */
1684
1685         /*
1686          * Got a client - check if it's a match or a wildcard.
1687          */
1688         got_flag = 0;
1689         if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
1690             newline = 0;
1691             continue;
1692         }
1693         if (!ISWILD(word))
1694             got_flag = NONWILD_CLIENT;
1695
1696         /*
1697          * Now get a server and check if it matches.
1698          */
1699         if (!getword(f, word, &newline, filename))
1700             break;
1701         if (newline)
1702             continue;
1703         if (!ISWILD(word)) {
1704             if (server != NULL && strcmp(word, server) != 0)
1705                 continue;
1706             got_flag |= NONWILD_SERVER;
1707         }
1708
1709         /*
1710          * Got some sort of a match - see if it's better than what
1711          * we have already.
1712          */
1713         if (got_flag <= best_flag)
1714             continue;
1715
1716         /*
1717          * Get the secret.
1718          */
1719         if (!getword(f, word, &newline, filename))
1720             break;
1721         if (newline)
1722             continue;
1723
1724         /*
1725          * Special syntax: @filename means read secret from file.
1726          */
1727         if (word[0] == '@') {
1728             strlcpy(atfile, word+1, sizeof(atfile));
1729             if ((sf = fopen(atfile, "r")) == NULL) {
1730                 warn("can't open indirect secret file %s", atfile);
1731                 continue;
1732             }
1733             check_access(sf, atfile);
1734             if (!getword(sf, word, &xxx, atfile)) {
1735                 warn("no secret in indirect secret file %s", atfile);
1736                 fclose(sf);
1737                 continue;
1738             }
1739             fclose(sf);
1740         }
1741         if (secret != NULL)
1742             strlcpy(lsecret, word, sizeof(lsecret));
1743
1744         /*
1745          * Now read address authorization info and make a wordlist.
1746          */
1747         app = &alist;
1748         for (;;) {
1749             if (!getword(f, word, &newline, filename) || newline)
1750                 break;
1751             ap = (struct wordlist *) malloc(sizeof(struct wordlist));
1752             if (ap == NULL)
1753                 novm("authorized addresses");
1754             ap->word = strdup(word);
1755             if (ap->word == NULL)
1756                 novm("authorized addresses");
1757             *app = ap;
1758             app = &ap->next;
1759         }
1760         *app = NULL;
1761
1762         /*
1763          * This is the best so far; remember it.
1764          */
1765         best_flag = got_flag;
1766         if (addr_list)
1767             free_wordlist(addr_list);
1768         addr_list = alist;
1769         if (secret != NULL)
1770             strlcpy(secret, lsecret, MAXWORDLEN);
1771
1772         if (!newline)
1773             break;
1774     }
1775
1776     /* scan for a -- word indicating the start of options */
1777     for (app = &addr_list; (ap = *app) != NULL; app = &ap->next)
1778         if (strcmp(ap->word, "--") == 0)
1779             break;
1780     /* ap = start of options */
1781     if (ap != NULL) {
1782         ap = ap->next;          /* first option */
1783         free(*app);                     /* free the "--" word */
1784         *app = NULL;            /* terminate addr list */
1785     }
1786     if (opts != NULL)
1787         *opts = ap;
1788     else if (ap != NULL)
1789         free_wordlist(ap);
1790     if (addrs != NULL)
1791         *addrs = addr_list;
1792     else if (addr_list != NULL)
1793         free_wordlist(addr_list);
1794
1795     return best_flag;
1796 }
1797
1798 /*
1799  * free_wordlist - release memory allocated for a wordlist.
1800  */
1801 static void
1802 free_wordlist(wp)
1803     struct wordlist *wp;
1804 {
1805     struct wordlist *next;
1806
1807     while (wp != NULL) {
1808         next = wp->next;
1809         free(wp);
1810         wp = next;
1811     }
1812 }
1813
1814 /*
1815  * auth_script_done - called when the auth-up or auth-down script
1816  * has finished.
1817  */
1818 static void
1819 auth_script_done(arg)
1820     void *arg;
1821 {
1822     auth_script_pid = 0;
1823     switch (auth_script_state) {
1824     case s_up:
1825         if (auth_state == s_down) {
1826             auth_script_state = s_down;
1827             auth_script(_PATH_AUTHDOWN);
1828         }
1829         break;
1830     case s_down:
1831         if (auth_state == s_up) {
1832             auth_script_state = s_up;
1833             auth_script(_PATH_AUTHUP);
1834         }
1835         break;
1836     }
1837 }
1838
1839 /*
1840  * auth_script - execute a script with arguments
1841  * interface-name peer-name real-user tty speed
1842  */
1843 static void
1844 auth_script(script)
1845     char *script;
1846 {
1847     char strspeed[32];
1848     struct passwd *pw;
1849     char struid[32];
1850     char *user_name;
1851     char *argv[8];
1852
1853     if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
1854         user_name = pw->pw_name;
1855     else {
1856         slprintf(struid, sizeof(struid), "%d", getuid());
1857         user_name = struid;
1858     }
1859     slprintf(strspeed, sizeof(strspeed), "%d", baud_rate);
1860
1861     argv[0] = script;
1862     argv[1] = ifname;
1863     argv[2] = peer_authname;
1864     argv[3] = user_name;
1865     argv[4] = devnam;
1866     argv[5] = strspeed;
1867     argv[6] = NULL;
1868
1869     auth_script_pid = run_program(script, argv, 0, auth_script_done, NULL);
1870 }