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