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