]> git.ozlabs.org Git - ppp.git/blob - pppd/auth.c
Multilink cleanups and fixes.
[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.64 2000/04/13 12:05:57 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 #ifdef HAVE_MULTILINK
514     if (multilink) {
515         if (mp_join_bundle()) {
516             if (updetach && !nodetach)
517                 detach();
518             return;
519         }
520     }
521 #endif /* HAVE_MULTILINK */
522
523 #if 0
524     if (!demand)
525         set_filters(&pass_filter, &active_filter);
526 #endif
527     for (i = 0; (protp = protocols[i]) != NULL; ++i)
528         if (protp->protocol < 0xC000 && protp->enabled_flag
529             && protp->open != NULL) {
530             (*protp->open)(0);
531             if (protp->protocol != PPP_CCP)
532                 ++num_np_open;
533         }
534
535     if (num_np_open == 0)
536         /* nothing to do */
537         lcp_close(0, "No network protocols running");
538 }
539
540 /*
541  * The peer has failed to authenticate himself using `protocol'.
542  */
543 void
544 auth_peer_fail(unit, protocol)
545     int unit, protocol;
546 {
547     /*
548      * Authentication failure: take the link down
549      */
550     lcp_close(unit, "Authentication failed");
551     status = EXIT_PEER_AUTH_FAILED;
552 }
553
554 /*
555  * The peer has been successfully authenticated using `protocol'.
556  */
557 void
558 auth_peer_success(unit, protocol, name, namelen)
559     int unit, protocol;
560     char *name;
561     int namelen;
562 {
563     int bit;
564
565     switch (protocol) {
566     case PPP_CHAP:
567         bit = CHAP_PEER;
568         break;
569     case PPP_PAP:
570         bit = PAP_PEER;
571         break;
572     default:
573         warn("auth_peer_success: unknown protocol %x", protocol);
574         return;
575     }
576
577     /*
578      * Save the authenticated name of the peer for later.
579      */
580     if (namelen > sizeof(peer_authname) - 1)
581         namelen = sizeof(peer_authname) - 1;
582     BCOPY(name, peer_authname, namelen);
583     peer_authname[namelen] = 0;
584     script_setenv("PEERNAME", peer_authname, 0);
585
586     /*
587      * If there is no more authentication still to be done,
588      * proceed to the network (or callback) phase.
589      */
590     if ((auth_pending[unit] &= ~bit) == 0)
591         network_phase(unit);
592 }
593
594 /*
595  * We have failed to authenticate ourselves to the peer using `protocol'.
596  */
597 void
598 auth_withpeer_fail(unit, protocol)
599     int unit, protocol;
600 {
601     if (passwd_from_file)
602         BZERO(passwd, MAXSECRETLEN);
603     /*
604      * We've failed to authenticate ourselves to our peer.
605      * Some servers keep sending CHAP challenges, but there
606      * is no point in persisting without any way to get updated
607      * authentication secrets.
608      */
609     lcp_close(unit, "Failed to authenticate ourselves to peer");
610     status = EXIT_AUTH_TOPEER_FAILED;
611 }
612
613 /*
614  * We have successfully authenticated ourselves with the peer using `protocol'.
615  */
616 void
617 auth_withpeer_success(unit, protocol)
618     int unit, protocol;
619 {
620     int bit;
621
622     switch (protocol) {
623     case PPP_CHAP:
624         bit = CHAP_WITHPEER;
625         break;
626     case PPP_PAP:
627         if (passwd_from_file)
628             BZERO(passwd, MAXSECRETLEN);
629         bit = PAP_WITHPEER;
630         break;
631     default:
632         warn("auth_withpeer_success: unknown protocol %x", protocol);
633         bit = 0;
634     }
635
636     /*
637      * If there is no more authentication still being done,
638      * proceed to the network (or callback) phase.
639      */
640     if ((auth_pending[unit] &= ~bit) == 0)
641         network_phase(unit);
642 }
643
644
645 /*
646  * np_up - a network protocol has come up.
647  */
648 void
649 np_up(unit, proto)
650     int unit, proto;
651 {
652     int tlim;
653
654     if (num_np_up == 0) {
655         /*
656          * At this point we consider that the link has come up successfully.
657          */
658         status = EXIT_OK;
659         unsuccess = 0;
660         new_phase(PHASE_RUNNING);
661
662         if (idle_time_hook != 0)
663             tlim = (*idle_time_hook)(NULL);
664         else
665             tlim = idle_time_limit;
666         if (tlim > 0)
667             TIMEOUT(check_idle, NULL, tlim);
668
669         /*
670          * Set a timeout to close the connection once the maximum
671          * connect time has expired.
672          */
673         if (maxconnect > 0)
674             TIMEOUT(connect_time_expired, 0, maxconnect);
675
676         /*
677          * Detach now, if the updetach option was given.
678          */
679         if (updetach && !nodetach)
680             detach();
681     }
682     ++num_np_up;
683 }
684
685 /*
686  * np_down - a network protocol has gone down.
687  */
688 void
689 np_down(unit, proto)
690     int unit, proto;
691 {
692     if (--num_np_up == 0) {
693         UNTIMEOUT(check_idle, NULL);
694         new_phase(PHASE_NETWORK);
695     }
696 }
697
698 /*
699  * np_finished - a network protocol has finished using the link.
700  */
701 void
702 np_finished(unit, proto)
703     int unit, proto;
704 {
705     if (--num_np_open <= 0) {
706         /* no further use for the link: shut up shop. */
707         lcp_close(0, "No network protocols running");
708     }
709 }
710
711 /*
712  * check_idle - check whether the link has been idle for long
713  * enough that we can shut it down.
714  */
715 static void
716 check_idle(arg)
717     void *arg;
718 {
719     struct ppp_idle idle;
720     time_t itime;
721     int tlim;
722
723     if (!get_idle_time(0, &idle))
724         return;
725     if (idle_time_hook != 0) {
726         tlim = idle_time_hook(&idle);
727     } else {
728         itime = MIN(idle.xmit_idle, idle.recv_idle);
729         tlim = idle_time_limit - itime;
730     }
731     if (tlim <= 0) {
732         /* link is idle: shut it down. */
733         notice("Terminating connection due to lack of activity.");
734         lcp_close(0, "Link inactive");
735         need_holdoff = 0;
736         status = EXIT_IDLE_TIMEOUT;
737     } else {
738         TIMEOUT(check_idle, NULL, tlim);
739     }
740 }
741
742 /*
743  * connect_time_expired - log a message and close the connection.
744  */
745 static void
746 connect_time_expired(arg)
747     void *arg;
748 {
749     info("Connect time expired");
750     lcp_close(0, "Connect time expired");       /* Close connection */
751     status = EXIT_CONNECT_TIME;
752 }
753
754 /*
755  * auth_check_options - called to check authentication options.
756  */
757 void
758 auth_check_options()
759 {
760     lcp_options *wo = &lcp_wantoptions[0];
761     int can_auth;
762     int lacks_ip;
763
764     /* Default our_name to hostname, and user to our_name */
765     if (our_name[0] == 0 || usehostname)
766         strlcpy(our_name, hostname, sizeof(our_name));
767     if (user[0] == 0)
768         strlcpy(user, our_name, sizeof(user));
769
770     /*
771      * If we have a default route, require the peer to authenticate
772      * unless the noauth option was given or the real user is root.
773      */
774     if (!auth_required && !allow_any_ip && have_route_to(0) && !privileged) {
775         auth_required = 1;
776         default_auth = 1;
777     }
778
779     /* If authentication is required, ask peer for CHAP or PAP. */
780     if (auth_required) {
781         if (!wo->neg_chap && !wo->neg_upap) {
782             wo->neg_chap = 1;
783             wo->neg_upap = 1;
784         }
785     } else {
786         wo->neg_chap = 0;
787         wo->neg_upap = 0;
788     }
789
790     /*
791      * Check whether we have appropriate secrets to use
792      * to authenticate the peer.
793      */
794     lacks_ip = 0;
795     can_auth = wo->neg_upap && (uselogin || have_pap_secret(&lacks_ip));
796     if (!can_auth && wo->neg_chap) {
797         can_auth = have_chap_secret((explicit_remote? remote_name: NULL),
798                                     our_name, 1, &lacks_ip);
799     }
800
801     if (auth_required && !can_auth && noauth_addrs == NULL) {
802         if (default_auth) {
803             option_error(
804 "By default the remote system is required to authenticate itself");
805             option_error(
806 "(because this system has a default route to the internet)");
807         } else if (explicit_remote)
808             option_error(
809 "The remote system (%s) is required to authenticate itself",
810                          remote_name);
811         else
812             option_error(
813 "The remote system is required to authenticate itself");
814         option_error(
815 "but I couldn't find any suitable secret (password) for it to use to do so.");
816         if (lacks_ip)
817             option_error(
818 "(None of the available passwords would let it use an IP address.)");
819
820         exit(1);
821     }
822 }
823
824 /*
825  * auth_reset - called when LCP is starting negotiations to recheck
826  * authentication options, i.e. whether we have appropriate secrets
827  * to use for authenticating ourselves and/or the peer.
828  */
829 void
830 auth_reset(unit)
831     int unit;
832 {
833     lcp_options *go = &lcp_gotoptions[unit];
834     lcp_options *ao = &lcp_allowoptions[0];
835
836     ao->neg_upap = !refuse_pap && (passwd[0] != 0 || get_pap_passwd(NULL));
837     ao->neg_chap = !refuse_chap
838         && (passwd[0] != 0
839             || have_chap_secret(user, (explicit_remote? remote_name: NULL),
840                                 0, NULL));
841
842     if (go->neg_upap && !uselogin && !have_pap_secret(NULL))
843         go->neg_upap = 0;
844     if (go->neg_chap) {
845         if (!have_chap_secret((explicit_remote? remote_name: NULL),
846                               our_name, 1, NULL))
847             go->neg_chap = 0;
848     }
849 }
850
851
852 /*
853  * check_passwd - Check the user name and passwd against the PAP secrets
854  * file.  If requested, also check against the system password database,
855  * and login the user if OK.
856  *
857  * returns:
858  *      UPAP_AUTHNAK: Authentication failed.
859  *      UPAP_AUTHACK: Authentication succeeded.
860  * In either case, msg points to an appropriate message.
861  */
862 int
863 check_passwd(unit, auser, userlen, apasswd, passwdlen, msg)
864     int unit;
865     char *auser;
866     int userlen;
867     char *apasswd;
868     int passwdlen;
869     char **msg;
870 {
871     int ret;
872     char *filename;
873     FILE *f;
874     struct wordlist *addrs = NULL, *opts = NULL;
875     char passwd[256], user[256];
876     char secret[MAXWORDLEN];
877     static int attempts = 0;
878
879     /*
880      * Make copies of apasswd and auser, then null-terminate them.
881      * If there are unprintable characters in the password, make
882      * them visible.
883      */
884     slprintf(passwd, sizeof(passwd), "%.*v", passwdlen, apasswd);
885     slprintf(user, sizeof(user), "%.*v", userlen, auser);
886     *msg = "";
887
888     /*
889      * Check if a plugin wants to handle this.
890      */
891     if (pap_auth_hook) {
892         ret = (*pap_auth_hook)(user, passwd, msg, &addrs, &opts);
893         if (ret >= 0) {
894             if (ret)
895                 set_allowed_addrs(unit, addrs, opts);
896             BZERO(passwd, sizeof(passwd));
897             if (addrs != 0)
898                 free_wordlist(addrs);
899             return ret? UPAP_AUTHACK: UPAP_AUTHNAK;
900         }
901     }
902
903     /*
904      * Open the file of pap secrets and scan for a suitable secret
905      * for authenticating this user.
906      */
907     filename = _PATH_UPAPFILE;
908     addrs = opts = NULL;
909     ret = UPAP_AUTHNAK;
910     f = fopen(filename, "r");
911     if (f == NULL) {
912         error("Can't open PAP password file %s: %m", filename);
913
914     } else {
915         check_access(f, filename);
916         if (scan_authfile(f, user, our_name, secret, &addrs, &opts, filename) < 0) {
917             warn("no PAP secret found for %s", user);
918         } else if (secret[0] != 0) {
919             /* password given in pap-secrets - must match */
920             if ((!cryptpap && strcmp(passwd, secret) == 0)
921                 || strcmp(crypt(passwd, secret), secret) == 0)
922                 ret = UPAP_AUTHACK;
923             else
924                 warn("PAP authentication failure for %s", user);
925         } else if (uselogin) {
926             /* empty password in pap-secrets and login option */
927             ret = plogin(user, passwd, msg);
928             if (ret == UPAP_AUTHNAK)
929                 warn("PAP login failure for %s", user);
930         } else {
931             /* empty password in pap-secrets and login option not used */
932             ret = UPAP_AUTHACK;
933         }
934         fclose(f);
935     }
936
937     if (ret == UPAP_AUTHNAK) {
938         if (**msg == 0)
939             *msg = "Login incorrect";
940         /*
941          * XXX can we ever get here more than once??
942          * Frustrate passwd stealer programs.
943          * Allow 10 tries, but start backing off after 3 (stolen from login).
944          * On 10'th, drop the connection.
945          */
946         if (attempts++ >= 10) {
947             warn("%d LOGIN FAILURES ON %s, %s", attempts, devnam, user);
948             lcp_close(unit, "login failed");
949         }
950         if (attempts > 3)
951             sleep((u_int) (attempts - 3) * 5);
952         if (opts != NULL)
953             free_wordlist(opts);
954
955     } else {
956         attempts = 0;                   /* Reset count */
957         if (**msg == 0)
958             *msg = "Login ok";
959         set_allowed_addrs(unit, addrs, opts);
960     }
961
962     if (addrs != NULL)
963         free_wordlist(addrs);
964     BZERO(passwd, sizeof(passwd));
965     BZERO(secret, sizeof(secret));
966
967     return ret;
968 }
969
970 /*
971  * This function is needed for PAM.
972  */
973
974 #ifdef USE_PAM
975 /* Static variables used to communicate between the conversation function
976  * and the server_login function 
977  */
978 static char *PAM_username;
979 static char *PAM_password;
980 static int PAM_error = 0;
981 static pam_handle_t *pamh = NULL;
982
983 /* PAM conversation function
984  * Here we assume (for now, at least) that echo on means login name, and
985  * echo off means password.
986  */
987
988 static int PAM_conv (int num_msg, const struct pam_message **msg,
989                     struct pam_response **resp, void *appdata_ptr)
990 {
991     int replies = 0;
992     struct pam_response *reply = NULL;
993
994 #define COPY_STRING(s) (s) ? strdup(s) : NULL
995
996     reply = malloc(sizeof(struct pam_response) * num_msg);
997     if (!reply) return PAM_CONV_ERR;
998
999     for (replies = 0; replies < num_msg; replies++) {
1000         switch (msg[replies]->msg_style) {
1001             case PAM_PROMPT_ECHO_ON:
1002                 reply[replies].resp_retcode = PAM_SUCCESS;
1003                 reply[replies].resp = COPY_STRING(PAM_username);
1004                 /* PAM frees resp */
1005                 break;
1006             case PAM_PROMPT_ECHO_OFF:
1007                 reply[replies].resp_retcode = PAM_SUCCESS;
1008                 reply[replies].resp = COPY_STRING(PAM_password);
1009                 /* PAM frees resp */
1010                 break;
1011             case PAM_TEXT_INFO:
1012                 /* fall through */
1013             case PAM_ERROR_MSG:
1014                 /* ignore it, but pam still wants a NULL response... */
1015                 reply[replies].resp_retcode = PAM_SUCCESS;
1016                 reply[replies].resp = NULL;
1017                 break;
1018             default:       
1019                 /* Must be an error of some sort... */
1020                 free (reply);
1021                 PAM_error = 1;
1022                 return PAM_CONV_ERR;
1023         }
1024     }
1025     *resp = reply;     
1026     return PAM_SUCCESS;
1027 }
1028
1029 static struct pam_conv PAM_conversation = {
1030     &PAM_conv,
1031     NULL
1032 };
1033 #endif  /* USE_PAM */
1034
1035 /*
1036  * plogin - Check the user name and password against the system
1037  * password database, and login the user if OK.
1038  *
1039  * returns:
1040  *      UPAP_AUTHNAK: Login failed.
1041  *      UPAP_AUTHACK: Login succeeded.
1042  * In either case, msg points to an appropriate message.
1043  */
1044
1045 static int
1046 plogin(user, passwd, msg)
1047     char *user;
1048     char *passwd;
1049     char **msg;
1050 {
1051     char *tty;
1052
1053 #ifdef USE_PAM
1054     int pam_error;
1055
1056     pam_error = pam_start ("ppp", user, &PAM_conversation, &pamh);
1057     if (pam_error != PAM_SUCCESS) {
1058         *msg = (char *) pam_strerror (pamh, pam_error);
1059         reopen_log();
1060         return UPAP_AUTHNAK;
1061     }
1062     /*
1063      * Define the fields for the credential validation
1064      */
1065      
1066     PAM_username = user;
1067     PAM_password = passwd;
1068     PAM_error = 0;
1069     pam_set_item (pamh, PAM_TTY, devnam); /* this might be useful to some modules */
1070
1071     /*
1072      * Validate the user
1073      */
1074     pam_error = pam_authenticate (pamh, PAM_SILENT);
1075     if (pam_error == PAM_SUCCESS && !PAM_error) {    
1076         pam_error = pam_acct_mgmt (pamh, PAM_SILENT);
1077         if (pam_error == PAM_SUCCESS)
1078             pam_open_session (pamh, PAM_SILENT);
1079     }
1080
1081     *msg = (char *) pam_strerror (pamh, pam_error);
1082
1083     /*
1084      * Clean up the mess
1085      */
1086     reopen_log();       /* apparently the PAM stuff does closelog() */
1087     PAM_username = NULL;
1088     PAM_password = NULL;
1089     if (pam_error != PAM_SUCCESS)
1090         return UPAP_AUTHNAK;
1091 #else /* #ifdef USE_PAM */
1092
1093 /*
1094  * Use the non-PAM methods directly
1095  */
1096
1097 #ifdef HAS_SHADOW
1098     struct spwd *spwd;
1099     struct spwd *getspnam();
1100 #endif
1101     struct passwd *pw = getpwnam(user);
1102
1103     endpwent();
1104     if (pw == NULL)
1105         return (UPAP_AUTHNAK);
1106
1107 #ifdef HAS_SHADOW
1108     spwd = getspnam(user);
1109     endspent();
1110     if (spwd) {
1111         /* check the age of the password entry */
1112         long now = time(NULL) / 86400L;
1113
1114         if ((spwd->sp_expire > 0 && now >= spwd->sp_expire)
1115             || ((spwd->sp_max >= 0 && spwd->sp_max < 10000)
1116                 && spwd->sp_lstchg >= 0
1117                 && now >= spwd->sp_lstchg + spwd->sp_max)) {
1118             warn("Password for %s has expired", user);
1119             return (UPAP_AUTHNAK);
1120         }
1121         pw->pw_passwd = spwd->sp_pwdp;
1122     }
1123 #endif
1124
1125     /*
1126      * If no passwd, don't let them login.
1127      */
1128     if (pw->pw_passwd == NULL || strlen(pw->pw_passwd) < 2
1129         || strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd) != 0)
1130         return (UPAP_AUTHNAK);
1131
1132 #endif /* #ifdef USE_PAM */
1133
1134     /*
1135      * Write a wtmp entry for this user.
1136      */
1137
1138     tty = devnam;
1139     if (strncmp(tty, "/dev/", 5) == 0)
1140         tty += 5;
1141     logwtmp(tty, user, remote_name);            /* Add wtmp login entry */
1142
1143 #if defined(_PATH_LASTLOG) && !defined(USE_PAM)
1144     if (pw != (struct passwd *)NULL) {
1145             struct lastlog ll;
1146             int fd;
1147
1148             if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
1149                 (void)lseek(fd, (off_t)(pw->pw_uid * sizeof(ll)), SEEK_SET);
1150                 memset((void *)&ll, 0, sizeof(ll));
1151                 (void)time(&ll.ll_time);
1152                 (void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
1153                 (void)write(fd, (char *)&ll, sizeof(ll));
1154                 (void)close(fd);
1155             }
1156     }
1157 #endif /* _PATH_LASTLOG and not USE_PAM */
1158
1159     info("user %s logged in", user);
1160     logged_in = 1;
1161
1162     return (UPAP_AUTHACK);
1163 }
1164
1165 /*
1166  * plogout - Logout the user.
1167  */
1168 static void
1169 plogout()
1170 {
1171 #ifdef USE_PAM
1172     int pam_error;
1173
1174     if (pamh != NULL) {
1175         pam_error = pam_close_session (pamh, PAM_SILENT);
1176         pam_end (pamh, pam_error);
1177         pamh = NULL;
1178     }
1179     /* Apparently the pam stuff does closelog(). */
1180     reopen_log();
1181 #else /* ! USE_PAM */   
1182     char *tty;
1183
1184     tty = devnam;
1185     if (strncmp(tty, "/dev/", 5) == 0)
1186         tty += 5;
1187     logwtmp(tty, "", "");               /* Wipe out utmp logout entry */
1188 #endif /* ! USE_PAM */
1189     logged_in = 0;
1190 }
1191
1192
1193 /*
1194  * null_login - Check if a username of "" and a password of "" are
1195  * acceptable, and iff so, set the list of acceptable IP addresses
1196  * and return 1.
1197  */
1198 static int
1199 null_login(unit)
1200     int unit;
1201 {
1202     char *filename;
1203     FILE *f;
1204     int i, ret;
1205     struct wordlist *addrs, *opts;
1206     char secret[MAXWORDLEN];
1207
1208     /*
1209      * Open the file of pap secrets and scan for a suitable secret.
1210      */
1211     filename = _PATH_UPAPFILE;
1212     addrs = NULL;
1213     f = fopen(filename, "r");
1214     if (f == NULL)
1215         return 0;
1216     check_access(f, filename);
1217
1218     i = scan_authfile(f, "", our_name, secret, &addrs, &opts, filename);
1219     ret = i >= 0 && secret[0] == 0;
1220     BZERO(secret, sizeof(secret));
1221
1222     if (ret)
1223         set_allowed_addrs(unit, addrs, opts);
1224     else if (opts != 0)
1225         free_wordlist(opts);
1226     if (addrs != 0)
1227         free_wordlist(addrs);
1228
1229     fclose(f);
1230     return ret;
1231 }
1232
1233
1234 /*
1235  * get_pap_passwd - get a password for authenticating ourselves with
1236  * our peer using PAP.  Returns 1 on success, 0 if no suitable password
1237  * could be found.
1238  * Assumes passwd points to MAXSECRETLEN bytes of space (if non-null).
1239  */
1240 static int
1241 get_pap_passwd(passwd)
1242     char *passwd;
1243 {
1244     char *filename;
1245     FILE *f;
1246     int ret;
1247     char secret[MAXWORDLEN];
1248
1249     /*
1250      * Check whether a plugin wants to supply this.
1251      */
1252     if (pap_passwd_hook) {
1253         ret = (*pap_passwd_hook)(user, passwd);
1254         if (ret >= 0)
1255             return ret;
1256     }
1257
1258     filename = _PATH_UPAPFILE;
1259     f = fopen(filename, "r");
1260     if (f == NULL)
1261         return 0;
1262     check_access(f, filename);
1263     ret = scan_authfile(f, user,
1264                         (remote_name[0]? remote_name: NULL),
1265                         secret, NULL, NULL, filename);
1266     fclose(f);
1267     if (ret < 0)
1268         return 0;
1269     if (passwd != NULL)
1270         strlcpy(passwd, secret, MAXSECRETLEN);
1271     BZERO(secret, sizeof(secret));
1272     return 1;
1273 }
1274
1275
1276 /*
1277  * have_pap_secret - check whether we have a PAP file with any
1278  * secrets that we could possibly use for authenticating the peer.
1279  */
1280 static int
1281 have_pap_secret(lacks_ipp)
1282     int *lacks_ipp;
1283 {
1284     FILE *f;
1285     int ret;
1286     char *filename;
1287     struct wordlist *addrs;
1288
1289     /* let the plugin decide, if there is one */
1290     if (pap_check_hook) {
1291         ret = (*pap_check_hook)();
1292         if (ret >= 0)
1293             return ret;
1294     }
1295
1296     filename = _PATH_UPAPFILE;
1297     f = fopen(filename, "r");
1298     if (f == NULL)
1299         return 0;
1300
1301     ret = scan_authfile(f, (explicit_remote? remote_name: NULL), our_name,
1302                         NULL, &addrs, NULL, filename);
1303     fclose(f);
1304     if (ret >= 0 && !some_ip_ok(addrs)) {
1305         if (lacks_ipp != 0)
1306             *lacks_ipp = 1;
1307         ret = -1;
1308     }
1309     if (addrs != 0)
1310         free_wordlist(addrs);
1311
1312     return ret >= 0;
1313 }
1314
1315
1316 /*
1317  * have_chap_secret - check whether we have a CHAP file with a
1318  * secret that we could possibly use for authenticating `client'
1319  * on `server'.  Either can be the null string, meaning we don't
1320  * know the identity yet.
1321  */
1322 static int
1323 have_chap_secret(client, server, need_ip, lacks_ipp)
1324     char *client;
1325     char *server;
1326     int need_ip;
1327     int *lacks_ipp;
1328 {
1329     FILE *f;
1330     int ret;
1331     char *filename;
1332     struct wordlist *addrs;
1333
1334     filename = _PATH_CHAPFILE;
1335     f = fopen(filename, "r");
1336     if (f == NULL)
1337         return 0;
1338
1339     if (client != NULL && client[0] == 0)
1340         client = NULL;
1341     else if (server != NULL && server[0] == 0)
1342         server = NULL;
1343
1344     ret = scan_authfile(f, client, server, NULL, &addrs, NULL, filename);
1345     fclose(f);
1346     if (ret >= 0 && need_ip && !some_ip_ok(addrs)) {
1347         if (lacks_ipp != 0)
1348             *lacks_ipp = 1;
1349         ret = -1;
1350     }
1351     if (addrs != 0)
1352         free_wordlist(addrs);
1353
1354     return ret >= 0;
1355 }
1356
1357
1358 /*
1359  * get_secret - open the CHAP secret file and return the secret
1360  * for authenticating the given client on the given server.
1361  * (We could be either client or server).
1362  */
1363 int
1364 get_secret(unit, client, server, secret, secret_len, am_server)
1365     int unit;
1366     char *client;
1367     char *server;
1368     char *secret;
1369     int *secret_len;
1370     int am_server;
1371 {
1372     FILE *f;
1373     int ret, len;
1374     char *filename;
1375     struct wordlist *addrs, *opts;
1376     char secbuf[MAXWORDLEN];
1377
1378     if (!am_server && passwd[0] != 0) {
1379         strlcpy(secbuf, passwd, sizeof(secbuf));
1380     } else {
1381         filename = _PATH_CHAPFILE;
1382         addrs = NULL;
1383         secbuf[0] = 0;
1384
1385         f = fopen(filename, "r");
1386         if (f == NULL) {
1387             error("Can't open chap secret file %s: %m", filename);
1388             return 0;
1389         }
1390         check_access(f, filename);
1391
1392         ret = scan_authfile(f, client, server, secbuf, &addrs, &opts, filename);
1393         fclose(f);
1394         if (ret < 0)
1395             return 0;
1396
1397         if (am_server)
1398             set_allowed_addrs(unit, addrs, opts);
1399         else if (opts != 0)
1400             free_wordlist(opts);
1401         if (addrs != 0)
1402             free_wordlist(addrs);
1403     }
1404
1405     len = strlen(secbuf);
1406     if (len > MAXSECRETLEN) {
1407         error("Secret for %s on %s is too long", client, server);
1408         len = MAXSECRETLEN;
1409     }
1410     BCOPY(secbuf, secret, len);
1411     BZERO(secbuf, sizeof(secbuf));
1412     *secret_len = len;
1413
1414     return 1;
1415 }
1416
1417 /*
1418  * set_allowed_addrs() - set the list of allowed addresses.
1419  * Also looks for `--' indicating options to apply for this peer
1420  * and leaves the following words in extra_options.
1421  */
1422 static void
1423 set_allowed_addrs(unit, addrs, opts)
1424     int unit;
1425     struct wordlist *addrs;
1426     struct wordlist *opts;
1427 {
1428     int n;
1429     struct wordlist *ap, **pap;
1430     struct permitted_ip *ip;
1431     char *ptr_word, *ptr_mask;
1432     struct hostent *hp;
1433     struct netent *np;
1434     u_int32_t a, mask, ah, offset;
1435     struct ipcp_options *wo = &ipcp_wantoptions[unit];
1436     u_int32_t suggested_ip = 0;
1437
1438     if (addresses[unit] != NULL)
1439         free(addresses[unit]);
1440     addresses[unit] = NULL;
1441     if (extra_options != NULL)
1442         free_wordlist(extra_options);
1443     extra_options = opts;
1444
1445     /*
1446      * Count the number of IP addresses given.
1447      */
1448     for (n = 0, pap = &addrs; (ap = *pap) != NULL; pap = &ap->next)
1449         ++n;
1450     if (n == 0)
1451         return;
1452     ip = (struct permitted_ip *) malloc((n + 1) * sizeof(struct permitted_ip));
1453     if (ip == 0)
1454         return;
1455
1456     n = 0;
1457     for (ap = addrs; ap != NULL; ap = ap->next) {
1458         /* "-" means no addresses authorized, "*" means any address allowed */
1459         ptr_word = ap->word;
1460         if (strcmp(ptr_word, "-") == 0)
1461             break;
1462         if (strcmp(ptr_word, "*") == 0) {
1463             ip[n].permit = 1;
1464             ip[n].base = ip[n].mask = 0;
1465             ++n;
1466             break;
1467         }
1468
1469         ip[n].permit = 1;
1470         if (*ptr_word == '!') {
1471             ip[n].permit = 0;
1472             ++ptr_word;
1473         }
1474
1475         mask = ~ (u_int32_t) 0;
1476         offset = 0;
1477         ptr_mask = strchr (ptr_word, '/');
1478         if (ptr_mask != NULL) {
1479             int bit_count;
1480             char *endp;
1481
1482             bit_count = (int) strtol (ptr_mask+1, &endp, 10);
1483             if (bit_count <= 0 || bit_count > 32) {
1484                 warn("invalid address length %v in auth. address list",
1485                      ptr_mask+1);
1486                 continue;
1487             }
1488             bit_count = 32 - bit_count; /* # bits in host part */
1489             if (*endp == '+') {
1490                 offset = ifunit + 1;
1491                 ++endp;
1492             }
1493             if (*endp != 0) {
1494                 warn("invalid address length syntax: %v", ptr_mask+1);
1495                 continue;
1496             }
1497             *ptr_mask = '\0';
1498             mask <<= bit_count;
1499         }
1500
1501         hp = gethostbyname(ptr_word);
1502         if (hp != NULL && hp->h_addrtype == AF_INET) {
1503             a = *(u_int32_t *)hp->h_addr;
1504         } else {
1505             np = getnetbyname (ptr_word);
1506             if (np != NULL && np->n_addrtype == AF_INET) {
1507                 a = htonl (*(u_int32_t *)np->n_net);
1508                 if (ptr_mask == NULL) {
1509                     /* calculate appropriate mask for net */
1510                     ah = ntohl(a);
1511                     if (IN_CLASSA(ah))
1512                         mask = IN_CLASSA_NET;
1513                     else if (IN_CLASSB(ah))
1514                         mask = IN_CLASSB_NET;
1515                     else if (IN_CLASSC(ah))
1516                         mask = IN_CLASSC_NET;
1517                 }
1518             } else {
1519                 a = inet_addr (ptr_word);
1520             }
1521         }
1522
1523         if (ptr_mask != NULL)
1524             *ptr_mask = '/';
1525
1526         if (a == (u_int32_t)-1L) {
1527             warn("unknown host %s in auth. address list", ap->word);
1528             continue;
1529         }
1530         if (offset != 0) {
1531             if (offset >= ~mask) {
1532                 warn("interface unit %d too large for subnet %v",
1533                      ifunit, ptr_word);
1534                 continue;
1535             }
1536             a = htonl((ntohl(a) & mask) + offset);
1537             mask = ~(u_int32_t)0;
1538         }
1539         ip[n].mask = htonl(mask);
1540         ip[n].base = a & ip[n].mask;
1541         ++n;
1542         if (~mask == 0 && suggested_ip == 0)
1543             suggested_ip = a;
1544     }
1545
1546     ip[n].permit = 0;           /* make the last entry forbid all addresses */
1547     ip[n].base = 0;             /* to terminate the list */
1548     ip[n].mask = 0;
1549
1550     addresses[unit] = ip;
1551
1552     /*
1553      * If the address given for the peer isn't authorized, or if
1554      * the user hasn't given one, AND there is an authorized address
1555      * which is a single host, then use that if we find one.
1556      */
1557     if (suggested_ip != 0
1558         && (wo->hisaddr == 0 || !auth_ip_addr(unit, wo->hisaddr)))
1559         wo->hisaddr = suggested_ip;
1560 }
1561
1562 /*
1563  * auth_ip_addr - check whether the peer is authorized to use
1564  * a given IP address.  Returns 1 if authorized, 0 otherwise.
1565  */
1566 int
1567 auth_ip_addr(unit, addr)
1568     int unit;
1569     u_int32_t addr;
1570 {
1571     int ok;
1572
1573     /* don't allow loopback or multicast address */
1574     if (bad_ip_adrs(addr))
1575         return 0;
1576
1577     if (addresses[unit] != NULL) {
1578         ok = ip_addr_check(addr, addresses[unit]);
1579         if (ok >= 0)
1580             return ok;
1581     }
1582     if (auth_required)
1583         return 0;               /* no addresses authorized */
1584     return allow_any_ip || privileged || !have_route_to(addr);
1585 }
1586
1587 static int
1588 ip_addr_check(addr, addrs)
1589     u_int32_t addr;
1590     struct permitted_ip *addrs;
1591 {
1592     for (; ; ++addrs)
1593         if ((addr & addrs->mask) == addrs->base)
1594             return addrs->permit;
1595 }
1596
1597 /*
1598  * bad_ip_adrs - return 1 if the IP address is one we don't want
1599  * to use, such as an address in the loopback net or a multicast address.
1600  * addr is in network byte order.
1601  */
1602 int
1603 bad_ip_adrs(addr)
1604     u_int32_t addr;
1605 {
1606     addr = ntohl(addr);
1607     return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
1608         || IN_MULTICAST(addr) || IN_BADCLASS(addr);
1609 }
1610
1611 /*
1612  * some_ip_ok - check a wordlist to see if it authorizes any
1613  * IP address(es).
1614  */
1615 static int
1616 some_ip_ok(addrs)
1617     struct wordlist *addrs;
1618 {
1619     for (; addrs != 0; addrs = addrs->next) {
1620         if (addrs->word[0] == '-')
1621             break;
1622         if (addrs->word[0] != '!')
1623             return 1;           /* some IP address is allowed */
1624     }
1625     return 0;
1626 }
1627
1628 /*
1629  * check_access - complain if a secret file has too-liberal permissions.
1630  */
1631 static void
1632 check_access(f, filename)
1633     FILE *f;
1634     char *filename;
1635 {
1636     struct stat sbuf;
1637
1638     if (fstat(fileno(f), &sbuf) < 0) {
1639         warn("cannot stat secret file %s: %m", filename);
1640     } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1641         warn("Warning - secret file %s has world and/or group access",
1642              filename);
1643     }
1644 }
1645
1646
1647 /*
1648  * scan_authfile - Scan an authorization file for a secret suitable
1649  * for authenticating `client' on `server'.  The return value is -1
1650  * if no secret is found, otherwise >= 0.  The return value has
1651  * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
1652  * NONWILD_SERVER set if the secret didn't have "*" for the server.
1653  * Any following words on the line up to a "--" (i.e. address authorization
1654  * info) are placed in a wordlist and returned in *addrs.  Any
1655  * following words (extra options) are placed in a wordlist and
1656  * returned in *opts.
1657  * We assume secret is NULL or points to MAXWORDLEN bytes of space.
1658  */
1659 static int
1660 scan_authfile(f, client, server, secret, addrs, opts, filename)
1661     FILE *f;
1662     char *client;
1663     char *server;
1664     char *secret;
1665     struct wordlist **addrs;
1666     struct wordlist **opts;
1667     char *filename;
1668 {
1669     int newline, xxx;
1670     int got_flag, best_flag;
1671     FILE *sf;
1672     struct wordlist *ap, *addr_list, *alist, **app;
1673     char word[MAXWORDLEN];
1674     char atfile[MAXWORDLEN];
1675     char lsecret[MAXWORDLEN];
1676
1677     if (addrs != NULL)
1678         *addrs = NULL;
1679     if (opts != NULL)
1680         *opts = NULL;
1681     addr_list = NULL;
1682     if (!getword(f, word, &newline, filename))
1683         return -1;              /* file is empty??? */
1684     newline = 1;
1685     best_flag = -1;
1686     for (;;) {
1687         /*
1688          * Skip until we find a word at the start of a line.
1689          */
1690         while (!newline && getword(f, word, &newline, filename))
1691             ;
1692         if (!newline)
1693             break;              /* got to end of file */
1694
1695         /*
1696          * Got a client - check if it's a match or a wildcard.
1697          */
1698         got_flag = 0;
1699         if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
1700             newline = 0;
1701             continue;
1702         }
1703         if (!ISWILD(word))
1704             got_flag = NONWILD_CLIENT;
1705
1706         /*
1707          * Now get a server and check if it matches.
1708          */
1709         if (!getword(f, word, &newline, filename))
1710             break;
1711         if (newline)
1712             continue;
1713         if (!ISWILD(word)) {
1714             if (server != NULL && strcmp(word, server) != 0)
1715                 continue;
1716             got_flag |= NONWILD_SERVER;
1717         }
1718
1719         /*
1720          * Got some sort of a match - see if it's better than what
1721          * we have already.
1722          */
1723         if (got_flag <= best_flag)
1724             continue;
1725
1726         /*
1727          * Get the secret.
1728          */
1729         if (!getword(f, word, &newline, filename))
1730             break;
1731         if (newline)
1732             continue;
1733
1734         /*
1735          * Special syntax: @filename means read secret from file.
1736          */
1737         if (word[0] == '@') {
1738             strlcpy(atfile, word+1, sizeof(atfile));
1739             if ((sf = fopen(atfile, "r")) == NULL) {
1740                 warn("can't open indirect secret file %s", atfile);
1741                 continue;
1742             }
1743             check_access(sf, atfile);
1744             if (!getword(sf, word, &xxx, atfile)) {
1745                 warn("no secret in indirect secret file %s", atfile);
1746                 fclose(sf);
1747                 continue;
1748             }
1749             fclose(sf);
1750         }
1751         if (secret != NULL)
1752             strlcpy(lsecret, word, sizeof(lsecret));
1753
1754         /*
1755          * Now read address authorization info and make a wordlist.
1756          */
1757         app = &alist;
1758         for (;;) {
1759             if (!getword(f, word, &newline, filename) || newline)
1760                 break;
1761             ap = (struct wordlist *) malloc(sizeof(struct wordlist));
1762             if (ap == NULL)
1763                 novm("authorized addresses");
1764             ap->word = strdup(word);
1765             if (ap->word == NULL)
1766                 novm("authorized addresses");
1767             *app = ap;
1768             app = &ap->next;
1769         }
1770         *app = NULL;
1771
1772         /*
1773          * This is the best so far; remember it.
1774          */
1775         best_flag = got_flag;
1776         if (addr_list)
1777             free_wordlist(addr_list);
1778         addr_list = alist;
1779         if (secret != NULL)
1780             strlcpy(secret, lsecret, MAXWORDLEN);
1781
1782         if (!newline)
1783             break;
1784     }
1785
1786     /* scan for a -- word indicating the start of options */
1787     for (app = &addr_list; (ap = *app) != NULL; app = &ap->next)
1788         if (strcmp(ap->word, "--") == 0)
1789             break;
1790     /* ap = start of options */
1791     if (ap != NULL) {
1792         ap = ap->next;          /* first option */
1793         free(*app);                     /* free the "--" word */
1794         *app = NULL;            /* terminate addr list */
1795     }
1796     if (opts != NULL)
1797         *opts = ap;
1798     else if (ap != NULL)
1799         free_wordlist(ap);
1800     if (addrs != NULL)
1801         *addrs = addr_list;
1802     else if (addr_list != NULL)
1803         free_wordlist(addr_list);
1804
1805     return best_flag;
1806 }
1807
1808 /*
1809  * free_wordlist - release memory allocated for a wordlist.
1810  */
1811 static void
1812 free_wordlist(wp)
1813     struct wordlist *wp;
1814 {
1815     struct wordlist *next;
1816
1817     while (wp != NULL) {
1818         next = wp->next;
1819         free(wp);
1820         wp = next;
1821     }
1822 }
1823
1824 /*
1825  * auth_script_done - called when the auth-up or auth-down script
1826  * has finished.
1827  */
1828 static void
1829 auth_script_done(arg)
1830     void *arg;
1831 {
1832     auth_script_pid = 0;
1833     switch (auth_script_state) {
1834     case s_up:
1835         if (auth_state == s_down) {
1836             auth_script_state = s_down;
1837             auth_script(_PATH_AUTHDOWN);
1838         }
1839         break;
1840     case s_down:
1841         if (auth_state == s_up) {
1842             auth_script_state = s_up;
1843             auth_script(_PATH_AUTHUP);
1844         }
1845         break;
1846     }
1847 }
1848
1849 /*
1850  * auth_script - execute a script with arguments
1851  * interface-name peer-name real-user tty speed
1852  */
1853 static void
1854 auth_script(script)
1855     char *script;
1856 {
1857     char strspeed[32];
1858     struct passwd *pw;
1859     char struid[32];
1860     char *user_name;
1861     char *argv[8];
1862
1863     if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
1864         user_name = pw->pw_name;
1865     else {
1866         slprintf(struid, sizeof(struid), "%d", getuid());
1867         user_name = struid;
1868     }
1869     slprintf(strspeed, sizeof(strspeed), "%d", baud_rate);
1870
1871     argv[0] = script;
1872     argv[1] = ifname;
1873     argv[2] = peer_authname;
1874     argv[3] = user_name;
1875     argv[4] = devnam;
1876     argv[5] = strspeed;
1877     argv[6] = NULL;
1878
1879     auth_script_pid = run_program(script, argv, 0, auth_script_done, NULL);
1880 }