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