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