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