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