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