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