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