]> git.ozlabs.org Git - ppp.git/blob - pppd/auth.c
fixes from Farrell
[ppp.git] / pppd / auth.c
1 /*
2  * auth.c - PPP authentication and phase control.
3  *
4  * Copyright (c) 1993 The Australian National University.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms are permitted
8  * provided that the above copyright notice and this paragraph are
9  * duplicated in all such forms and that any documentation,
10  * advertising materials, and other materials related to such
11  * distribution and use acknowledge that the software was developed
12  * by the Australian National University.  The name of the University
13  * may not be used to endorse or promote products derived from this
14  * software without specific prior written permission.
15  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18  *
19  * Copyright (c) 1989 Carnegie Mellon University.
20  * All rights reserved.
21  *
22  * Redistribution and use in source and binary forms are permitted
23  * provided that the above copyright notice and this paragraph are
24  * duplicated in all such forms and that any documentation,
25  * advertising materials, and other materials related to such
26  * distribution and use acknowledge that the software was developed
27  * by Carnegie Mellon University.  The name of the
28  * University may not be used to endorse or promote products derived
29  * from this software without specific prior written permission.
30  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
32  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
33  */
34
35 #ifndef lint
36 static char rcsid[] = "$Id: auth.c,v 1.31 1997/04/30 05:50:16 paulus Exp $";
37 #endif
38
39 #include <stdio.h>
40 #include <stddef.h>
41 #include <stdlib.h>
42 #include <unistd.h>
43 #include <syslog.h>
44 #include <pwd.h>
45 #include <string.h>
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <sys/socket.h>
49
50 #include <netdb.h>
51 #include <netinet/in.h>
52 #include <arpa/inet.h>
53
54 #ifdef USE_PAM
55 #include <security/pam_appl.h>
56 #include <security/pam_modules.h>
57 #endif
58
59 #ifdef HAS_SHADOW
60 #include <shadow.h>
61 #ifndef SVR4
62 #include <shadow/pwauth.h>
63 #endif
64 #ifndef PW_PPP
65 #define PW_PPP PW_LOGIN
66 #endif
67 #endif
68
69 #include "pppd.h"
70 #include "fsm.h"
71 #include "lcp.h"
72 #include "ipcp.h"
73 #include "upap.h"
74 #include "chap.h"
75 #ifdef CBCP_SUPPORT
76 #include "cbcp.h"
77 #endif
78 #include "pathnames.h"
79
80 /* Used for storing a sequence of words.  Usually malloced. */
81 struct wordlist {
82     struct wordlist     *next;
83     char                word[1];
84 };
85
86 /* Bits in scan_authfile return value */
87 #define NONWILD_SERVER  1
88 #define NONWILD_CLIENT  2
89
90 #define ISWILD(word)    (word[0] == '*' && word[1] == 0)
91
92 #define FALSE   0
93 #define TRUE    1
94
95 /* The name by which the peer authenticated itself to us. */
96 char peer_authname[MAXNAMELEN];
97
98 /* Records which authentication operations haven't completed yet. */
99 static int auth_pending[NUM_PPP];
100
101 /* Set if we have successfully called login() */
102 static int logged_in;
103
104 /* Set if we have run the /etc/ppp/auth-up script. */
105 static int did_authup;
106
107 /* List of addresses which the peer may use. */
108 static struct wordlist *addresses[NUM_PPP];
109
110 /* Number of network protocols which we have opened. */
111 static int num_np_open;
112
113 /* Number of network protocols which have come up. */
114 static int num_np_up;
115
116 /* Set if we got the contents of passwd[] from the pap-secrets file. */
117 static int passwd_from_file;
118
119 /* Bits in auth_pending[] */
120 #define PAP_WITHPEER    1
121 #define PAP_PEER        2
122 #define CHAP_WITHPEER   4
123 #define CHAP_PEER       8
124
125 extern char *crypt __P((const char *, const char *));
126
127 /* Prototypes for procedures local to this file. */
128
129 static void network_phase __P((int));
130 static void check_idle __P((void *));
131 static void connect_time_expired __P((void *));
132 static int  login __P((char *, char *, char **, int *));
133 static void logout __P((void));
134 static int  null_login __P((int));
135 static int  get_pap_passwd __P((char *));
136 static int  have_pap_secret __P((void));
137 static int  have_chap_secret __P((char *, char *, u_int32_t));
138 static int  ip_addr_check __P((u_int32_t, struct wordlist *));
139 static int  scan_authfile __P((FILE *, char *, char *, u_int32_t, char *,
140                                struct wordlist **, char *));
141 static void free_wordlist __P((struct wordlist *));
142 static void auth_script __P((char *));
143 static void set_allowed_addrs __P((int, struct wordlist *));
144 #ifdef CBCP_SUPPORT
145 static void callback_phase __P((int));
146 #endif
147
148 /*
149  * An Open on LCP has requested a change from Dead to Establish phase.
150  * Do what's necessary to bring the physical layer up.
151  */
152 void
153 link_required(unit)
154     int unit;
155 {
156 }
157
158 /*
159  * LCP has terminated the link; go to the Dead phase and take the
160  * physical layer down.
161  */
162 void
163 link_terminated(unit)
164     int unit;
165 {
166     if (phase == PHASE_DEAD)
167         return;
168     if (logged_in)
169         logout();
170     phase = PHASE_DEAD;
171     syslog(LOG_NOTICE, "Connection terminated.");
172 }
173
174 /*
175  * LCP has gone down; it will either die or try to re-establish.
176  */
177 void
178 link_down(unit)
179     int unit;
180 {
181     int i;
182     struct protent *protp;
183
184     if (did_authup) {
185         auth_script(_PATH_AUTHDOWN);
186         did_authup = 0;
187     }
188     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
189         if (!protp->enabled_flag)
190             continue;
191         if (protp->protocol != PPP_LCP && protp->lowerdown != NULL)
192             (*protp->lowerdown)(unit);
193         if (protp->protocol < 0xC000 && protp->close != NULL)
194             (*protp->close)(unit, "LCP down");
195     }
196     num_np_open = 0;
197     num_np_up = 0;
198     if (phase != PHASE_DEAD)
199         phase = PHASE_TERMINATE;
200 }
201
202 /*
203  * The link is established.
204  * Proceed to the Dead, Authenticate or Network phase as appropriate.
205  */
206 void
207 link_established(unit)
208     int unit;
209 {
210     int auth;
211     lcp_options *wo = &lcp_wantoptions[unit];
212     lcp_options *go = &lcp_gotoptions[unit];
213     lcp_options *ho = &lcp_hisoptions[unit];
214     int i;
215     struct protent *protp;
216
217     /*
218      * Tell higher-level protocols that LCP is up.
219      */
220     for (i = 0; (protp = protocols[i]) != NULL; ++i)
221         if (protp->protocol != PPP_LCP && protp->enabled_flag
222             && protp->lowerup != NULL)
223             (*protp->lowerup)(unit);
224
225     if (auth_required && !(go->neg_chap || go->neg_upap)) {
226         /*
227          * We wanted the peer to authenticate itself, and it refused:
228          * treat it as though it authenticated with PAP using a username
229          * of "" and a password of "".  If that's not OK, boot it out.
230          */
231         if (!wo->neg_upap || !null_login(unit)) {
232             syslog(LOG_WARNING, "peer refused to authenticate");
233             lcp_close(unit, "peer refused to authenticate");
234             return;
235         }
236     }
237
238     phase = PHASE_AUTHENTICATE;
239     auth = 0;
240     if (go->neg_chap) {
241         ChapAuthPeer(unit, our_name, go->chap_mdtype);
242         auth |= CHAP_PEER;
243     } else if (go->neg_upap) {
244         upap_authpeer(unit);
245         auth |= PAP_PEER;
246     }
247     if (ho->neg_chap) {
248         ChapAuthWithPeer(unit, user, ho->chap_mdtype);
249         auth |= CHAP_WITHPEER;
250     } else if (ho->neg_upap) {
251         if (passwd[0] == 0) {
252             passwd_from_file = 1;
253             if (!get_pap_passwd(passwd))
254                 syslog(LOG_ERR, "No secret found for PAP login");
255         }
256         upap_authwithpeer(unit, user, passwd);
257         auth |= PAP_WITHPEER;
258     }
259     auth_pending[unit] = auth;
260
261     if (!auth)
262         network_phase(unit);
263 }
264
265 /*
266  * Proceed to the network phase.
267  */
268 static void
269 network_phase(unit)
270     int unit;
271 {
272     int i;
273     struct protent *protp;
274     lcp_options *go = &lcp_gotoptions[unit];
275
276     /*
277      * If the peer had to authenticate, run the auth-up script now.
278      */
279     if ((go->neg_chap || go->neg_upap) && !did_authup) {
280         auth_script(_PATH_AUTHUP);
281         did_authup = 1;
282     }
283
284 #ifdef CBCP_SUPPORT
285     /*
286      * If we negotiated callback, do it now.
287      */
288     if (go->neg_cbcp) {
289         phase = PHASE_CALLBACK;
290         (*cbcp_protent.open)(unit);
291         return;
292     }
293 #endif
294
295     phase = PHASE_NETWORK;
296 #if 0
297     if (!demand)
298         set_filters(&pass_filter, &active_filter);
299 #endif
300     for (i = 0; (protp = protocols[i]) != NULL; ++i)
301         if (protp->protocol < 0xC000 && protp->enabled_flag
302             && protp->open != NULL) {
303             (*protp->open)(unit);
304             if (protp->protocol != PPP_CCP)
305                 ++num_np_open;
306         }
307 }
308
309 /*
310  * The peer has failed to authenticate himself using `protocol'.
311  */
312 void
313 auth_peer_fail(unit, protocol)
314     int unit, protocol;
315 {
316     /*
317      * Authentication failure: take the link down
318      */
319     lcp_close(unit, "Authentication failed");
320 }
321
322 /*
323  * The peer has been successfully authenticated using `protocol'.
324  */
325 void
326 auth_peer_success(unit, protocol, name, namelen)
327     int unit, protocol;
328     char *name;
329     int namelen;
330 {
331     int bit;
332
333     switch (protocol) {
334     case PPP_CHAP:
335         bit = CHAP_PEER;
336         break;
337     case PPP_PAP:
338         bit = PAP_PEER;
339         break;
340     default:
341         syslog(LOG_WARNING, "auth_peer_success: unknown protocol %x",
342                protocol);
343         return;
344     }
345
346     /*
347      * Save the authenticated name of the peer for later.
348      */
349     if (namelen > sizeof(peer_authname) - 1)
350         namelen = sizeof(peer_authname) - 1;
351     BCOPY(name, peer_authname, namelen);
352     peer_authname[namelen] = 0;
353
354     /*
355      * If there is no more authentication still to be done,
356      * proceed to the network (or callback) phase.
357      */
358     if ((auth_pending[unit] &= ~bit) == 0)
359         network_phase(unit);
360 }
361
362 /*
363  * We have failed to authenticate ourselves to the peer using `protocol'.
364  */
365 void
366 auth_withpeer_fail(unit, protocol)
367     int unit, protocol;
368 {
369     if (passwd_from_file)
370         BZERO(passwd, MAXSECRETLEN);
371     /*
372      * We've failed to authenticate ourselves to our peer.
373      * He'll probably take the link down, and there's not much
374      * we can do except wait for that.
375      */
376 }
377
378 /*
379  * We have successfully authenticated ourselves with the peer using `protocol'.
380  */
381 void
382 auth_withpeer_success(unit, protocol)
383     int unit, protocol;
384 {
385     int bit;
386
387     switch (protocol) {
388     case PPP_CHAP:
389         bit = CHAP_WITHPEER;
390         break;
391     case PPP_PAP:
392         if (passwd_from_file)
393             BZERO(passwd, MAXSECRETLEN);
394         bit = PAP_WITHPEER;
395         break;
396     default:
397         syslog(LOG_WARNING, "auth_peer_success: unknown protocol %x",
398                protocol);
399         bit = 0;
400     }
401
402     /*
403      * If there is no more authentication still being done,
404      * proceed to the network (or callback) phase.
405      */
406     if ((auth_pending[unit] &= ~bit) == 0)
407         network_phase(unit);
408 }
409
410
411 /*
412  * np_up - a network protocol has come up.
413  */
414 void
415 np_up(unit, proto)
416     int unit, proto;
417 {
418     if (num_np_up == 0 && idle_time_limit > 0) {
419         TIMEOUT(check_idle, NULL, idle_time_limit);
420
421         /*
422          * Set a timeout to close the connection once the maximum
423          * connect time has expired.
424          */
425         if (maxconnect > 0)
426             TIMEOUT(connect_time_expired, 0, maxconnect);
427     }
428     ++num_np_up;
429 }
430
431 /*
432  * np_down - a network protocol has gone down.
433  */
434 void
435 np_down(unit, proto)
436     int unit, proto;
437 {
438     if (--num_np_up == 0 && idle_time_limit > 0) {
439         UNTIMEOUT(check_idle, NULL);
440     }
441 }
442
443 /*
444  * np_finished - a network protocol has finished using the link.
445  */
446 void
447 np_finished(unit, proto)
448     int unit, proto;
449 {
450     if (--num_np_open <= 0) {
451         /* no further use for the link: shut up shop. */
452         lcp_close(0, "No network protocols running");
453     }
454 }
455
456 /*
457  * check_idle - check whether the link has been idle for long
458  * enough that we can shut it down.
459  */
460 static void
461 check_idle(arg)
462      void *arg;
463 {
464     struct ppp_idle idle;
465     time_t itime;
466
467     if (!get_idle_time(0, &idle))
468         return;
469     itime = MIN(idle.xmit_idle, idle.recv_idle);
470     if (itime >= idle_time_limit) {
471         /* link is idle: shut it down. */
472         syslog(LOG_INFO, "Terminating connection due to lack of activity.");
473         need_holdoff = 0;
474         lcp_close(0, "Link inactive");
475     } else {
476         TIMEOUT(check_idle, NULL, idle_time_limit - itime);
477     }
478 }
479
480 /*
481  * connect_time_expired - log a message and close the connection.
482  */
483 static void
484 connect_time_expired(arg)
485     void *arg;
486 {
487     syslog(LOG_INFO, "Connect time expired");
488     lcp_close(0, "Connect time expired");       /* Close connection */
489 }
490
491 /*
492  * auth_check_options - called to check authentication options.
493  */
494 void
495 auth_check_options()
496 {
497     lcp_options *wo = &lcp_wantoptions[0];
498     int can_auth;
499     ipcp_options *ipwo = &ipcp_wantoptions[0];
500     u_int32_t remote;
501
502     /* Default our_name to hostname, and user to our_name */
503     if (our_name[0] == 0 || usehostname)
504         strcpy(our_name, hostname);
505     if (user[0] == 0)
506         strcpy(user, our_name);
507
508     /* If authentication is required, ask peer for CHAP or PAP. */
509     if (auth_required && !wo->neg_chap && !wo->neg_upap) {
510         wo->neg_chap = 1;
511         wo->neg_upap = 1;
512     }
513
514     /*
515      * Check whether we have appropriate secrets to use
516      * to authenticate the peer.
517      */
518     can_auth = wo->neg_upap && (uselogin || have_pap_secret());
519     if (!can_auth && wo->neg_chap) {
520         remote = ipwo->accept_remote? 0: ipwo->hisaddr;
521         can_auth = have_chap_secret(remote_name, our_name, remote);
522     }
523
524     if (auth_required && !can_auth) {
525         option_error("peer authentication required but no suitable secret(s) found\n");
526         if (remote_name[0] == 0)
527             option_error("for authenticating any peer to us (%s)\n", our_name);
528         else
529             option_error("for authenticating peer %s to us (%s)\n",
530                          remote_name, our_name);
531         exit(1);
532     }
533
534     /*
535      * Check whether the user tried to override certain values
536      * set by root.
537      */
538     if (!auth_required && auth_req_info.priv > 0) {
539         if (!default_device && devnam_info.priv == 0) {
540             option_error("can't override device name when noauth option used");
541             exit(1);
542         }
543         if ((connector != NULL && connector_info.priv == 0)
544             || (disconnector != NULL && disconnector_info.priv == 0)
545             || (welcomer != NULL && welcomer_info.priv == 0)) {
546             option_error("can't override connect, disconnect or welcome");
547             option_error("option values when noauth option used");
548             exit(1);
549         }
550     }
551 }
552
553 /*
554  * auth_reset - called when LCP is starting negotiations to recheck
555  * authentication options, i.e. whether we have appropriate secrets
556  * to use for authenticating ourselves and/or the peer.
557  */
558 void
559 auth_reset(unit)
560     int unit;
561 {
562     lcp_options *go = &lcp_gotoptions[unit];
563     lcp_options *ao = &lcp_allowoptions[0];
564     ipcp_options *ipwo = &ipcp_wantoptions[0];
565     u_int32_t remote;
566
567     ao->neg_upap = !refuse_pap && (passwd[0] != 0 || get_pap_passwd(NULL));
568     ao->neg_chap = !refuse_chap
569         && have_chap_secret(user, remote_name, (u_int32_t)0);
570
571     if (go->neg_upap && !uselogin && !have_pap_secret())
572         go->neg_upap = 0;
573     if (go->neg_chap) {
574         remote = ipwo->accept_remote? 0: ipwo->hisaddr;
575         if (!have_chap_secret(remote_name, our_name, remote))
576             go->neg_chap = 0;
577     }
578
579 }
580
581
582 /*
583  * check_passwd - Check the user name and passwd against the PAP secrets
584  * file.  If requested, also check against the system password database,
585  * and login the user if OK.
586  *
587  * returns:
588  *      UPAP_AUTHNAK: Authentication failed.
589  *      UPAP_AUTHACK: Authentication succeeded.
590  * In either case, msg points to an appropriate message.
591  */
592 int
593 check_passwd(unit, auser, userlen, apasswd, passwdlen, msg, msglen)
594     int unit;
595     char *auser;
596     int userlen;
597     char *apasswd;
598     int passwdlen;
599     char **msg;
600     int *msglen;
601 {
602     int ret;
603     char *filename;
604     FILE *f;
605     struct wordlist *addrs;
606     u_int32_t remote;
607     ipcp_options *ipwo = &ipcp_wantoptions[unit];
608     char passwd[256], user[256];
609     char secret[MAXWORDLEN];
610     static int attempts = 0;
611
612     /*
613      * Make copies of apasswd and auser, then null-terminate them.
614      */
615     BCOPY(apasswd, passwd, passwdlen);
616     passwd[passwdlen] = '\0';
617     BCOPY(auser, user, userlen);
618     user[userlen] = '\0';
619     *msg = (char *) 0;
620
621     /*
622      * Open the file of pap secrets and scan for a suitable secret
623      * for authenticating this user.
624      */
625     filename = _PATH_UPAPFILE;
626     addrs = NULL;
627     ret = UPAP_AUTHACK;
628     f = fopen(filename, "r");
629     if (f == NULL) {
630         syslog(LOG_ERR, "Can't open PAP password file %s: %m", filename);
631         ret = UPAP_AUTHNAK;
632
633     } else {
634         check_access(f, filename);
635         remote = ipwo->accept_remote? 0: ipwo->hisaddr;
636         if (scan_authfile(f, user, our_name, remote,
637                           secret, &addrs, filename) < 0
638             || (secret[0] != 0 && (cryptpap || strcmp(passwd, secret) != 0)
639                 && strcmp(crypt(passwd, secret), secret) != 0)) {
640             syslog(LOG_WARNING, "PAP authentication failure for %s", user);
641             ret = UPAP_AUTHNAK;
642         }
643         fclose(f);
644     }
645
646     if (uselogin && ret == UPAP_AUTHACK) {
647         ret = login(user, passwd, msg, msglen);
648         if (ret == UPAP_AUTHNAK) {
649             syslog(LOG_WARNING, "PAP login failure for %s", user);
650         }
651     }
652
653     if (ret == UPAP_AUTHNAK) {
654         if (*msg == (char *) 0)
655             *msg = "Login incorrect";
656         *msglen = strlen(*msg);
657         /*
658          * Frustrate passwd stealer programs.
659          * Allow 10 tries, but start backing off after 3 (stolen from login).
660          * On 10'th, drop the connection.
661          */
662         if (attempts++ >= 10) {
663             syslog(LOG_WARNING, "%d LOGIN FAILURES ON %s, %s",
664                    attempts, devnam, user);
665             quit();
666         }
667         if (attempts > 3)
668             sleep((u_int) (attempts - 3) * 5);
669         if (addrs != NULL)
670             free_wordlist(addrs);
671
672     } else {
673         attempts = 0;                   /* Reset count */
674         if (*msg == (char *) 0)
675             *msg = "Login ok";
676         *msglen = strlen(*msg);
677         set_allowed_addrs(unit, addrs);
678     }
679
680     BZERO(passwd, sizeof(passwd));
681     BZERO(secret, sizeof(secret));
682
683     return ret;
684 }
685
686 /*
687  * This function is needed for PAM. However, it should not be called.
688  * If it is, return the error code.
689  */
690
691 #ifdef USE_PAM
692 static int pam_conv(int num_msg, const struct pam_message **msg,
693                     struct pam_response **resp, void *appdata_ptr)
694 {
695     return PAM_CONV_ERR;
696 }
697 #endif
698
699 /*
700  * login - Check the user name and password against the system
701  * password database, and login the user if OK.
702  *
703  * returns:
704  *      UPAP_AUTHNAK: Login failed.
705  *      UPAP_AUTHACK: Login succeeded.
706  * In either case, msg points to an appropriate message.
707  */
708
709 static int
710 login(user, passwd, msg, msglen)
711     char *user;
712     char *passwd;
713     char **msg;
714     int *msglen;
715 {
716     char *tty;
717
718 #ifdef USE_PAM
719     struct pam_conv pam_conversation;
720     pam_handle_t *pamh;
721     int pam_error;
722     char *pass;
723     char *dev;
724 /*
725  * Fill the pam_conversion structure
726  */
727     memset (&pam_conversation, '\0', sizeof (struct pam_conv));
728     pam_conversation.conv = &pam_conv;
729
730     pam_error = pam_start ("ppp", user, &pam_conversation, &pamh);
731     if (pam_error != PAM_SUCCESS) {
732         *msg = (char *) pam_strerror (pam_error);
733         return UPAP_AUTHNAK;
734     }
735 /*
736  * Define the fields for the credintial validation
737  */
738     (void) pam_set_item (pamh, PAM_AUTHTOK, passwd);
739     (void) pam_set_item (pamh, PAM_TTY,     devnam);
740 /*
741  * Validate the user
742  */
743     pam_error = pam_authenticate (pamh, PAM_SILENT);
744     if (pam_error == PAM_SUCCESS)
745         pam_error = pam_acct_mgmt (pamh, PAM_SILENT);
746
747     *msg = (char *) pam_strerror (pam_error);
748 /*
749  * Clean up the mess
750  */
751     (void) pam_end (pamh, pam_error);
752
753     if (pam_error != PAM_SUCCESS)
754         return UPAP_AUTHNAK;
755 /*
756  * Use the non-PAM methods directly
757  */
758 #else /* #ifdef USE_PAM */
759
760     struct passwd *pw;
761
762 #ifdef HAS_SHADOW
763     struct spwd *spwd;
764     struct spwd *getspnam();
765     extern int isexpired (struct passwd *, struct spwd *); /* in libshadow.a */
766 #endif
767
768     pw = getpwnam(user);
769     if (pw == NULL) {
770         return (UPAP_AUTHNAK);
771     }
772
773 #ifdef HAS_SHADOW
774     spwd = getspnam(user);
775     endspent();
776     if (spwd) {
777         /* check the age of the password entry */
778         if (isexpired(pw, spwd)) {
779             syslog(LOG_WARNING,"Expired password for %s",user);
780             return (UPAP_AUTHNAK);
781         }
782         pw->pw_passwd = spwd->sp_pwdp;
783     }
784 #endif
785
786     /*
787      * If no passwd, don't let them login.
788      */
789     if (pw->pw_passwd == NULL || *pw->pw_passwd == '\0'
790         || strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd) != 0)
791         return (UPAP_AUTHNAK);
792
793 #endif /* #ifdef USE_PAM */
794
795     syslog(LOG_INFO, "user %s logged in", user);
796
797     /*
798      * Write a wtmp entry for this user.
799      */
800     tty = devnam;
801     if (strncmp(tty, "/dev/", 5) == 0)
802         tty += 5;
803     logwtmp(tty, user, remote_name);            /* Add wtmp login entry */
804     logged_in = TRUE;
805
806     return (UPAP_AUTHACK);
807 }
808
809 /*
810  * logout - Logout the user.
811  */
812 static void
813 logout()
814 {
815     char *tty;
816
817     tty = devnam;
818     if (strncmp(tty, "/dev/", 5) == 0)
819         tty += 5;
820     logwtmp(tty, "", "");               /* Wipe out wtmp logout entry */
821     logged_in = FALSE;
822 }
823
824
825 /*
826  * null_login - Check if a username of "" and a password of "" are
827  * acceptable, and iff so, set the list of acceptable IP addresses
828  * and return 1.
829  */
830 static int
831 null_login(unit)
832     int unit;
833 {
834     char *filename;
835     FILE *f;
836     int i, ret;
837     struct wordlist *addrs;
838     char secret[MAXWORDLEN];
839
840     /*
841      * Open the file of pap secrets and scan for a suitable secret.
842      * We don't accept a wildcard client.
843      */
844     filename = _PATH_UPAPFILE;
845     addrs = NULL;
846     f = fopen(filename, "r");
847     if (f == NULL)
848         return 0;
849     check_access(f, filename);
850
851     i = scan_authfile(f, "", our_name, (u_int32_t)0, secret, &addrs, filename);
852     ret = i >= 0 && (i & NONWILD_CLIENT) != 0 && secret[0] == 0;
853     BZERO(secret, sizeof(secret));
854
855     if (ret)
856         set_allowed_addrs(unit, addrs);
857     else
858         free_wordlist(addrs);
859
860     fclose(f);
861     return ret;
862 }
863
864
865 /*
866  * get_pap_passwd - get a password for authenticating ourselves with
867  * our peer using PAP.  Returns 1 on success, 0 if no suitable password
868  * could be found.
869  */
870 static int
871 get_pap_passwd(passwd)
872     char *passwd;
873 {
874     char *filename;
875     FILE *f;
876     struct wordlist *addrs;
877     char secret[MAXWORDLEN];
878
879     filename = _PATH_UPAPFILE;
880     addrs = NULL;
881     f = fopen(filename, "r");
882     if (f == NULL)
883         return 0;
884     check_access(f, filename);
885     if (scan_authfile(f, user,
886                       remote_name[0]? remote_name: NULL,
887                       (u_int32_t)0, secret, NULL, filename) < 0)
888         return 0;
889     if (passwd != NULL) {
890         strncpy(passwd, secret, MAXSECRETLEN);
891         passwd[MAXSECRETLEN-1] = 0;
892     }
893     BZERO(secret, sizeof(secret));
894     return 1;
895 }
896
897
898 /*
899  * have_pap_secret - check whether we have a PAP file with any
900  * secrets that we could possibly use for authenticating the peer.
901  */
902 static int
903 have_pap_secret()
904 {
905     FILE *f;
906     int ret;
907     char *filename;
908     ipcp_options *ipwo = &ipcp_wantoptions[0];
909     u_int32_t remote;
910
911     filename = _PATH_UPAPFILE;
912     f = fopen(filename, "r");
913     if (f == NULL)
914         return 0;
915
916     remote = ipwo->accept_remote? 0: ipwo->hisaddr;
917     ret = scan_authfile(f, NULL, our_name, remote, NULL, NULL, filename);
918     fclose(f);
919     if (ret < 0)
920         return 0;
921
922     return 1;
923 }
924
925
926 /*
927  * have_chap_secret - check whether we have a CHAP file with a
928  * secret that we could possibly use for authenticating `client'
929  * on `server'.  Either can be the null string, meaning we don't
930  * know the identity yet.
931  */
932 static int
933 have_chap_secret(client, server, remote)
934     char *client;
935     char *server;
936     u_int32_t remote;
937 {
938     FILE *f;
939     int ret;
940     char *filename;
941
942     filename = _PATH_CHAPFILE;
943     f = fopen(filename, "r");
944     if (f == NULL)
945         return 0;
946
947     if (client[0] == 0)
948         client = NULL;
949     else if (server[0] == 0)
950         server = NULL;
951
952     ret = scan_authfile(f, client, server, remote, NULL, NULL, filename);
953     fclose(f);
954     if (ret < 0)
955         return 0;
956
957     return 1;
958 }
959
960
961 /*
962  * get_secret - open the CHAP secret file and return the secret
963  * for authenticating the given client on the given server.
964  * (We could be either client or server).
965  */
966 int
967 get_secret(unit, client, server, secret, secret_len, save_addrs)
968     int unit;
969     char *client;
970     char *server;
971     char *secret;
972     int *secret_len;
973     int save_addrs;
974 {
975     FILE *f;
976     int ret, len;
977     char *filename;
978     struct wordlist *addrs;
979     char secbuf[MAXWORDLEN];
980
981     filename = _PATH_CHAPFILE;
982     addrs = NULL;
983     secbuf[0] = 0;
984
985     f = fopen(filename, "r");
986     if (f == NULL) {
987         syslog(LOG_ERR, "Can't open chap secret file %s: %m", filename);
988         return 0;
989     }
990     check_access(f, filename);
991
992     ret = scan_authfile(f, client, server, (u_int32_t)0,
993                         secbuf, &addrs, filename);
994     fclose(f);
995     if (ret < 0)
996         return 0;
997
998     if (save_addrs)
999         set_allowed_addrs(unit, addrs);
1000
1001     len = strlen(secbuf);
1002     if (len > MAXSECRETLEN) {
1003         syslog(LOG_ERR, "Secret for %s on %s is too long", client, server);
1004         len = MAXSECRETLEN;
1005     }
1006     BCOPY(secbuf, secret, len);
1007     BZERO(secbuf, sizeof(secbuf));
1008     *secret_len = len;
1009
1010     return 1;
1011 }
1012
1013 /*
1014  * set_allowed_addrs() - set the list of allowed addresses.
1015  */
1016 static void
1017 set_allowed_addrs(unit, addrs)
1018     int unit;
1019     struct wordlist *addrs;
1020 {
1021     if (addresses[unit] != NULL)
1022         free_wordlist(addresses[unit]);
1023     addresses[unit] = addrs;
1024
1025     /*
1026      * If there's only one authorized address we might as well
1027      * ask our peer for that one right away
1028      */
1029     if (addrs != NULL && addrs->next == NULL) {
1030         char *p = addrs->word;
1031         struct ipcp_options *wo = &ipcp_wantoptions[unit];
1032         u_int32_t a;
1033         struct hostent *hp;
1034
1035         if (wo->hisaddr == 0 && *p != '!' && *p != '-'
1036             && strchr(p, '/') == NULL) {
1037             hp = gethostbyname(p);
1038             if (hp != NULL && hp->h_addrtype == AF_INET)
1039                 a = *(u_int32_t *)hp->h_addr;
1040             else
1041                 a = inet_addr(p);
1042             if (a != (u_int32_t) -1)
1043                 wo->hisaddr = a;
1044         }
1045     }
1046 }
1047
1048 /*
1049  * auth_ip_addr - check whether the peer is authorized to use
1050  * a given IP address.  Returns 1 if authorized, 0 otherwise.
1051  */
1052 int
1053 auth_ip_addr(unit, addr)
1054     int unit;
1055     u_int32_t addr;
1056 {
1057     return ip_addr_check(addr, addresses[unit]);
1058 }
1059
1060 static int
1061 ip_addr_check(addr, addrs)
1062     u_int32_t addr;
1063     struct wordlist *addrs;
1064 {
1065     u_int32_t a, mask, ah;
1066     int accept;
1067     char *ptr_word, *ptr_mask;
1068     struct hostent *hp;
1069     struct netent *np;
1070
1071     /* don't allow loopback or multicast address */
1072     if (bad_ip_adrs(addr))
1073         return 0;
1074
1075     if (addrs == NULL)
1076         return !auth_required;          /* no addresses authorized */
1077
1078     for (; addrs != NULL; addrs = addrs->next) {
1079         /* "-" means no addresses authorized, "*" means any address allowed */
1080         ptr_word = addrs->word;
1081         if (strcmp(ptr_word, "-") == 0)
1082             break;
1083         if (strcmp(ptr_word, "*") == 0)
1084             return 1;
1085
1086         accept = 1;
1087         if (*ptr_word == '!') {
1088             accept = 0;
1089             ++ptr_word;
1090         }
1091
1092         mask = ~ (u_int32_t) 0;
1093         ptr_mask = strchr (ptr_word, '/');
1094         if (ptr_mask != NULL) {
1095             int bit_count;
1096
1097             bit_count = (int) strtol (ptr_mask+1, (char **) 0, 10);
1098             if (bit_count <= 0 || bit_count > 32) {
1099                 syslog (LOG_WARNING,
1100                         "invalid address length %s in auth. address list",
1101                         ptr_mask);
1102                 continue;
1103             }
1104             *ptr_mask = '\0';
1105             mask <<= 32 - bit_count;
1106         }
1107
1108         hp = gethostbyname(ptr_word);
1109         if (hp != NULL && hp->h_addrtype == AF_INET) {
1110             a = *(u_int32_t *)hp->h_addr;
1111         } else {
1112             np = getnetbyname (ptr_word);
1113             if (np != NULL && np->n_addrtype == AF_INET) {
1114                 a = htonl (*(u_int32_t *)np->n_net);
1115                 if (ptr_mask == NULL) {
1116                     /* calculate appropriate mask for net */
1117                     ah = ntohl(a);
1118                     if (IN_CLASSA(ah))
1119                         mask = IN_CLASSA_NET;
1120                     else if (IN_CLASSB(ah))
1121                         mask = IN_CLASSB_NET;
1122                     else if (IN_CLASSC(ah))
1123                         mask = IN_CLASSC_NET;
1124                 }
1125             } else {
1126                 a = inet_addr (ptr_word);
1127             }
1128         }
1129
1130         if (ptr_mask != NULL)
1131             *ptr_mask = '/';
1132
1133         if (a == (u_int32_t)-1L)
1134             syslog (LOG_WARNING,
1135                     "unknown host %s in auth. address list",
1136                     addrs->word);
1137         else
1138             /* Here a and addr are in network byte order,
1139                and mask is in host order. */
1140             if (((addr ^ a) & htonl(mask)) == 0)
1141                 return accept;
1142     }
1143     return 0;                   /* not in list => can't have it */
1144 }
1145
1146 /*
1147  * bad_ip_adrs - return 1 if the IP address is one we don't want
1148  * to use, such as an address in the loopback net or a multicast address.
1149  * addr is in network byte order.
1150  */
1151 int
1152 bad_ip_adrs(addr)
1153     u_int32_t addr;
1154 {
1155     addr = ntohl(addr);
1156     return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
1157         || IN_MULTICAST(addr) || IN_BADCLASS(addr);
1158 }
1159
1160 /*
1161  * check_access - complain if a secret file has too-liberal permissions.
1162  */
1163 void
1164 check_access(f, filename)
1165     FILE *f;
1166     char *filename;
1167 {
1168     struct stat sbuf;
1169
1170     if (fstat(fileno(f), &sbuf) < 0) {
1171         syslog(LOG_WARNING, "cannot stat secret file %s: %m", filename);
1172     } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1173         syslog(LOG_WARNING, "Warning - secret file %s has world and/or group access", filename);
1174     }
1175 }
1176
1177
1178 /*
1179  * scan_authfile - Scan an authorization file for a secret suitable
1180  * for authenticating `client' on `server'.  The return value is -1
1181  * if no secret is found, otherwise >= 0.  The return value has
1182  * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
1183  * NONWILD_SERVER set if the secret didn't have "*" for the server.
1184  * Any following words on the line (i.e. address authorization
1185  * info) are placed in a wordlist and returned in *addrs.  
1186  */
1187 static int
1188 scan_authfile(f, client, server, ipaddr, secret, addrs, filename)
1189     FILE *f;
1190     char *client;
1191     char *server;
1192     u_int32_t ipaddr;
1193     char *secret;
1194     struct wordlist **addrs;
1195     char *filename;
1196 {
1197     int newline, xxx;
1198     int got_flag, best_flag;
1199     FILE *sf;
1200     struct wordlist *ap, *addr_list, *alist, *alast;
1201     char word[MAXWORDLEN];
1202     char atfile[MAXWORDLEN];
1203     char lsecret[MAXWORDLEN];
1204
1205     if (addrs != NULL)
1206         *addrs = NULL;
1207     addr_list = NULL;
1208     if (!getword(f, word, &newline, filename))
1209         return -1;              /* file is empty??? */
1210     newline = 1;
1211     best_flag = -1;
1212     for (;;) {
1213         /*
1214          * Skip until we find a word at the start of a line.
1215          */
1216         while (!newline && getword(f, word, &newline, filename))
1217             ;
1218         if (!newline)
1219             break;              /* got to end of file */
1220
1221         /*
1222          * Got a client - check if it's a match or a wildcard.
1223          */
1224         got_flag = 0;
1225         if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
1226             newline = 0;
1227             continue;
1228         }
1229         if (!ISWILD(word))
1230             got_flag = NONWILD_CLIENT;
1231
1232         /*
1233          * Now get a server and check if it matches.
1234          */
1235         if (!getword(f, word, &newline, filename))
1236             break;
1237         if (newline)
1238             continue;
1239         if (server != NULL && strcmp(word, server) != 0 && !ISWILD(word))
1240             continue;
1241         if (!ISWILD(word))
1242             got_flag |= NONWILD_SERVER;
1243
1244         /*
1245          * Got some sort of a match - see if it's better than what
1246          * we have already.
1247          */
1248         if (got_flag <= best_flag)
1249             continue;
1250
1251         /*
1252          * Get the secret.
1253          */
1254         if (!getword(f, word, &newline, filename))
1255             break;
1256         if (newline)
1257             continue;
1258
1259         /*
1260          * Special syntax: @filename means read secret from file.
1261          */
1262         if (word[0] == '@') {
1263             strcpy(atfile, word+1);
1264             if ((sf = fopen(atfile, "r")) == NULL) {
1265                 syslog(LOG_WARNING, "can't open indirect secret file %s",
1266                        atfile);
1267                 continue;
1268             }
1269             check_access(sf, atfile);
1270             if (!getword(sf, word, &xxx, atfile)) {
1271                 syslog(LOG_WARNING, "no secret in indirect secret file %s",
1272                        atfile);
1273                 fclose(sf);
1274                 continue;
1275             }
1276             fclose(sf);
1277         }
1278         if (secret != NULL)
1279             strcpy(lsecret, word);
1280
1281         /*
1282          * Now read address authorization info and make a wordlist.
1283          */
1284         alist = alast = NULL;
1285         for (;;) {
1286             if (!getword(f, word, &newline, filename) || newline)
1287                 break;
1288             ap = (struct wordlist *) malloc(sizeof(struct wordlist)
1289                                             + strlen(word));
1290             if (ap == NULL)
1291                 novm("authorized addresses");
1292             ap->next = NULL;
1293             strcpy(ap->word, word);
1294             if (alist == NULL)
1295                 alist = ap;
1296             else
1297                 alast->next = ap;
1298             alast = ap;
1299         }
1300
1301         /*
1302          * Check if the given IP address is allowed by the wordlist.
1303          */
1304         if (ipaddr != 0 && !ip_addr_check(ipaddr, alist)) {
1305             free_wordlist(alist);
1306             continue;
1307         }
1308
1309         /*
1310          * This is the best so far; remember it.
1311          */
1312         best_flag = got_flag;
1313         if (addr_list)
1314             free_wordlist(addr_list);
1315         addr_list = alist;
1316         if (secret != NULL)
1317             strcpy(secret, lsecret);
1318
1319         if (!newline)
1320             break;
1321     }
1322
1323     if (addrs != NULL)
1324         *addrs = addr_list;
1325     else if (addr_list != NULL)
1326         free_wordlist(addr_list);
1327
1328     return best_flag;
1329 }
1330
1331 /*
1332  * free_wordlist - release memory allocated for a wordlist.
1333  */
1334 static void
1335 free_wordlist(wp)
1336     struct wordlist *wp;
1337 {
1338     struct wordlist *next;
1339
1340     while (wp != NULL) {
1341         next = wp->next;
1342         free(wp);
1343         wp = next;
1344     }
1345 }
1346
1347 /*
1348  * auth_script - execute a script with arguments
1349  * interface-name peer-name real-user tty speed
1350  */
1351 static void
1352 auth_script(script)
1353     char *script;
1354 {
1355     char strspeed[32];
1356     struct passwd *pw;
1357     char struid[32];
1358     char *user_name;
1359     char *argv[8];
1360
1361     if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
1362         user_name = pw->pw_name;
1363     else {
1364         sprintf(struid, "%d", getuid());
1365         user_name = struid;
1366     }
1367     sprintf(strspeed, "%d", baud_rate);
1368
1369     argv[0] = script;
1370     argv[1] = ifname;
1371     argv[2] = peer_authname;
1372     argv[3] = user_name;
1373     argv[4] = devnam;
1374     argv[5] = strspeed;
1375     argv[6] = NULL;
1376
1377     run_program(script, argv, 0);
1378 }