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