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