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