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