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