]> git.ozlabs.org Git - ppp.git/blob - pppd/auth.c
de3ae645ff0c84daa78a5a5d636b9b0590dc59bb
[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.52 1999/05/12 06:19:46 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             || (secret[0] != 0 && (cryptpap || strcmp(passwd, secret) != 0)
794                 && strcmp(crypt(passwd, secret), secret) != 0)) {
795             warn("PAP authentication failure for %s", user);
796             ret = UPAP_AUTHNAK;
797         }
798         fclose(f);
799     }
800
801     if (uselogin && ret == UPAP_AUTHACK) {
802         ret = plogin(user, passwd, msg, msglen);
803         if (ret == UPAP_AUTHNAK) {
804             warn("PAP login failure for %s", user);
805         }
806     }
807
808     if (ret == UPAP_AUTHNAK) {
809         if (*msg == (char *) 0)
810             *msg = "Login incorrect";
811         *msglen = strlen(*msg);
812         /*
813          * XXX can we ever get here more than once??
814          * Frustrate passwd stealer programs.
815          * Allow 10 tries, but start backing off after 3 (stolen from login).
816          * On 10'th, drop the connection.
817          */
818         if (attempts++ >= 10) {
819             warn("%d LOGIN FAILURES ON %s, %s", attempts, devnam, user);
820             lcp_close(unit, "login failed");
821         }
822         if (attempts > 3)
823             sleep((u_int) (attempts - 3) * 5);
824         if (addrs != NULL)
825             free_wordlist(addrs);
826
827     } else {
828         attempts = 0;                   /* Reset count */
829         if (*msg == (char *) 0)
830             *msg = "Login ok";
831         *msglen = strlen(*msg);
832         set_allowed_addrs(unit, addrs);
833     }
834
835     BZERO(passwd, sizeof(passwd));
836     BZERO(secret, sizeof(secret));
837
838     return ret;
839 }
840
841 /*
842  * This function is needed for PAM.
843  */
844
845 #ifdef USE_PAM
846 /* Static variables used to communicate between the conversation function
847  * and the server_login function 
848  */
849 static char *PAM_username;
850 static char *PAM_password;
851 static int PAM_error = 0;
852 static pam_handle_t *pamh = NULL;
853
854 /* PAM conversation function
855  * Here we assume (for now, at least) that echo on means login name, and
856  * echo off means password.
857  */
858
859 static int PAM_conv (int num_msg, const struct pam_message **msg,
860                     struct pam_response **resp, void *appdata_ptr)
861 {
862     int replies = 0;
863     struct pam_response *reply = NULL;
864
865 #define COPY_STRING(s) (s) ? strdup(s) : NULL
866
867     reply = malloc(sizeof(struct pam_response) * num_msg);
868     if (!reply) return PAM_CONV_ERR;
869
870     for (replies = 0; replies < num_msg; replies++) {
871         switch (msg[replies]->msg_style) {
872             case PAM_PROMPT_ECHO_ON:
873                 reply[replies].resp_retcode = PAM_SUCCESS;
874                 reply[replies].resp = COPY_STRING(PAM_username);
875                 /* PAM frees resp */
876                 break;
877             case PAM_PROMPT_ECHO_OFF:
878                 reply[replies].resp_retcode = PAM_SUCCESS;
879                 reply[replies].resp = COPY_STRING(PAM_password);
880                 /* PAM frees resp */
881                 break;
882             case PAM_TEXT_INFO:
883                 /* fall through */
884             case PAM_ERROR_MSG:
885                 /* ignore it, but pam still wants a NULL response... */
886                 reply[replies].resp_retcode = PAM_SUCCESS;
887                 reply[replies].resp = NULL;
888                 break;
889             default:       
890                 /* Must be an error of some sort... */
891                 free (reply);
892                 PAM_error = 1;
893                 return PAM_CONV_ERR;
894         }
895     }
896     *resp = reply;     
897     return PAM_SUCCESS;
898 }
899
900 static struct pam_conv PAM_conversation = {
901     &PAM_conv,
902     NULL
903 };
904 #endif  /* USE_PAM */
905
906 /*
907  * plogin - Check the user name and password against the system
908  * password database, and login the user if OK.
909  *
910  * returns:
911  *      UPAP_AUTHNAK: Login failed.
912  *      UPAP_AUTHACK: Login succeeded.
913  * In either case, msg points to an appropriate message.
914  */
915
916 static int
917 plogin(user, passwd, msg, msglen)
918     char *user;
919     char *passwd;
920     char **msg;
921     int *msglen;
922 {
923     char *tty;
924
925 #ifdef USE_PAM
926     int pam_error;
927
928     pam_error = pam_start ("ppp", user, &PAM_conversation, &pamh);
929     if (pam_error != PAM_SUCCESS) {
930         *msg = (char *) pam_strerror (pamh, pam_error);
931         reopen_log();
932         return UPAP_AUTHNAK;
933     }
934     /*
935      * Define the fields for the credential validation
936      */
937      
938     PAM_username = user;
939     PAM_password = passwd;
940     PAM_error = 0;
941     pam_set_item (pamh, PAM_TTY, devnam); /* this might be useful to some modules */
942
943     /*
944      * Validate the user
945      */
946     pam_error = pam_authenticate (pamh, PAM_SILENT);
947     if (pam_error == PAM_SUCCESS && !PAM_error) {    
948         pam_error = pam_acct_mgmt (pamh, PAM_SILENT);
949         if (pam_error == PAM_SUCCESS)
950             pam_open_session (pamh, PAM_SILENT);
951     }
952
953     *msg = (char *) pam_strerror (pamh, pam_error);
954
955     /*
956      * Clean up the mess
957      */
958     reopen_log();       /* apparently the PAM stuff does closelog() */
959     PAM_username = NULL;
960     PAM_password = NULL;
961     if (pam_error != PAM_SUCCESS)
962         return UPAP_AUTHNAK;
963 #else /* #ifdef USE_PAM */
964
965 /*
966  * Use the non-PAM methods directly
967  */
968
969 #ifdef HAS_SHADOW
970     struct spwd *spwd;
971     struct spwd *getspnam();
972 #endif
973     struct passwd *pw = getpwnam(user);
974
975     endpwent();
976     if (pw == NULL)
977         return (UPAP_AUTHNAK);
978
979 #ifdef HAS_SHADOW
980     spwd = getspnam(user);
981     endspent();
982     if (spwd) {
983         /* check the age of the password entry */
984         long now = time(NULL) / 86400L;
985
986         if ((spwd->sp_expire > 0 && now >= spwd->sp_expire)
987             || ((spwd->sp_max >= 0 && spwd->sp_max < 10000)
988                 && spwd->sp_lstchg >= 0
989                 && now >= spwd->sp_lstchg + spwd->sp_max)) {
990             warn("Password for %s has expired", user);
991             return (UPAP_AUTHNAK);
992         }
993         pw->pw_passwd = spwd->sp_pwdp;
994     }
995 #endif
996
997     /*
998      * If no passwd, don't let them login.
999      */
1000     if (pw->pw_passwd == NULL || strlen(pw->pw_passwd) < 2
1001         || strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd) != 0)
1002         return (UPAP_AUTHNAK);
1003
1004 #endif /* #ifdef USE_PAM */
1005
1006     /*
1007      * Write a wtmp entry for this user.
1008      */
1009
1010     tty = devnam;
1011     if (strncmp(tty, "/dev/", 5) == 0)
1012         tty += 5;
1013     logwtmp(tty, user, remote_name);            /* Add wtmp login entry */
1014
1015 #if defined(_PATH_LASTLOG) && !defined(USE_PAM)
1016     if (pw != (struct passwd *)NULL) {
1017             struct lastlog ll;
1018             int fd;
1019
1020             if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
1021                 (void)lseek(fd, (off_t)(pw->pw_uid * sizeof(ll)), SEEK_SET);
1022                 memset((void *)&ll, 0, sizeof(ll));
1023                 (void)time(&ll.ll_time);
1024                 (void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
1025                 (void)write(fd, (char *)&ll, sizeof(ll));
1026                 (void)close(fd);
1027             }
1028     }
1029 #endif /* _PATH_LASTLOG and not USE_PAM */
1030
1031     info("user %s logged in", user);
1032     logged_in = 1;
1033
1034     return (UPAP_AUTHACK);
1035 }
1036
1037 /*
1038  * plogout - Logout the user.
1039  */
1040 static void
1041 plogout()
1042 {
1043 #ifdef USE_PAM
1044     int pam_error;
1045
1046     if (pamh != NULL) {
1047         pam_error = pam_close_session (pamh, PAM_SILENT);
1048         pam_end (pamh, pam_error);
1049         pamh = NULL;
1050     }
1051     /* Apparently the pam stuff does closelog(). */
1052     reopen_log();
1053 #else /* ! USE_PAM */   
1054     char *tty;
1055
1056     tty = devnam;
1057     if (strncmp(tty, "/dev/", 5) == 0)
1058         tty += 5;
1059     logwtmp(tty, "", "");               /* Wipe out utmp logout entry */
1060 #endif /* ! USE_PAM */
1061     logged_in = 0;
1062 }
1063
1064
1065 /*
1066  * null_login - Check if a username of "" and a password of "" are
1067  * acceptable, and iff so, set the list of acceptable IP addresses
1068  * and return 1.
1069  */
1070 static int
1071 null_login(unit)
1072     int unit;
1073 {
1074     char *filename;
1075     FILE *f;
1076     int i, ret;
1077     struct wordlist *addrs;
1078     char secret[MAXWORDLEN];
1079
1080     /*
1081      * Open the file of pap secrets and scan for a suitable secret.
1082      * We don't accept a wildcard client.
1083      */
1084     filename = _PATH_UPAPFILE;
1085     addrs = NULL;
1086     f = fopen(filename, "r");
1087     if (f == NULL)
1088         return 0;
1089     check_access(f, filename);
1090
1091     i = scan_authfile(f, "", our_name, secret, &addrs, filename);
1092     ret = i >= 0 && (i & NONWILD_CLIENT) != 0 && secret[0] == 0;
1093     BZERO(secret, sizeof(secret));
1094
1095     if (ret)
1096         set_allowed_addrs(unit, addrs);
1097     else
1098         free_wordlist(addrs);
1099
1100     fclose(f);
1101     return ret;
1102 }
1103
1104
1105 /*
1106  * get_pap_passwd - get a password for authenticating ourselves with
1107  * our peer using PAP.  Returns 1 on success, 0 if no suitable password
1108  * could be found.
1109  * Assumes passwd points to MAXSECRETLEN bytes of space (if non-null).
1110  */
1111 static int
1112 get_pap_passwd(passwd)
1113     char *passwd;
1114 {
1115     char *filename;
1116     FILE *f;
1117     int ret;
1118     struct wordlist *addrs;
1119     char secret[MAXWORDLEN];
1120
1121     filename = _PATH_UPAPFILE;
1122     addrs = NULL;
1123     f = fopen(filename, "r");
1124     if (f == NULL)
1125         return 0;
1126     check_access(f, filename);
1127     ret = scan_authfile(f, user,
1128                         (remote_name[0]? remote_name: NULL),
1129                         secret, NULL, filename);
1130     fclose(f);
1131     if (ret < 0)
1132         return 0;
1133     if (passwd != NULL)
1134         strlcpy(passwd, secret, MAXSECRETLEN);
1135     BZERO(secret, sizeof(secret));
1136     return 1;
1137 }
1138
1139
1140 /*
1141  * have_pap_secret - check whether we have a PAP file with any
1142  * secrets that we could possibly use for authenticating the peer.
1143  */
1144 static int
1145 have_pap_secret(lacks_ipp)
1146     int *lacks_ipp;
1147 {
1148     FILE *f;
1149     int ret;
1150     char *filename;
1151     struct wordlist *addrs;
1152
1153     filename = _PATH_UPAPFILE;
1154     f = fopen(filename, "r");
1155     if (f == NULL)
1156         return 0;
1157
1158     ret = scan_authfile(f, (explicit_remote? remote_name: NULL), our_name,
1159                         NULL, &addrs, filename);
1160     fclose(f);
1161     if (ret >= 0 && !some_ip_ok(addrs)) {
1162         if (lacks_ipp != 0)
1163             *lacks_ipp = 1;
1164         ret = -1;
1165     }
1166     if (addrs != 0)
1167         free_wordlist(addrs);
1168
1169     return ret >= 0;
1170 }
1171
1172
1173 /*
1174  * have_chap_secret - check whether we have a CHAP file with a
1175  * secret that we could possibly use for authenticating `client'
1176  * on `server'.  Either can be the null string, meaning we don't
1177  * know the identity yet.
1178  */
1179 static int
1180 have_chap_secret(client, server, need_ip, lacks_ipp)
1181     char *client;
1182     char *server;
1183     int need_ip;
1184     int *lacks_ipp;
1185 {
1186     FILE *f;
1187     int ret;
1188     char *filename;
1189     struct wordlist *addrs;
1190
1191     filename = _PATH_CHAPFILE;
1192     f = fopen(filename, "r");
1193     if (f == NULL)
1194         return 0;
1195
1196     if (client != NULL && client[0] == 0)
1197         client = NULL;
1198     else if (server != NULL && server[0] == 0)
1199         server = NULL;
1200
1201     ret = scan_authfile(f, client, server, NULL, &addrs, filename);
1202     fclose(f);
1203     if (ret >= 0 && need_ip && !some_ip_ok(addrs)) {
1204         if (lacks_ipp != 0)
1205             *lacks_ipp = 1;
1206         ret = -1;
1207     }
1208     if (addrs != 0)
1209         free_wordlist(addrs);
1210
1211     return ret >= 0;
1212 }
1213
1214
1215 /*
1216  * get_secret - open the CHAP secret file and return the secret
1217  * for authenticating the given client on the given server.
1218  * (We could be either client or server).
1219  */
1220 int
1221 get_secret(unit, client, server, secret, secret_len, save_addrs)
1222     int unit;
1223     char *client;
1224     char *server;
1225     char *secret;
1226     int *secret_len;
1227     int save_addrs;
1228 {
1229     FILE *f;
1230     int ret, len;
1231     char *filename;
1232     struct wordlist *addrs;
1233     char secbuf[MAXWORDLEN];
1234
1235     filename = _PATH_CHAPFILE;
1236     addrs = NULL;
1237     secbuf[0] = 0;
1238
1239     f = fopen(filename, "r");
1240     if (f == NULL) {
1241         error("Can't open chap secret file %s: %m", filename);
1242         return 0;
1243     }
1244     check_access(f, filename);
1245
1246     ret = scan_authfile(f, client, server, secbuf, &addrs, filename);
1247     fclose(f);
1248     if (ret < 0)
1249         return 0;
1250
1251     if (save_addrs)
1252         set_allowed_addrs(unit, addrs);
1253
1254     len = strlen(secbuf);
1255     if (len > MAXSECRETLEN) {
1256         error("Secret for %s on %s is too long", client, server);
1257         len = MAXSECRETLEN;
1258     }
1259     BCOPY(secbuf, secret, len);
1260     BZERO(secbuf, sizeof(secbuf));
1261     *secret_len = len;
1262
1263     return 1;
1264 }
1265
1266 /*
1267  * set_allowed_addrs() - set the list of allowed addresses.
1268  */
1269 static void
1270 set_allowed_addrs(unit, addrs)
1271     int unit;
1272     struct wordlist *addrs;
1273 {
1274     int n = 0;
1275     struct wordlist *ap;
1276     struct permitted_ip *ip;
1277     char *ptr_word, *ptr_mask;
1278     struct hostent *hp;
1279     struct netent *np;
1280     u_int32_t a, mask, ah;
1281     struct ipcp_options *wo = &ipcp_wantoptions[unit];
1282     u_int32_t suggested_ip = 0;
1283
1284     if (addresses[unit] != NULL)
1285         free(addresses[unit]);
1286     addresses[unit] = NULL;
1287
1288     for (ap = addrs; ap != NULL; ap = ap->next)
1289         ++n;
1290     if (n == 0)
1291         return;
1292     ip = (struct permitted_ip *) malloc((n + 1) * sizeof(struct permitted_ip));
1293     if (ip == 0)
1294         return;
1295
1296     n = 0;
1297     for (ap = addrs; ap != NULL; ap = ap->next) {
1298         /* "-" means no addresses authorized, "*" means any address allowed */
1299         ptr_word = ap->word;
1300         if (strcmp(ptr_word, "-") == 0)
1301             break;
1302         if (strcmp(ptr_word, "*") == 0) {
1303             ip[n].permit = 1;
1304             ip[n].base = ip[n].mask = 0;
1305             ++n;
1306             break;
1307         }
1308
1309         ip[n].permit = 1;
1310         if (*ptr_word == '!') {
1311             ip[n].permit = 0;
1312             ++ptr_word;
1313         }
1314
1315         mask = ~ (u_int32_t) 0;
1316         ptr_mask = strchr (ptr_word, '/');
1317         if (ptr_mask != NULL) {
1318             int bit_count;
1319
1320             bit_count = (int) strtol (ptr_mask+1, (char **) 0, 10);
1321             if (bit_count <= 0 || bit_count > 32) {
1322                 warn("invalid address length %v in auth. address list",
1323                      ptr_mask);
1324                 continue;
1325             }
1326             *ptr_mask = '\0';
1327             mask <<= 32 - bit_count;
1328         }
1329
1330         hp = gethostbyname(ptr_word);
1331         if (hp != NULL && hp->h_addrtype == AF_INET) {
1332             a = *(u_int32_t *)hp->h_addr;
1333         } else {
1334             np = getnetbyname (ptr_word);
1335             if (np != NULL && np->n_addrtype == AF_INET) {
1336                 a = htonl (*(u_int32_t *)np->n_net);
1337                 if (ptr_mask == NULL) {
1338                     /* calculate appropriate mask for net */
1339                     ah = ntohl(a);
1340                     if (IN_CLASSA(ah))
1341                         mask = IN_CLASSA_NET;
1342                     else if (IN_CLASSB(ah))
1343                         mask = IN_CLASSB_NET;
1344                     else if (IN_CLASSC(ah))
1345                         mask = IN_CLASSC_NET;
1346                 }
1347             } else {
1348                 a = inet_addr (ptr_word);
1349             }
1350         }
1351
1352         if (ptr_mask != NULL)
1353             *ptr_mask = '/';
1354
1355         if (a == (u_int32_t)-1L)
1356             warn("unknown host %s in auth. address list", ap->word);
1357         else {
1358             ip[n].mask = htonl(mask);
1359             ip[n].base = a & ip[n].mask;
1360             ++n;
1361             if (~mask == 0 && suggested_ip == 0)
1362                 suggested_ip = a;
1363         }
1364     }
1365
1366     ip[n].permit = 0;           /* make the last entry forbid all addresses */
1367     ip[n].base = 0;             /* to terminate the list */
1368     ip[n].mask = 0;
1369
1370     addresses[unit] = ip;
1371
1372     /*
1373      * If the address given for the peer isn't authorized, or if
1374      * the user hasn't given one, AND there is an authorized address
1375      * which is a single host, then use that if we find one.
1376      */
1377     if (suggested_ip != 0
1378         && (wo->hisaddr == 0 || !auth_ip_addr(unit, wo->hisaddr)))
1379         wo->hisaddr = suggested_ip;
1380 }
1381
1382 /*
1383  * auth_ip_addr - check whether the peer is authorized to use
1384  * a given IP address.  Returns 1 if authorized, 0 otherwise.
1385  */
1386 int
1387 auth_ip_addr(unit, addr)
1388     int unit;
1389     u_int32_t addr;
1390 {
1391     if (addresses[unit] == NULL) {
1392         if (auth_required)
1393             return 0;           /* no addresses authorized */
1394         return allow_any_ip || !have_route_to(addr);
1395     }
1396     return ip_addr_check(addr, addresses[unit]);
1397 }
1398
1399 static int
1400 ip_addr_check(addr, addrs)
1401     u_int32_t addr;
1402     struct permitted_ip *addrs;
1403 {
1404     /* don't allow loopback or multicast address */
1405     if (bad_ip_adrs(addr))
1406         return 0;
1407
1408     for (; ; ++addrs)
1409         if ((addr & addrs->mask) == addrs->base)
1410             return addrs->permit;
1411 }
1412
1413 /*
1414  * bad_ip_adrs - return 1 if the IP address is one we don't want
1415  * to use, such as an address in the loopback net or a multicast address.
1416  * addr is in network byte order.
1417  */
1418 int
1419 bad_ip_adrs(addr)
1420     u_int32_t addr;
1421 {
1422     addr = ntohl(addr);
1423     return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
1424         || IN_MULTICAST(addr) || IN_BADCLASS(addr);
1425 }
1426
1427 /*
1428  * some_ip_ok - check a wordlist to see if it authorizes any
1429  * IP address(es).
1430  */
1431 static int
1432 some_ip_ok(addrs)
1433     struct wordlist *addrs;
1434 {
1435     for (; addrs != 0; addrs = addrs->next) {
1436         if (strcmp(addrs->word, "-") == 0)
1437             break;
1438         if (addrs->word[0] != '!')
1439             return 1;           /* some IP address is allowed */
1440     }
1441     return 0;
1442 }
1443
1444 /*
1445  * check_access - complain if a secret file has too-liberal permissions.
1446  */
1447 static void
1448 check_access(f, filename)
1449     FILE *f;
1450     char *filename;
1451 {
1452     struct stat sbuf;
1453
1454     if (fstat(fileno(f), &sbuf) < 0) {
1455         warn("cannot stat secret file %s: %m", filename);
1456     } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1457         warn("Warning - secret file %s has world and/or group access",
1458              filename);
1459     }
1460 }
1461
1462
1463 /*
1464  * scan_authfile - Scan an authorization file for a secret suitable
1465  * for authenticating `client' on `server'.  The return value is -1
1466  * if no secret is found, otherwise >= 0.  The return value has
1467  * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
1468  * NONWILD_SERVER set if the secret didn't have "*" for the server.
1469  * Any following words on the line (i.e. address authorization
1470  * info) are placed in a wordlist and returned in *addrs.
1471  * We assume secret is NULL or points to MAXWORDLEN bytes of space.
1472  */
1473 static int
1474 scan_authfile(f, client, server, secret, addrs, filename)
1475     FILE *f;
1476     char *client;
1477     char *server;
1478     char *secret;
1479     struct wordlist **addrs;
1480     char *filename;
1481 {
1482     int newline, xxx;
1483     int got_flag, best_flag;
1484     FILE *sf;
1485     struct wordlist *ap, *addr_list, *alist, *alast;
1486     char word[MAXWORDLEN];
1487     char atfile[MAXWORDLEN];
1488     char lsecret[MAXWORDLEN];
1489
1490     if (addrs != NULL)
1491         *addrs = NULL;
1492     addr_list = NULL;
1493     if (!getword(f, word, &newline, filename))
1494         return -1;              /* file is empty??? */
1495     newline = 1;
1496     best_flag = -1;
1497     for (;;) {
1498         /*
1499          * Skip until we find a word at the start of a line.
1500          */
1501         while (!newline && getword(f, word, &newline, filename))
1502             ;
1503         if (!newline)
1504             break;              /* got to end of file */
1505
1506         /*
1507          * Got a client - check if it's a match or a wildcard.
1508          */
1509         got_flag = 0;
1510         if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
1511             newline = 0;
1512             continue;
1513         }
1514         if (!ISWILD(word))
1515             got_flag = NONWILD_CLIENT;
1516
1517         /*
1518          * Now get a server and check if it matches.
1519          */
1520         if (!getword(f, word, &newline, filename))
1521             break;
1522         if (newline)
1523             continue;
1524         if (!ISWILD(word)) {
1525             if (server != NULL && strcmp(word, server) != 0)
1526                 continue;
1527             got_flag |= NONWILD_SERVER;
1528         }
1529
1530         /*
1531          * Got some sort of a match - see if it's better than what
1532          * we have already.
1533          */
1534         if (got_flag <= best_flag)
1535             continue;
1536
1537         /*
1538          * Get the secret.
1539          */
1540         if (!getword(f, word, &newline, filename))
1541             break;
1542         if (newline)
1543             continue;
1544
1545         /*
1546          * Special syntax: @filename means read secret from file.
1547          */
1548         if (word[0] == '@') {
1549             strlcpy(atfile, word+1, sizeof(atfile));
1550             if ((sf = fopen(atfile, "r")) == NULL) {
1551                 warn("can't open indirect secret file %s", atfile);
1552                 continue;
1553             }
1554             check_access(sf, atfile);
1555             if (!getword(sf, word, &xxx, atfile)) {
1556                 warn("no secret in indirect secret file %s", atfile);
1557                 fclose(sf);
1558                 continue;
1559             }
1560             fclose(sf);
1561         }
1562         if (secret != NULL)
1563             strlcpy(lsecret, word, sizeof(lsecret));
1564
1565         /*
1566          * Now read address authorization info and make a wordlist.
1567          */
1568         alist = alast = NULL;
1569         for (;;) {
1570             if (!getword(f, word, &newline, filename) || newline)
1571                 break;
1572             ap = (struct wordlist *) malloc(sizeof(struct wordlist));
1573             if (ap == NULL)
1574                 novm("authorized addresses");
1575             ap->next = NULL;
1576             ap->word = strdup(word);
1577             if (ap->word == NULL)
1578                 novm("authorized address");
1579             if (alist == NULL)
1580                 alist = ap;
1581             else
1582                 alast->next = ap;
1583             alast = ap;
1584         }
1585
1586         /*
1587          * This is the best so far; remember it.
1588          */
1589         best_flag = got_flag;
1590         if (addr_list)
1591             free_wordlist(addr_list);
1592         addr_list = alist;
1593         if (secret != NULL)
1594             strlcpy(secret, lsecret, MAXWORDLEN);
1595
1596         if (!newline)
1597             break;
1598     }
1599
1600     if (addrs != NULL)
1601         *addrs = addr_list;
1602     else if (addr_list != NULL)
1603         free_wordlist(addr_list);
1604
1605     return best_flag;
1606 }
1607
1608 /*
1609  * free_wordlist - release memory allocated for a wordlist.
1610  */
1611 static void
1612 free_wordlist(wp)
1613     struct wordlist *wp;
1614 {
1615     struct wordlist *next;
1616
1617     while (wp != NULL) {
1618         next = wp->next;
1619         free(wp);
1620         wp = next;
1621     }
1622 }
1623
1624 /*
1625  * auth_script_done - called when the auth-up or auth-down script
1626  * has finished.
1627  */
1628 static void
1629 auth_script_done(arg)
1630     void *arg;
1631 {
1632     auth_script_pid = 0;
1633     switch (auth_script_state) {
1634     case s_up:
1635         if (auth_state == s_down) {
1636             auth_script_state = s_down;
1637             auth_script(_PATH_AUTHDOWN);
1638         }
1639         break;
1640     case s_down:
1641         if (auth_state == s_up) {
1642             auth_script_state = s_up;
1643             auth_script(_PATH_AUTHUP);
1644         }
1645         break;
1646     }
1647 }
1648
1649 /*
1650  * auth_script - execute a script with arguments
1651  * interface-name peer-name real-user tty speed
1652  */
1653 static void
1654 auth_script(script)
1655     char *script;
1656 {
1657     char strspeed[32];
1658     struct passwd *pw;
1659     char struid[32];
1660     char *user_name;
1661     char *argv[8];
1662
1663     if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
1664         user_name = pw->pw_name;
1665     else {
1666         slprintf(struid, sizeof(struid), "%d", getuid());
1667         user_name = struid;
1668     }
1669     slprintf(strspeed, sizeof(strspeed), "%d", baud_rate);
1670
1671     argv[0] = script;
1672     argv[1] = ifname;
1673     argv[2] = peer_authname;
1674     argv[3] = user_name;
1675     argv[4] = devnam;
1676     argv[5] = strspeed;
1677     argv[6] = NULL;
1678
1679     auth_script_pid = run_program(script, argv, 0, auth_script_done, NULL);
1680 }