]> git.ozlabs.org Git - ppp.git/blob - pppd/auth.c
get crypt decl; mods to shadow password stuff
[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.23 1996/05/28 00:47:01 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 HAS_SHADOW
63 #include <shadow.h>
64 #include <shadow/pwauth.h>
65 #ifndef PW_PPP
66 #define PW_PPP PW_LOGIN
67 #endif
68 #endif
69
70 #include "pppd.h"
71 #include "fsm.h"
72 #include "lcp.h"
73 #include "ipcp.h"
74 #include "upap.h"
75 #include "chap.h"
76 #include "pathnames.h"
77
78 #if defined(sun) && defined(sparc)
79 #include <alloca.h>
80 #endif /*sparc*/
81
82 /* Used for storing a sequence of words.  Usually malloced. */
83 struct wordlist {
84     struct wordlist     *next;
85     char                word[1];
86 };
87
88 /* Bits in scan_authfile return value */
89 #define NONWILD_SERVER  1
90 #define NONWILD_CLIENT  2
91
92 #define ISWILD(word)    (word[0] == '*' && word[1] == 0)
93
94 #define FALSE   0
95 #define TRUE    1
96
97 /* Records which authentication operations haven't completed yet. */
98 static int auth_pending[NUM_PPP];
99
100 /* Set if we have successfully called login() */
101 static int logged_in;
102
103 /* List of addresses which the peer may use. */
104 static struct wordlist *addresses[NUM_PPP];
105
106 /* Number of network protocols which we have opened. */
107 static int num_np_open;
108
109 /* Number of network protocols which have come up. */
110 static int num_np_up;
111
112 /* Bits in auth_pending[] */
113 #define UPAP_WITHPEER   1
114 #define UPAP_PEER       2
115 #define CHAP_WITHPEER   4
116 #define CHAP_PEER       8
117
118 /* Prototypes for procedures local to this file. */
119
120 static void network_phase __P((int));
121 static void check_idle __P((caddr_t));
122 static int  login __P((char *, char *, char **, int *));
123 static void logout __P((void));
124 static int  null_login __P((int));
125 static int  get_upap_passwd __P((void));
126 static int  have_upap_secret __P((void));
127 static int  have_chap_secret __P((char *, char *, u_int32_t));
128 static int  ip_addr_check __P((u_int32_t, struct wordlist *));
129 static int  scan_authfile __P((FILE *, char *, char *, u_int32_t, char *,
130                                struct wordlist **, char *));
131 static void free_wordlist __P((struct wordlist *));
132
133 /*
134  * An Open on LCP has requested a change from Dead to Establish phase.
135  * Do what's necessary to bring the physical layer up.
136  */
137 void
138 link_required(unit)
139     int unit;
140 {
141 }
142
143 /*
144  * LCP has terminated the link; go to the Dead phase and take the
145  * physical layer down.
146  */
147 void
148 link_terminated(unit)
149     int unit;
150 {
151     if (phase == PHASE_DEAD)
152         return;
153     if (logged_in)
154         logout();
155     phase = PHASE_DEAD;
156     syslog(LOG_NOTICE, "Connection terminated.");
157 }
158
159 /*
160  * LCP has gone down; it will either die or try to re-establish.
161  */
162 void
163 link_down(unit)
164     int unit;
165 {
166     int i;
167     struct protent *protp;
168
169     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
170         if (!protp->enabled_flag)
171             continue;
172         if (protp->protocol != PPP_LCP && protp->lowerdown != NULL)
173             (*protp->lowerdown)(unit);
174         if (protp->protocol < 0xC000 && protp->close != NULL)
175             (*protp->close)(unit, "LCP down");
176     }
177     num_np_open = 0;
178     num_np_up = 0;
179     phase = PHASE_TERMINATE;
180 }
181
182 /*
183  * The link is established.
184  * Proceed to the Dead, Authenticate or Network phase as appropriate.
185  */
186 void
187 link_established(unit)
188     int unit;
189 {
190     int auth;
191     lcp_options *wo = &lcp_wantoptions[unit];
192     lcp_options *go = &lcp_gotoptions[unit];
193     lcp_options *ho = &lcp_hisoptions[unit];
194     int i;
195     struct protent *protp;
196
197     /*
198      * Tell higher-level protocols that LCP is up.
199      */
200     for (i = 0; (protp = protocols[i]) != NULL; ++i)
201         if (protp->protocol != PPP_LCP && protp->enabled_flag
202             && protp->lowerup != NULL)
203             (*protp->lowerup)(unit);
204
205     if (auth_required && !(go->neg_chap || go->neg_upap)) {
206         /*
207          * We wanted the peer to authenticate itself, and it refused:
208          * treat it as though it authenticated with PAP using a username
209          * of "" and a password of "".  If that's not OK, boot it out.
210          */
211         if (!wo->neg_upap || !null_login(unit)) {
212             syslog(LOG_WARNING, "peer refused to authenticate");
213             lcp_close(unit, "peer refused to authenticate");
214             phase = PHASE_TERMINATE;
215             return;
216         }
217     }
218
219     phase = PHASE_AUTHENTICATE;
220     auth = 0;
221     if (go->neg_chap) {
222         ChapAuthPeer(unit, our_name, go->chap_mdtype);
223         auth |= CHAP_PEER;
224     } else if (go->neg_upap) {
225         upap_authpeer(unit);
226         auth |= UPAP_PEER;
227     }
228     if (ho->neg_chap) {
229         ChapAuthWithPeer(unit, our_name, ho->chap_mdtype);
230         auth |= CHAP_WITHPEER;
231     } else if (ho->neg_upap) {
232         upap_authwithpeer(unit, user, passwd);
233         auth |= UPAP_WITHPEER;
234     }
235     auth_pending[unit] = auth;
236
237     if (!auth)
238         network_phase(unit);
239 }
240
241 /*
242  * Proceed to the network phase.
243  */
244 static void
245 network_phase(unit)
246     int unit;
247 {
248     int i;
249     struct protent *protp;
250
251     phase = PHASE_NETWORK;
252 #if 0
253     if (!demand)
254         set_filters(&pass_filter, &active_filter);
255 #endif
256     for (i = 0; (protp = protocols[i]) != NULL; ++i)
257         if (protp->protocol < 0xC000 && protp->enabled_flag
258             && protp->open != NULL) {
259             (*protp->open)(unit);
260             if (protp->protocol != PPP_CCP)
261                 ++num_np_open;
262         }
263 }
264
265 /*
266  * The peer has failed to authenticate himself using `protocol'.
267  */
268 void
269 auth_peer_fail(unit, protocol)
270     int unit, protocol;
271 {
272     /*
273      * Authentication failure: take the link down
274      */
275     lcp_close(unit, "Authentication failed");
276     phase = PHASE_TERMINATE;
277 }
278
279 /*
280  * The peer has been successfully authenticated using `protocol'.
281  */
282 void
283 auth_peer_success(unit, protocol)
284     int unit, protocol;
285 {
286     int bit;
287
288     switch (protocol) {
289     case PPP_CHAP:
290         bit = CHAP_PEER;
291         break;
292     case PPP_PAP:
293         bit = UPAP_PEER;
294         break;
295     default:
296         syslog(LOG_WARNING, "auth_peer_success: unknown protocol %x",
297                protocol);
298         return;
299     }
300
301     /*
302      * If there is no more authentication still to be done,
303      * proceed to the network phase.
304      */
305     if ((auth_pending[unit] &= ~bit) == 0)
306         network_phase(unit);
307 }
308
309 /*
310  * We have failed to authenticate ourselves to the peer using `protocol'.
311  */
312 void
313 auth_withpeer_fail(unit, protocol)
314     int unit, protocol;
315 {
316     /*
317      * We've failed to authenticate ourselves to our peer.
318      * He'll probably take the link down, and there's not much
319      * we can do except wait for that.
320      */
321 }
322
323 /*
324  * We have successfully authenticated ourselves with the peer using `protocol'.
325  */
326 void
327 auth_withpeer_success(unit, protocol)
328     int unit, protocol;
329 {
330     int bit;
331
332     switch (protocol) {
333     case PPP_CHAP:
334         bit = CHAP_WITHPEER;
335         break;
336     case PPP_PAP:
337         bit = UPAP_WITHPEER;
338         break;
339     default:
340         syslog(LOG_WARNING, "auth_peer_success: unknown protocol %x",
341                protocol);
342         bit = 0;
343     }
344
345     /*
346      * If there is no more authentication still being done,
347      * proceed to the network phase.
348      */
349     if ((auth_pending[unit] &= ~bit) == 0)
350         network_phase(unit);
351 }
352
353
354 /*
355  * np_up - a network protocol has come up.
356  */
357 void
358 np_up(unit, proto)
359     int unit, proto;
360 {
361     if (num_np_up == 0 && idle_time_limit > 0) {
362         TIMEOUT(check_idle, NULL, idle_time_limit);
363     }
364     ++num_np_up;
365 }
366
367 /*
368  * np_down - a network protocol has gone down.
369  */
370 void
371 np_down(unit, proto)
372     int unit, proto;
373 {
374     if (--num_np_up == 0 && idle_time_limit > 0) {
375         UNTIMEOUT(check_idle, NULL);
376     }
377 }
378
379 /*
380  * np_finished - a network protocol has finished using the link.
381  */
382 void
383 np_finished(unit, proto)
384     int unit, proto;
385 {
386     if (--num_np_open <= 0) {
387         /* no further use for the link: shut up shop. */
388         lcp_close(0, "No network protocols running");
389     }
390 }
391
392 /*
393  * check_idle - check whether the link has been idle for long
394  * enough that we can shut it down.
395  */
396 static void
397 check_idle(arg)
398     caddr_t arg;
399 {
400     struct ppp_idle idle;
401     time_t itime;
402
403     if (!get_idle_time(0, &idle))
404         return;
405     itime = MIN(idle.xmit_idle, idle.recv_idle);
406     if (itime >= idle_time_limit) {
407         /* link is idle: shut it down. */
408         syslog(LOG_INFO, "Terminating connection due to lack of activity.");
409         lcp_close(0, "Link inactive");
410     } else {
411         TIMEOUT(check_idle, NULL, idle_time_limit - itime);
412     }
413 }
414
415 /*
416  * auth_check_options - called to check authentication options.
417  */
418 void
419 auth_check_options()
420 {
421     lcp_options *wo = &lcp_wantoptions[0];
422     lcp_options *ao = &lcp_allowoptions[0];
423     ipcp_options *ipwo = &ipcp_wantoptions[0];
424     u_int32_t remote;
425
426     /* Default our_name to hostname, and user to our_name */
427     if (our_name[0] == 0 || usehostname)
428         strcpy(our_name, hostname);
429     if (user[0] == 0)
430         strcpy(user, our_name);
431
432     /* If authentication is required, ask peer for CHAP or PAP. */
433     if (auth_required && !wo->neg_chap && !wo->neg_upap) {
434         wo->neg_chap = 1;
435         wo->neg_upap = 1;
436     }
437
438     /*
439      * Check whether we have appropriate secrets to use
440      * to authenticate ourselves and/or the peer.
441      */
442     if (ao->neg_upap && passwd[0] == 0 && !get_upap_passwd())
443         ao->neg_upap = 0;
444     if (wo->neg_upap && !uselogin && !have_upap_secret())
445         wo->neg_upap = 0;
446     if (ao->neg_chap && !have_chap_secret(our_name, remote_name, (u_int32_t)0))
447         ao->neg_chap = 0;
448     if (wo->neg_chap) {
449         remote = ipwo->accept_remote? 0: ipwo->hisaddr;
450         if (!have_chap_secret(remote_name, our_name, remote))
451             wo->neg_chap = 0;
452     }
453
454     if (auth_required && !wo->neg_chap && !wo->neg_upap) {
455         fprintf(stderr, "\
456 pppd: peer authentication required but no suitable secret(s) found\n");
457         exit(1);
458     }
459
460 }
461
462
463 /*
464  * check_passwd - Check the user name and passwd against the PAP secrets
465  * file.  If requested, also check against the system password database,
466  * and login the user if OK.
467  *
468  * returns:
469  *      UPAP_AUTHNAK: Authentication failed.
470  *      UPAP_AUTHACK: Authentication succeeded.
471  * In either case, msg points to an appropriate message.
472  */
473 int
474 check_passwd(unit, auser, userlen, apasswd, passwdlen, msg, msglen)
475     int unit;
476     char *auser;
477     int userlen;
478     char *apasswd;
479     int passwdlen;
480     char **msg;
481     int *msglen;
482 {
483     int ret;
484     char *filename;
485     FILE *f;
486     struct wordlist *addrs;
487     u_int32_t remote;
488     ipcp_options *ipwo = &ipcp_wantoptions[unit];
489     char passwd[256], user[256];
490     char secret[MAXWORDLEN];
491     static int attempts = 0;
492
493     /*
494      * Make copies of apasswd and auser, then null-terminate them.
495      */
496     BCOPY(apasswd, passwd, passwdlen);
497     passwd[passwdlen] = '\0';
498     BCOPY(auser, user, userlen);
499     user[userlen] = '\0';
500
501     /*
502      * Open the file of upap secrets and scan for a suitable secret
503      * for authenticating this user.
504      */
505     filename = _PATH_UPAPFILE;
506     addrs = NULL;
507     ret = UPAP_AUTHACK;
508     f = fopen(filename, "r");
509     if (f == NULL) {
510         if (!uselogin) {
511             syslog(LOG_ERR, "Can't open PAP password file %s: %m", filename);
512             ret = UPAP_AUTHNAK;
513         }
514
515     } else {
516         check_access(f, filename);
517         remote = ipwo->accept_remote? 0: ipwo->hisaddr;
518         if (scan_authfile(f, user, our_name, remote,
519                           secret, &addrs, filename) < 0
520             || (secret[0] != 0 && (cryptpap || strcmp(passwd, secret) != 0)
521                 && strcmp(crypt(passwd, secret), secret) != 0)) {
522             syslog(LOG_WARNING, "PAP authentication failure for %s", user);
523             ret = UPAP_AUTHNAK;
524         }
525         fclose(f);
526     }
527
528     if (uselogin && ret == UPAP_AUTHACK) {
529         ret = login(user, passwd, msg, msglen);
530         if (ret == UPAP_AUTHNAK) {
531             syslog(LOG_WARNING, "PAP login failure for %s", user);
532         }
533     }
534
535     if (ret == UPAP_AUTHNAK) {
536         *msg = "Login incorrect";
537         *msglen = strlen(*msg);
538         /*
539          * Frustrate passwd stealer programs.
540          * Allow 10 tries, but start backing off after 3 (stolen from login).
541          * On 10'th, drop the connection.
542          */
543         if (attempts++ >= 10) {
544             syslog(LOG_WARNING, "%d LOGIN FAILURES ON %s, %s",
545                    attempts, devnam, user);
546             quit();
547         }
548         if (attempts > 3)
549             sleep((u_int) (attempts - 3) * 5);
550         if (addrs != NULL)
551             free_wordlist(addrs);
552
553     } else {
554         attempts = 0;                   /* Reset count */
555         *msg = "Login ok";
556         *msglen = strlen(*msg);
557         if (addresses[unit] != NULL)
558             free_wordlist(addresses[unit]);
559         addresses[unit] = addrs;
560     }
561
562     return ret;
563 }
564
565 #ifdef HAS_SHADOW
566 /**************
567  * This function was lifted from the shadow-3.3.2 version by John Haugh II.
568  * It is included because the function was not in the standard libshadow
569  * library. If it is included in the library then I can remove it from here.
570  */
571
572 #define DAY     (24L*3600L)
573 /*
574  * isexpired - determine if account is expired yet
575  *
576  *      isexpired calculates the expiration date based on the
577  *      password expiration criteria.
578  */
579
580 /*ARGSUSED*/
581 int
582 isexpired (pw, sp)
583 struct  passwd  *pw;
584 struct  spwd    *sp;
585 {
586         long    clock;
587
588         clock = time ((time_t *) 0) / DAY;
589
590         /*
591          * Quick and easy - there is an expired account field
592          * along with an inactive account field.  Do the expired
593          * one first since it is worse.
594          */
595
596         if (sp->sp_expire > 0 && sp->sp_expire < clock)
597                 return 3;
598
599         if (sp->sp_inact > 0 && sp->sp_lstchg > 0 && sp->sp_max > 0 &&
600                         sp->sp_inact + sp->sp_lstchg + sp->sp_max < clock)
601                 return 2;
602
603         /*
604          * The last and max fields must be present for an account
605          * to have an expired password.  A maximum of >10000 days
606          * is considered to be infinite.
607          */
608
609         if (sp->sp_lstchg == -1 ||
610                         sp->sp_max == -1 || sp->sp_max >= 10000L)
611                 return 0;
612
613         /*
614          * Calculate today's day and the day on which the password
615          * is going to expire.  If that date has already passed,
616          * the password has expired.
617          */
618
619         if (sp->sp_lstchg + sp->sp_max < clock)
620                 return 1;
621
622         return 0;
623 }
624 #endif
625
626 /*
627  * login - Check the user name and password against the system
628  * password database, and login the user if OK.
629  *
630  * returns:
631  *      UPAP_AUTHNAK: Login failed.
632  *      UPAP_AUTHACK: Login succeeded.
633  * In either case, msg points to an appropriate message.
634  */
635 static int
636 login(user, passwd, msg, msglen)
637     char *user;
638     char *passwd;
639     char **msg;
640     int *msglen;
641 {
642     struct passwd *pw;
643     char *epasswd;
644     char *tty;
645
646 #ifdef HAS_SHADOW
647     struct spwd *spwd;
648     struct spwd *getspnam();
649 #endif
650
651     if ((pw = getpwnam(user)) == NULL) {
652         return (UPAP_AUTHNAK);
653     }
654
655 #ifdef HAS_SHADOW
656     if ((spwd = getspnam(user)) == NULL) {
657         pw->pw_passwd = "";
658     } else {
659         pw->pw_passwd = spwd->sp_pwdp;
660     }
661 #endif
662
663     /*
664      * XXX If no passwd, let them login without one.
665      */
666     if (pw->pw_passwd == '\0') {
667         return (UPAP_AUTHACK);
668     }
669
670 #ifdef HAS_SHADOW
671     if (pw->pw_passwd) {
672         if (pw->pw_passwd[0] == '@') {
673             if (pw_auth (pw->pw_passwd+1, pw->pw_name, PW_PPP, NULL)) {
674                 return (UPAP_AUTHNAK);
675             }
676         } else {
677             epasswd = pw_encrypt(passwd, pw->pw_passwd);
678             if (strcmp(epasswd, pw->pw_passwd)) {
679                 return (UPAP_AUTHNAK);
680             }
681         }
682         /* check the age of the password entry */
683         if (spwd && (isexpired (pw, spwd) != 0)) {
684             return (UPAP_AUTHNAK);
685         }
686     }
687 #else
688     epasswd = crypt(passwd, pw->pw_passwd);
689     if (strcmp(epasswd, pw->pw_passwd)) {
690         return (UPAP_AUTHNAK);
691     }
692 #endif
693
694     syslog(LOG_INFO, "user %s logged in", user);
695
696     /*
697      * Write a wtmp entry for this user.
698      */
699     tty = devnam;
700     if (strncmp(tty, "/dev/", 5) == 0)
701         tty += 5;
702     logwtmp(tty, user, remote_name);            /* Add wtmp login entry */
703     logged_in = TRUE;
704
705     return (UPAP_AUTHACK);
706 }
707
708 /*
709  * logout - Logout the user.
710  */
711 static void
712 logout()
713 {
714     char *tty;
715
716     tty = devnam;
717     if (strncmp(tty, "/dev/", 5) == 0)
718         tty += 5;
719     logwtmp(tty, "", "");               /* Wipe out wtmp logout entry */
720     logged_in = FALSE;
721 }
722
723
724 /*
725  * null_login - Check if a username of "" and a password of "" are
726  * acceptable, and iff so, set the list of acceptable IP addresses
727  * and return 1.
728  */
729 static int
730 null_login(unit)
731     int unit;
732 {
733     char *filename;
734     FILE *f;
735     int i, ret;
736     struct wordlist *addrs;
737     char secret[MAXWORDLEN];
738
739     /*
740      * Open the file of upap secrets and scan for a suitable secret.
741      * We don't accept a wildcard client.
742      */
743     filename = _PATH_UPAPFILE;
744     addrs = NULL;
745     f = fopen(filename, "r");
746     if (f == NULL)
747         return 0;
748     check_access(f, filename);
749
750     i = scan_authfile(f, "", our_name, (u_int32_t)0, secret, &addrs, filename);
751     ret = i >= 0 && (i & NONWILD_CLIENT) != 0 && secret[0] == 0;
752
753     if (ret) {
754         if (addresses[unit] != NULL)
755             free_wordlist(addresses[unit]);
756         addresses[unit] = addrs;
757     }
758
759     fclose(f);
760     return ret;
761 }
762
763
764 /*
765  * get_upap_passwd - get a password for authenticating ourselves with
766  * our peer using PAP.  Returns 1 on success, 0 if no suitable password
767  * could be found.
768  */
769 static int
770 get_upap_passwd()
771 {
772     char *filename;
773     FILE *f;
774     struct wordlist *addrs;
775     char secret[MAXWORDLEN];
776
777     filename = _PATH_UPAPFILE;
778     addrs = NULL;
779     f = fopen(filename, "r");
780     if (f == NULL)
781         return 0;
782     check_access(f, filename);
783     if (scan_authfile(f, user, remote_name, (u_int32_t)0,
784                       secret, NULL, filename) < 0)
785         return 0;
786     strncpy(passwd, secret, MAXSECRETLEN);
787     passwd[MAXSECRETLEN-1] = 0;
788     return 1;
789 }
790
791
792 /*
793  * have_upap_secret - check whether we have a PAP file with any
794  * secrets that we could possibly use for authenticating the peer.
795  */
796 static int
797 have_upap_secret()
798 {
799     FILE *f;
800     int ret;
801     char *filename;
802     ipcp_options *ipwo = &ipcp_wantoptions[0];
803     u_int32_t remote;
804
805     filename = _PATH_UPAPFILE;
806     f = fopen(filename, "r");
807     if (f == NULL)
808         return 0;
809
810     remote = ipwo->accept_remote? 0: ipwo->hisaddr;
811     ret = scan_authfile(f, NULL, our_name, remote, NULL, NULL, filename);
812     fclose(f);
813     if (ret < 0)
814         return 0;
815
816     return 1;
817 }
818
819
820 /*
821  * have_chap_secret - check whether we have a CHAP file with a
822  * secret that we could possibly use for authenticating `client'
823  * on `server'.  Either can be the null string, meaning we don't
824  * know the identity yet.
825  */
826 static int
827 have_chap_secret(client, server, remote)
828     char *client;
829     char *server;
830     u_int32_t remote;
831 {
832     FILE *f;
833     int ret;
834     char *filename;
835
836     filename = _PATH_CHAPFILE;
837     f = fopen(filename, "r");
838     if (f == NULL)
839         return 0;
840
841     if (client[0] == 0)
842         client = NULL;
843     else if (server[0] == 0)
844         server = NULL;
845
846     ret = scan_authfile(f, client, server, remote, NULL, NULL, filename);
847     fclose(f);
848     if (ret < 0)
849         return 0;
850
851     return 1;
852 }
853
854
855 /*
856  * get_secret - open the CHAP secret file and return the secret
857  * for authenticating the given client on the given server.
858  * (We could be either client or server).
859  */
860 int
861 get_secret(unit, client, server, secret, secret_len, save_addrs)
862     int unit;
863     char *client;
864     char *server;
865     char *secret;
866     int *secret_len;
867     int save_addrs;
868 {
869     FILE *f;
870     int ret, len;
871     char *filename;
872     struct wordlist *addrs;
873     char secbuf[MAXWORDLEN];
874
875     filename = _PATH_CHAPFILE;
876     addrs = NULL;
877     secbuf[0] = 0;
878
879     f = fopen(filename, "r");
880     if (f == NULL) {
881         syslog(LOG_ERR, "Can't open chap secret file %s: %m", filename);
882         return 0;
883     }
884     check_access(f, filename);
885
886     ret = scan_authfile(f, client, server, (u_int32_t)0,
887                         secbuf, &addrs, filename);
888     fclose(f);
889     if (ret < 0)
890         return 0;
891
892     if (save_addrs) {
893         if (addresses[unit] != NULL)
894             free_wordlist(addresses[unit]);
895         addresses[unit] = addrs;
896     }
897
898     len = strlen(secbuf);
899     if (len > MAXSECRETLEN) {
900         syslog(LOG_ERR, "Secret for %s on %s is too long", client, server);
901         len = MAXSECRETLEN;
902     }
903     BCOPY(secbuf, secret, len);
904     *secret_len = len;
905
906     return 1;
907 }
908
909 /*
910  * auth_ip_addr - check whether the peer is authorized to use
911  * a given IP address.  Returns 1 if authorized, 0 otherwise.
912  */
913 int
914 auth_ip_addr(unit, addr)
915     int unit;
916     u_int32_t addr;
917 {
918     return ip_addr_check(addr, addresses[unit]);
919 }
920
921 static int
922 ip_addr_check(addr, addrs)
923     u_int32_t addr;
924     struct wordlist *addrs;
925 {
926     u_int32_t a, mask, ah;
927     int accept;
928     char *ptr_word, *ptr_mask;
929     struct hostent *hp;
930     struct netent *np;
931
932     /* don't allow loopback or multicast address */
933     if (bad_ip_adrs(addr))
934         return 0;
935
936     if (addrs == NULL)
937         return 1;               /* no restriction */
938
939     for (; addrs != NULL; addrs = addrs->next) {
940         /* "-" means no addresses authorized */
941         ptr_word = addrs->word;
942         if (strcmp(ptr_word, "-") == 0)
943             break;
944
945         accept = 1;
946         if (*ptr_word == '!') {
947             accept = 0;
948             ++ptr_word;
949         }
950
951         mask = ~ (u_int32_t) 0;
952         ptr_mask = strchr (ptr_word, '/');
953         if (ptr_mask != NULL) {
954             int bit_count;
955
956             bit_count = (int) strtol (ptr_mask+1, (char **) 0, 10);
957             if (bit_count <= 0 || bit_count > 32) {
958                 syslog (LOG_WARNING,
959                         "invalid address length %s in auth. address list",
960                         ptr_mask);
961                 continue;
962             }
963             *ptr_mask = '\0';
964             mask <<= 32 - bit_count;
965         }
966
967         hp = gethostbyname(ptr_word);
968         if (hp != NULL && hp->h_addrtype == AF_INET) {
969             a    = *(u_int32_t *)hp->h_addr;
970             mask = ~ (u_int32_t) 0;     /* are we sure we want this? */
971         } else {
972             np = getnetbyname (ptr_word);
973             if (np != NULL && np->n_addrtype == AF_INET)
974                 a = htonl (*(u_int32_t *)np->n_net);
975             else
976                 a = inet_addr (ptr_word);
977             if (ptr_mask == NULL) {
978                 /* calculate appropriate mask for net */
979                 ah = ntohl(a);
980                 if (IN_CLASSA(ah))
981                     mask = IN_CLASSA_NET;
982                 else if (IN_CLASSB(ah))
983                     mask = IN_CLASSB_NET;
984                 else if (IN_CLASSC(ah))
985                     mask = IN_CLASSC_NET;
986             }
987         }
988
989         if (ptr_mask != NULL)
990             *ptr_mask = '/';
991
992         if (a == -1L)
993             syslog (LOG_WARNING,
994                     "unknown host %s in auth. address list",
995                     addrs->word);
996         else
997             if (((addr ^ a) & htonl(mask)) == 0)
998                 return accept;
999     }
1000     return 0;                   /* not in list => can't have it */
1001 }
1002
1003 /*
1004  * bad_ip_adrs - return 1 if the IP address is one we don't want
1005  * to use, such as an address in the loopback net or a multicast address.
1006  * addr is in network byte order.
1007  */
1008 int
1009 bad_ip_adrs(addr)
1010     u_int32_t addr;
1011 {
1012     addr = ntohl(addr);
1013     return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
1014         || IN_MULTICAST(addr) || IN_BADCLASS(addr);
1015 }
1016
1017 /*
1018  * check_access - complain if a secret file has too-liberal permissions.
1019  */
1020 void
1021 check_access(f, filename)
1022     FILE *f;
1023     char *filename;
1024 {
1025     struct stat sbuf;
1026
1027     if (fstat(fileno(f), &sbuf) < 0) {
1028         syslog(LOG_WARNING, "cannot stat secret file %s: %m", filename);
1029     } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1030         syslog(LOG_WARNING, "Warning - secret file %s has world and/or group access", filename);
1031     }
1032 }
1033
1034
1035 /*
1036  * scan_authfile - Scan an authorization file for a secret suitable
1037  * for authenticating `client' on `server'.  The return value is -1
1038  * if no secret is found, otherwise >= 0.  The return value has
1039  * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
1040  * NONWILD_SERVER set if the secret didn't have "*" for the server.
1041  * Any following words on the line (i.e. address authorization
1042  * info) are placed in a wordlist and returned in *addrs.  
1043  */
1044 static int
1045 scan_authfile(f, client, server, ipaddr, secret, addrs, filename)
1046     FILE *f;
1047     char *client;
1048     char *server;
1049     u_int32_t ipaddr;
1050     char *secret;
1051     struct wordlist **addrs;
1052     char *filename;
1053 {
1054     int newline, xxx;
1055     int got_flag, best_flag;
1056     FILE *sf;
1057     struct wordlist *ap, *addr_list, *alist, *alast;
1058     char word[MAXWORDLEN];
1059     char atfile[MAXWORDLEN];
1060     char lsecret[MAXWORDLEN];
1061
1062     if (addrs != NULL)
1063         *addrs = NULL;
1064     addr_list = NULL;
1065     if (!getword(f, word, &newline, filename))
1066         return -1;              /* file is empty??? */
1067     newline = 1;
1068     best_flag = -1;
1069     for (;;) {
1070         /*
1071          * Skip until we find a word at the start of a line.
1072          */
1073         while (!newline && getword(f, word, &newline, filename))
1074             ;
1075         if (!newline)
1076             break;              /* got to end of file */
1077
1078         /*
1079          * Got a client - check if it's a match or a wildcard.
1080          */
1081         got_flag = 0;
1082         if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
1083             newline = 0;
1084             continue;
1085         }
1086         if (!ISWILD(word))
1087             got_flag = NONWILD_CLIENT;
1088
1089         /*
1090          * Now get a server and check if it matches.
1091          */
1092         if (!getword(f, word, &newline, filename))
1093             break;
1094         if (newline)
1095             continue;
1096         if (server != NULL && strcmp(word, server) != 0 && !ISWILD(word))
1097             continue;
1098         if (!ISWILD(word))
1099             got_flag |= NONWILD_SERVER;
1100
1101         /*
1102          * Got some sort of a match - see if it's better than what
1103          * we have already.
1104          */
1105         if (got_flag <= best_flag)
1106             continue;
1107
1108         /*
1109          * Get the secret.
1110          */
1111         if (!getword(f, word, &newline, filename))
1112             break;
1113         if (newline)
1114             continue;
1115
1116         /*
1117          * Special syntax: @filename means read secret from file.
1118          */
1119         if (word[0] == '@') {
1120             strcpy(atfile, word+1);
1121             if ((sf = fopen(atfile, "r")) == NULL) {
1122                 syslog(LOG_WARNING, "can't open indirect secret file %s",
1123                        atfile);
1124                 continue;
1125             }
1126             check_access(sf, atfile);
1127             if (!getword(sf, word, &xxx, atfile)) {
1128                 syslog(LOG_WARNING, "no secret in indirect secret file %s",
1129                        atfile);
1130                 fclose(sf);
1131                 continue;
1132             }
1133             fclose(sf);
1134         }
1135         if (secret != NULL)
1136             strcpy(lsecret, word);
1137
1138         /*
1139          * Now read address authorization info and make a wordlist.
1140          */
1141         alist = alast = NULL;
1142         for (;;) {
1143             if (!getword(f, word, &newline, filename) || newline)
1144                 break;
1145             ap = (struct wordlist *) malloc(sizeof(struct wordlist)
1146                                             + strlen(word));
1147             if (ap == NULL)
1148                 novm("authorized addresses");
1149             ap->next = NULL;
1150             strcpy(ap->word, word);
1151             if (alist == NULL)
1152                 alist = ap;
1153             else
1154                 alast->next = ap;
1155             alast = ap;
1156         }
1157
1158         /*
1159          * Check if the given IP address is allowed by the wordlist.
1160          */
1161         if (ipaddr != 0 && !ip_addr_check(ipaddr, alist)) {
1162             free_wordlist(alist);
1163             continue;
1164         }
1165
1166         /*
1167          * This is the best so far; remember it.
1168          */
1169         best_flag = got_flag;
1170         if (addr_list)
1171             free_wordlist(addr_list);
1172         addr_list = alist;
1173         if (secret != NULL)
1174             strcpy(secret, lsecret);
1175
1176         if (!newline)
1177             break;
1178     }
1179
1180     if (addrs != NULL)
1181         *addrs = addr_list;
1182     else if (addr_list != NULL)
1183         free_wordlist(addr_list);
1184
1185     return best_flag;
1186 }
1187
1188 /*
1189  * free_wordlist - release memory allocated for a wordlist.
1190  */
1191 static void
1192 free_wordlist(wp)
1193     struct wordlist *wp;
1194 {
1195     struct wordlist *next;
1196
1197     while (wp != NULL) {
1198         next = wp->next;
1199         free(wp);
1200         wp = next;
1201     }
1202 }