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