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