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