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