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