]> git.ozlabs.org Git - ppp.git/blob - pppd/auth.c
include optional callback support
[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.28 1996/10/08 04:35:02 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 #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 #ifdef CBCP_SUPPORT
82 #include "cbcp.h"
83 #endif
84 #include "pathnames.h"
85
86 /* Used for storing a sequence of words.  Usually malloced. */
87 struct wordlist {
88     struct wordlist     *next;
89     char                word[1];
90 };
91
92 /* Bits in scan_authfile return value */
93 #define NONWILD_SERVER  1
94 #define NONWILD_CLIENT  2
95
96 #define ISWILD(word)    (word[0] == '*' && word[1] == 0)
97
98 #define FALSE   0
99 #define TRUE    1
100
101 /* The name by which the peer authenticated itself to us. */
102 char peer_authname[MAXNAMELEN];
103
104 /* Records which authentication operations haven't completed yet. */
105 static int auth_pending[NUM_PPP];
106
107 /* Set if we have successfully called login() */
108 static int logged_in;
109
110 /* Set if we have run the /etc/ppp/auth-up script. */
111 static int did_authup;
112
113 /* List of addresses which the peer may use. */
114 static struct wordlist *addresses[NUM_PPP];
115
116 /* Number of network protocols which we have opened. */
117 static int num_np_open;
118
119 /* Number of network protocols which have come up. */
120 static int num_np_up;
121
122 /* Set if we got the contents of passwd[] from the pap-secrets file. */
123 static int passwd_from_file;
124
125 /* Bits in auth_pending[] */
126 #define PAP_WITHPEER    1
127 #define PAP_PEER        2
128 #define CHAP_WITHPEER   4
129 #define CHAP_PEER       8
130
131 /* Prototypes for procedures local to this file. */
132
133 static void network_phase __P((int));
134 static void check_idle __P((caddr_t));
135 static int  login __P((char *, char *, char **, int *));
136 static void logout __P((void));
137 static int  null_login __P((int));
138 static int  get_pap_passwd __P((char *));
139 static int  have_pap_secret __P((void));
140 static int  have_chap_secret __P((char *, char *, u_int32_t));
141 static int  ip_addr_check __P((u_int32_t, struct wordlist *));
142 static int  scan_authfile __P((FILE *, char *, char *, u_int32_t, char *,
143                                struct wordlist **, char *));
144 static void free_wordlist __P((struct wordlist *));
145 static void auth_script __P((char *));
146 #ifdef CBCP_SUPPORT
147 static void callback_phase __P((int));
148 #endif
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         logout();
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     phase = PHASE_TERMINATE;
201 }
202
203 /*
204  * The link is established.
205  * Proceed to the Dead, Authenticate or Network phase as appropriate.
206  */
207 void
208 link_established(unit)
209     int unit;
210 {
211     int auth;
212     lcp_options *wo = &lcp_wantoptions[unit];
213     lcp_options *go = &lcp_gotoptions[unit];
214     lcp_options *ho = &lcp_hisoptions[unit];
215     int i;
216     struct protent *protp;
217
218     /*
219      * Tell higher-level protocols that LCP is up.
220      */
221     for (i = 0; (protp = protocols[i]) != NULL; ++i)
222         if (protp->protocol != PPP_LCP && protp->enabled_flag
223             && protp->lowerup != NULL)
224             (*protp->lowerup)(unit);
225
226     if (auth_required && !(go->neg_chap || go->neg_upap)) {
227         /*
228          * We wanted the peer to authenticate itself, and it refused:
229          * treat it as though it authenticated with PAP using a username
230          * of "" and a password of "".  If that's not OK, boot it out.
231          */
232         if (!wo->neg_upap || !null_login(unit)) {
233             syslog(LOG_WARNING, "peer refused to authenticate");
234             lcp_close(unit, "peer refused to authenticate");
235             return;
236         }
237     }
238
239     phase = PHASE_AUTHENTICATE;
240     auth = 0;
241     if (go->neg_chap) {
242         ChapAuthPeer(unit, our_name, go->chap_mdtype);
243         auth |= CHAP_PEER;
244     } else if (go->neg_upap) {
245         upap_authpeer(unit);
246         auth |= PAP_PEER;
247     }
248     if (ho->neg_chap) {
249         ChapAuthWithPeer(unit, user, ho->chap_mdtype);
250         auth |= CHAP_WITHPEER;
251     } else if (ho->neg_upap) {
252         if (passwd[0] == 0) {
253             passwd_from_file = 1;
254             if (!get_pap_passwd(passwd))
255                 syslog(LOG_ERR, "No secret found for PAP login");
256         }
257         upap_authwithpeer(unit, user, passwd);
258         auth |= PAP_WITHPEER;
259     }
260     auth_pending[unit] = auth;
261
262     if (!auth)
263         network_phase(unit);
264 }
265
266 /*
267  * Proceed to the network phase.
268  */
269 static void
270 network_phase(unit)
271     int unit;
272 {
273     int i;
274     struct protent *protp;
275     lcp_options *go = &lcp_gotoptions[unit];
276
277     /*
278      * If the peer had to authenticate, run the auth-up script now.
279      */
280     if ((go->neg_chap || go->neg_upap) && !did_authup) {
281         auth_script(_PATH_AUTHUP);
282         did_authup = 1;
283     }
284
285 #ifdef CBCP_SUPPORT
286     /*
287      * If we negotiated callback, do it now.
288      */
289     if (go->neg_cbcp) {
290         phase = PHASE_CALLBACK;
291         (*cbcp_protent.open)(unit);
292         return;
293     }
294 #endif
295
296     phase = PHASE_NETWORK;
297 #if 0
298     if (!demand)
299         set_filters(&pass_filter, &active_filter);
300 #endif
301     for (i = 0; (protp = protocols[i]) != NULL; ++i)
302         if (protp->protocol < 0xC000 && protp->enabled_flag
303             && protp->open != NULL) {
304             (*protp->open)(unit);
305             if (protp->protocol != PPP_CCP)
306                 ++num_np_open;
307         }
308 }
309
310 /*
311  * The peer has failed to authenticate himself using `protocol'.
312  */
313 void
314 auth_peer_fail(unit, protocol)
315     int unit, protocol;
316 {
317     /*
318      * Authentication failure: take the link down
319      */
320     lcp_close(unit, "Authentication failed");
321 }
322
323 /*
324  * The peer has been successfully authenticated using `protocol'.
325  */
326 void
327 auth_peer_success(unit, protocol, name, namelen)
328     int unit, protocol;
329     char *name;
330     int namelen;
331 {
332     int bit;
333
334     switch (protocol) {
335     case PPP_CHAP:
336         bit = CHAP_PEER;
337         break;
338     case PPP_PAP:
339         bit = PAP_PEER;
340         break;
341     default:
342         syslog(LOG_WARNING, "auth_peer_success: unknown protocol %x",
343                protocol);
344         return;
345     }
346
347     /*
348      * Save the authenticated name of the peer for later.
349      */
350     if (namelen > sizeof(peer_authname) - 1)
351         namelen = sizeof(peer_authname) - 1;
352     BCOPY(name, peer_authname, namelen);
353     peer_authname[namelen] = 0;
354
355     /*
356      * If there is no more authentication still to be done,
357      * proceed to the network (or callback) phase.
358      */
359     if ((auth_pending[unit] &= ~bit) == 0)
360         network_phase(unit);
361 }
362
363 /*
364  * We have failed to authenticate ourselves to the peer using `protocol'.
365  */
366 void
367 auth_withpeer_fail(unit, protocol)
368     int unit, protocol;
369 {
370     if (passwd_from_file)
371         BZERO(passwd, MAXSECRETLEN);
372     /*
373      * We've failed to authenticate ourselves to our peer.
374      * He'll probably take the link down, and there's not much
375      * we can do except wait for that.
376      */
377 }
378
379 /*
380  * We have successfully authenticated ourselves with the peer using `protocol'.
381  */
382 void
383 auth_withpeer_success(unit, protocol)
384     int unit, protocol;
385 {
386     int bit;
387
388     switch (protocol) {
389     case PPP_CHAP:
390         bit = CHAP_WITHPEER;
391         break;
392     case PPP_PAP:
393         if (passwd_from_file)
394             BZERO(passwd, MAXSECRETLEN);
395         bit = PAP_WITHPEER;
396         break;
397     default:
398         syslog(LOG_WARNING, "auth_peer_success: unknown protocol %x",
399                protocol);
400         bit = 0;
401     }
402
403     /*
404      * If there is no more authentication still being done,
405      * proceed to the network (or callback) phase.
406      */
407     if ((auth_pending[unit] &= ~bit) == 0)
408         network_phase(unit);
409 }
410
411
412 /*
413  * np_up - a network protocol has come up.
414  */
415 void
416 np_up(unit, proto)
417     int unit, proto;
418 {
419     if (num_np_up == 0 && idle_time_limit > 0) {
420         TIMEOUT(check_idle, NULL, idle_time_limit);
421     }
422     ++num_np_up;
423 }
424
425 /*
426  * np_down - a network protocol has gone down.
427  */
428 void
429 np_down(unit, proto)
430     int unit, proto;
431 {
432     if (--num_np_up == 0 && idle_time_limit > 0) {
433         UNTIMEOUT(check_idle, NULL);
434     }
435 }
436
437 /*
438  * np_finished - a network protocol has finished using the link.
439  */
440 void
441 np_finished(unit, proto)
442     int unit, proto;
443 {
444     if (--num_np_open <= 0) {
445         /* no further use for the link: shut up shop. */
446         lcp_close(0, "No network protocols running");
447     }
448 }
449
450 /*
451  * check_idle - check whether the link has been idle for long
452  * enough that we can shut it down.
453  */
454 static void
455 check_idle(arg)
456     caddr_t arg;
457 {
458     struct ppp_idle idle;
459     time_t itime;
460
461     if (!get_idle_time(0, &idle))
462         return;
463     itime = MIN(idle.xmit_idle, idle.recv_idle);
464     if (itime >= idle_time_limit) {
465         /* link is idle: shut it down. */
466         syslog(LOG_INFO, "Terminating connection due to lack of activity.");
467         need_holdoff = 0;
468         lcp_close(0, "Link inactive");
469     } else {
470         TIMEOUT(check_idle, NULL, idle_time_limit - itime);
471     }
472 }
473
474 /*
475  * auth_check_options - called to check authentication options.
476  */
477 void
478 auth_check_options()
479 {
480     lcp_options *wo = &lcp_wantoptions[0];
481     int can_auth;
482     ipcp_options *ipwo = &ipcp_wantoptions[0];
483     u_int32_t remote;
484
485     /* Check that we are running as root. */
486     if (geteuid() != 0) {
487         option_error("must be run with root privileges");
488         exit(1);
489     }
490
491     /* Default our_name to hostname, and user to our_name */
492     if (our_name[0] == 0 || usehostname)
493         strcpy(our_name, hostname);
494     if (user[0] == 0)
495         strcpy(user, our_name);
496
497     /* If authentication is required, ask peer for CHAP or PAP. */
498     if (auth_required && !wo->neg_chap && !wo->neg_upap) {
499         wo->neg_chap = 1;
500         wo->neg_upap = 1;
501     }
502
503     /*
504      * Check whether we have appropriate secrets to use
505      * to authenticate the peer.
506      */
507     can_auth = wo->neg_upap && (uselogin || have_pap_secret());
508     if (!can_auth && wo->neg_chap) {
509         remote = ipwo->accept_remote? 0: ipwo->hisaddr;
510         can_auth = have_chap_secret(remote_name, our_name, remote);
511     }
512
513     if (auth_required && !can_auth) {
514         option_error("peer authentication required but no suitable secret(s) found\n");
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     if ((pw = getpwnam(user)) == NULL) {
819         return (UPAP_AUTHNAK);
820     }
821
822 #ifdef HAS_SHADOW
823     if ((spwd = getspnam(user)) == NULL) {
824         pw->pw_passwd = "";
825     } else {
826         pw->pw_passwd = spwd->sp_pwdp;
827     }
828 #endif
829
830     /*
831      * XXX If no passwd, let them login without one.
832      */
833     if (pw->pw_passwd == '\0') {
834         return (UPAP_AUTHACK);
835     }
836
837 #ifdef HAS_SHADOW
838     if (pw->pw_passwd) {
839         if (pw->pw_passwd[0] == '@') {
840             if (pw_auth (pw->pw_passwd+1, pw->pw_name, PW_PPP, NULL)) {
841                 return (UPAP_AUTHNAK);
842             }
843         } else {
844             epasswd = pw_encrypt(passwd, pw->pw_passwd);
845             if (strcmp(epasswd, pw->pw_passwd)) {
846                 return (UPAP_AUTHNAK);
847             }
848         }
849         /* check the age of the password entry */
850         if (spwd && (isexpired (pw, spwd) != 0)) {
851             return (UPAP_AUTHNAK);
852         }
853     }
854 #else
855     epasswd = crypt(passwd, pw->pw_passwd);
856     if (strcmp(epasswd, pw->pw_passwd)) {
857         return (UPAP_AUTHNAK);
858     }
859 #endif
860 #endif /* #ifdef USE_PAM */
861
862     syslog(LOG_INFO, "user %s logged in", user);
863
864     /*
865      * Write a wtmp entry for this user.
866      */
867     tty = devnam;
868     if (strncmp(tty, "/dev/", 5) == 0)
869         tty += 5;
870     logwtmp(tty, user, remote_name);            /* Add wtmp login entry */
871     logged_in = TRUE;
872
873     return (UPAP_AUTHACK);
874 }
875
876 /*
877  * logout - Logout the user.
878  */
879 static void
880 logout()
881 {
882     char *tty;
883
884     tty = devnam;
885     if (strncmp(tty, "/dev/", 5) == 0)
886         tty += 5;
887     logwtmp(tty, "", "");               /* Wipe out wtmp logout entry */
888     logged_in = FALSE;
889 }
890
891
892 /*
893  * null_login - Check if a username of "" and a password of "" are
894  * acceptable, and iff so, set the list of acceptable IP addresses
895  * and return 1.
896  */
897 static int
898 null_login(unit)
899     int unit;
900 {
901     char *filename;
902     FILE *f;
903     int i, ret;
904     struct wordlist *addrs;
905     char secret[MAXWORDLEN];
906
907     /*
908      * Open the file of pap secrets and scan for a suitable secret.
909      * We don't accept a wildcard client.
910      */
911     filename = _PATH_UPAPFILE;
912     addrs = NULL;
913     f = fopen(filename, "r");
914     if (f == NULL)
915         return 0;
916     check_access(f, filename);
917
918     i = scan_authfile(f, "", our_name, (u_int32_t)0, secret, &addrs, filename);
919     ret = i >= 0 && (i & NONWILD_CLIENT) != 0 && secret[0] == 0;
920     BZERO(secret, sizeof(secret));
921
922     if (ret) {
923         if (addresses[unit] != NULL)
924             free_wordlist(addresses[unit]);
925         addresses[unit] = addrs;
926     }
927
928     fclose(f);
929     return ret;
930 }
931
932
933 /*
934  * get_pap_passwd - get a password for authenticating ourselves with
935  * our peer using PAP.  Returns 1 on success, 0 if no suitable password
936  * could be found.
937  */
938 static int
939 get_pap_passwd(passwd)
940     char *passwd;
941 {
942     char *filename;
943     FILE *f;
944     struct wordlist *addrs;
945     char secret[MAXWORDLEN];
946
947     filename = _PATH_UPAPFILE;
948     addrs = NULL;
949     f = fopen(filename, "r");
950     if (f == NULL)
951         return 0;
952     check_access(f, filename);
953     if (scan_authfile(f, user,
954                       remote_name[0]? remote_name: NULL,
955                       (u_int32_t)0, secret, NULL, filename) < 0)
956         return 0;
957     if (passwd != NULL) {
958         strncpy(passwd, secret, MAXSECRETLEN);
959         passwd[MAXSECRETLEN-1] = 0;
960     }
961     BZERO(secret, sizeof(secret));
962     return 1;
963 }
964
965
966 /*
967  * have_pap_secret - check whether we have a PAP file with any
968  * secrets that we could possibly use for authenticating the peer.
969  */
970 static int
971 have_pap_secret()
972 {
973     FILE *f;
974     int ret;
975     char *filename;
976     ipcp_options *ipwo = &ipcp_wantoptions[0];
977     u_int32_t remote;
978
979     filename = _PATH_UPAPFILE;
980     f = fopen(filename, "r");
981     if (f == NULL)
982         return 0;
983
984     remote = ipwo->accept_remote? 0: ipwo->hisaddr;
985     ret = scan_authfile(f, NULL, our_name, remote, NULL, NULL, filename);
986     fclose(f);
987     if (ret < 0)
988         return 0;
989
990     return 1;
991 }
992
993
994 /*
995  * have_chap_secret - check whether we have a CHAP file with a
996  * secret that we could possibly use for authenticating `client'
997  * on `server'.  Either can be the null string, meaning we don't
998  * know the identity yet.
999  */
1000 static int
1001 have_chap_secret(client, server, remote)
1002     char *client;
1003     char *server;
1004     u_int32_t remote;
1005 {
1006     FILE *f;
1007     int ret;
1008     char *filename;
1009
1010     filename = _PATH_CHAPFILE;
1011     f = fopen(filename, "r");
1012     if (f == NULL)
1013         return 0;
1014
1015     if (client[0] == 0)
1016         client = NULL;
1017     else if (server[0] == 0)
1018         server = NULL;
1019
1020     ret = scan_authfile(f, client, server, remote, NULL, NULL, filename);
1021     fclose(f);
1022     if (ret < 0)
1023         return 0;
1024
1025     return 1;
1026 }
1027
1028
1029 /*
1030  * get_secret - open the CHAP secret file and return the secret
1031  * for authenticating the given client on the given server.
1032  * (We could be either client or server).
1033  */
1034 int
1035 get_secret(unit, client, server, secret, secret_len, save_addrs)
1036     int unit;
1037     char *client;
1038     char *server;
1039     char *secret;
1040     int *secret_len;
1041     int save_addrs;
1042 {
1043     FILE *f;
1044     int ret, len;
1045     char *filename;
1046     struct wordlist *addrs;
1047     char secbuf[MAXWORDLEN];
1048
1049     filename = _PATH_CHAPFILE;
1050     addrs = NULL;
1051     secbuf[0] = 0;
1052
1053     f = fopen(filename, "r");
1054     if (f == NULL) {
1055         syslog(LOG_ERR, "Can't open chap secret file %s: %m", filename);
1056         return 0;
1057     }
1058     check_access(f, filename);
1059
1060     ret = scan_authfile(f, client, server, (u_int32_t)0,
1061                         secbuf, &addrs, filename);
1062     fclose(f);
1063     if (ret < 0)
1064         return 0;
1065
1066     if (save_addrs) {
1067         if (addresses[unit] != NULL)
1068             free_wordlist(addresses[unit]);
1069         addresses[unit] = addrs;
1070     }
1071
1072     len = strlen(secbuf);
1073     if (len > MAXSECRETLEN) {
1074         syslog(LOG_ERR, "Secret for %s on %s is too long", client, server);
1075         len = MAXSECRETLEN;
1076     }
1077     BCOPY(secbuf, secret, len);
1078     BZERO(secbuf, sizeof(secbuf));
1079     *secret_len = len;
1080
1081     return 1;
1082 }
1083
1084 /*
1085  * auth_ip_addr - check whether the peer is authorized to use
1086  * a given IP address.  Returns 1 if authorized, 0 otherwise.
1087  */
1088 int
1089 auth_ip_addr(unit, addr)
1090     int unit;
1091     u_int32_t addr;
1092 {
1093     return ip_addr_check(addr, addresses[unit]);
1094 }
1095
1096 static int
1097 ip_addr_check(addr, addrs)
1098     u_int32_t addr;
1099     struct wordlist *addrs;
1100 {
1101     u_int32_t a, mask, ah;
1102     int accept;
1103     char *ptr_word, *ptr_mask;
1104     struct hostent *hp;
1105     struct netent *np;
1106
1107     /* don't allow loopback or multicast address */
1108     if (bad_ip_adrs(addr))
1109         return 0;
1110
1111     if (addrs == NULL)
1112         return 1;               /* no restriction */
1113
1114     for (; addrs != NULL; addrs = addrs->next) {
1115         /* "-" means no addresses authorized */
1116         ptr_word = addrs->word;
1117         if (strcmp(ptr_word, "-") == 0)
1118             break;
1119
1120         accept = 1;
1121         if (*ptr_word == '!') {
1122             accept = 0;
1123             ++ptr_word;
1124         }
1125
1126         mask = ~ (u_int32_t) 0;
1127         ptr_mask = strchr (ptr_word, '/');
1128         if (ptr_mask != NULL) {
1129             int bit_count;
1130
1131             bit_count = (int) strtol (ptr_mask+1, (char **) 0, 10);
1132             if (bit_count <= 0 || bit_count > 32) {
1133                 syslog (LOG_WARNING,
1134                         "invalid address length %s in auth. address list",
1135                         ptr_mask);
1136                 continue;
1137             }
1138             *ptr_mask = '\0';
1139             mask <<= 32 - bit_count;
1140         }
1141
1142         hp = gethostbyname(ptr_word);
1143         if (hp != NULL && hp->h_addrtype == AF_INET) {
1144             a    = *(u_int32_t *)hp->h_addr;
1145             mask = ~ (u_int32_t) 0;     /* are we sure we want this? */
1146         } else {
1147             np = getnetbyname (ptr_word);
1148             if (np != NULL && np->n_addrtype == AF_INET)
1149                 a = htonl (*(u_int32_t *)np->n_net);
1150             else
1151                 a = inet_addr (ptr_word);
1152             if (ptr_mask == NULL) {
1153                 /* calculate appropriate mask for net */
1154                 ah = ntohl(a);
1155                 if (IN_CLASSA(ah))
1156                     mask = IN_CLASSA_NET;
1157                 else if (IN_CLASSB(ah))
1158                     mask = IN_CLASSB_NET;
1159                 else if (IN_CLASSC(ah))
1160                     mask = IN_CLASSC_NET;
1161             }
1162         }
1163
1164         if (ptr_mask != NULL)
1165             *ptr_mask = '/';
1166
1167         if (a == -1L)
1168             syslog (LOG_WARNING,
1169                     "unknown host %s in auth. address list",
1170                     addrs->word);
1171         else
1172             if (((addr ^ a) & htonl(mask)) == 0)
1173                 return accept;
1174     }
1175     return 0;                   /* not in list => can't have it */
1176 }
1177
1178 /*
1179  * bad_ip_adrs - return 1 if the IP address is one we don't want
1180  * to use, such as an address in the loopback net or a multicast address.
1181  * addr is in network byte order.
1182  */
1183 int
1184 bad_ip_adrs(addr)
1185     u_int32_t addr;
1186 {
1187     addr = ntohl(addr);
1188     return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
1189         || IN_MULTICAST(addr) || IN_BADCLASS(addr);
1190 }
1191
1192 /*
1193  * check_access - complain if a secret file has too-liberal permissions.
1194  */
1195 void
1196 check_access(f, filename)
1197     FILE *f;
1198     char *filename;
1199 {
1200     struct stat sbuf;
1201
1202     if (fstat(fileno(f), &sbuf) < 0) {
1203         syslog(LOG_WARNING, "cannot stat secret file %s: %m", filename);
1204     } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1205         syslog(LOG_WARNING, "Warning - secret file %s has world and/or group access", filename);
1206     }
1207 }
1208
1209
1210 /*
1211  * scan_authfile - Scan an authorization file for a secret suitable
1212  * for authenticating `client' on `server'.  The return value is -1
1213  * if no secret is found, otherwise >= 0.  The return value has
1214  * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
1215  * NONWILD_SERVER set if the secret didn't have "*" for the server.
1216  * Any following words on the line (i.e. address authorization
1217  * info) are placed in a wordlist and returned in *addrs.  
1218  */
1219 static int
1220 scan_authfile(f, client, server, ipaddr, secret, addrs, filename)
1221     FILE *f;
1222     char *client;
1223     char *server;
1224     u_int32_t ipaddr;
1225     char *secret;
1226     struct wordlist **addrs;
1227     char *filename;
1228 {
1229     int newline, xxx;
1230     int got_flag, best_flag;
1231     FILE *sf;
1232     struct wordlist *ap, *addr_list, *alist, *alast;
1233     char word[MAXWORDLEN];
1234     char atfile[MAXWORDLEN];
1235     char lsecret[MAXWORDLEN];
1236
1237     if (addrs != NULL)
1238         *addrs = NULL;
1239     addr_list = NULL;
1240     if (!getword(f, word, &newline, filename))
1241         return -1;              /* file is empty??? */
1242     newline = 1;
1243     best_flag = -1;
1244     for (;;) {
1245         /*
1246          * Skip until we find a word at the start of a line.
1247          */
1248         while (!newline && getword(f, word, &newline, filename))
1249             ;
1250         if (!newline)
1251             break;              /* got to end of file */
1252
1253         /*
1254          * Got a client - check if it's a match or a wildcard.
1255          */
1256         got_flag = 0;
1257         if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
1258             newline = 0;
1259             continue;
1260         }
1261         if (!ISWILD(word))
1262             got_flag = NONWILD_CLIENT;
1263
1264         /*
1265          * Now get a server and check if it matches.
1266          */
1267         if (!getword(f, word, &newline, filename))
1268             break;
1269         if (newline)
1270             continue;
1271         if (server != NULL && strcmp(word, server) != 0 && !ISWILD(word))
1272             continue;
1273         if (!ISWILD(word))
1274             got_flag |= NONWILD_SERVER;
1275
1276         /*
1277          * Got some sort of a match - see if it's better than what
1278          * we have already.
1279          */
1280         if (got_flag <= best_flag)
1281             continue;
1282
1283         /*
1284          * Get the secret.
1285          */
1286         if (!getword(f, word, &newline, filename))
1287             break;
1288         if (newline)
1289             continue;
1290
1291         /*
1292          * Special syntax: @filename means read secret from file.
1293          */
1294         if (word[0] == '@') {
1295             strcpy(atfile, word+1);
1296             if ((sf = fopen(atfile, "r")) == NULL) {
1297                 syslog(LOG_WARNING, "can't open indirect secret file %s",
1298                        atfile);
1299                 continue;
1300             }
1301             check_access(sf, atfile);
1302             if (!getword(sf, word, &xxx, atfile)) {
1303                 syslog(LOG_WARNING, "no secret in indirect secret file %s",
1304                        atfile);
1305                 fclose(sf);
1306                 continue;
1307             }
1308             fclose(sf);
1309         }
1310         if (secret != NULL)
1311             strcpy(lsecret, word);
1312
1313         /*
1314          * Now read address authorization info and make a wordlist.
1315          */
1316         alist = alast = NULL;
1317         for (;;) {
1318             if (!getword(f, word, &newline, filename) || newline)
1319                 break;
1320             ap = (struct wordlist *) malloc(sizeof(struct wordlist)
1321                                             + strlen(word));
1322             if (ap == NULL)
1323                 novm("authorized addresses");
1324             ap->next = NULL;
1325             strcpy(ap->word, word);
1326             if (alist == NULL)
1327                 alist = ap;
1328             else
1329                 alast->next = ap;
1330             alast = ap;
1331         }
1332
1333         /*
1334          * Check if the given IP address is allowed by the wordlist.
1335          */
1336         if (ipaddr != 0 && !ip_addr_check(ipaddr, alist)) {
1337             free_wordlist(alist);
1338             continue;
1339         }
1340
1341         /*
1342          * This is the best so far; remember it.
1343          */
1344         best_flag = got_flag;
1345         if (addr_list)
1346             free_wordlist(addr_list);
1347         addr_list = alist;
1348         if (secret != NULL)
1349             strcpy(secret, lsecret);
1350
1351         if (!newline)
1352             break;
1353     }
1354
1355     if (addrs != NULL)
1356         *addrs = addr_list;
1357     else if (addr_list != NULL)
1358         free_wordlist(addr_list);
1359
1360     return best_flag;
1361 }
1362
1363 /*
1364  * free_wordlist - release memory allocated for a wordlist.
1365  */
1366 static void
1367 free_wordlist(wp)
1368     struct wordlist *wp;
1369 {
1370     struct wordlist *next;
1371
1372     while (wp != NULL) {
1373         next = wp->next;
1374         free(wp);
1375         wp = next;
1376     }
1377 }
1378
1379 /*
1380  * auth_script - execute a script with arguments
1381  * interface-name peer-name real-user tty speed
1382  */
1383 static void
1384 auth_script(script)
1385     char *script;
1386 {
1387     char strspeed[32];
1388     struct passwd *pw;
1389     char struid[32];
1390     char *user_name;
1391     char *argv[8];
1392
1393     if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
1394         user_name = pw->pw_name;
1395     else {
1396         sprintf(struid, "%d", getuid());
1397         user_name = struid;
1398     }
1399     sprintf(strspeed, "%d", baud_rate);
1400
1401     argv[0] = script;
1402     argv[1] = ifname;
1403     argv[2] = peer_authname;
1404     argv[3] = user_name;
1405     argv[4] = devnam;
1406     argv[5] = strspeed;
1407     argv[6] = NULL;
1408
1409     run_program(script, argv, 0);
1410 }