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