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