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