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