]> git.ozlabs.org Git - ppp.git/blob - pppd/auth.c
nodeflatedraft option; small change to ms-dns and ms-wins options.
[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.36 1998/03/25 01:26: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     ++num_np_up;
438 }
439
440 /*
441  * np_down - a network protocol has gone down.
442  */
443 void
444 np_down(unit, proto)
445     int unit, proto;
446 {
447     if (--num_np_up == 0 && idle_time_limit > 0) {
448         UNTIMEOUT(check_idle, NULL);
449     }
450 }
451
452 /*
453  * np_finished - a network protocol has finished using the link.
454  */
455 void
456 np_finished(unit, proto)
457     int unit, proto;
458 {
459     if (--num_np_open <= 0) {
460         /* no further use for the link: shut up shop. */
461         lcp_close(0, "No network protocols running");
462     }
463 }
464
465 /*
466  * check_idle - check whether the link has been idle for long
467  * enough that we can shut it down.
468  */
469 static void
470 check_idle(arg)
471      void *arg;
472 {
473     struct ppp_idle idle;
474     time_t itime;
475
476     if (!get_idle_time(0, &idle))
477         return;
478     itime = MIN(idle.xmit_idle, idle.recv_idle);
479     if (itime >= idle_time_limit) {
480         /* link is idle: shut it down. */
481         syslog(LOG_INFO, "Terminating connection due to lack of activity.");
482         lcp_close(0, "Link inactive");
483     } else {
484         TIMEOUT(check_idle, NULL, idle_time_limit - itime);
485     }
486 }
487
488 /*
489  * connect_time_expired - log a message and close the connection.
490  */
491 static void
492 connect_time_expired(arg)
493     void *arg;
494 {
495     syslog(LOG_INFO, "Connect time expired");
496     lcp_close(0, "Connect time expired");       /* Close connection */
497 }
498
499 /*
500  * auth_check_options - called to check authentication options.
501  */
502 void
503 auth_check_options()
504 {
505     lcp_options *wo = &lcp_wantoptions[0];
506     int can_auth;
507     ipcp_options *ipwo = &ipcp_wantoptions[0];
508     u_int32_t remote;
509
510     /* Default our_name to hostname, and user to our_name */
511     if (our_name[0] == 0 || usehostname)
512         strcpy(our_name, hostname);
513     if (user[0] == 0)
514         strcpy(user, our_name);
515
516     /* If authentication is required, ask peer for CHAP or PAP. */
517     if (auth_required && !wo->neg_chap && !wo->neg_upap) {
518         wo->neg_chap = 1;
519         wo->neg_upap = 1;
520     }
521
522     /*
523      * Check whether we have appropriate secrets to use
524      * to authenticate the peer.
525      */
526     can_auth = wo->neg_upap && (uselogin || have_pap_secret());
527     if (!can_auth && wo->neg_chap) {
528         remote = ipwo->accept_remote? 0: ipwo->hisaddr;
529         can_auth = have_chap_secret(remote_name, our_name, remote);
530     }
531
532     if (auth_required && !can_auth) {
533         option_error("peer authentication required but no suitable secret(s) found\n");
534         if (remote_name[0] == 0)
535             option_error("for authenticating any peer to us (%s)\n", our_name);
536         else
537             option_error("for authenticating peer %s to us (%s)\n",
538                          remote_name, our_name);
539         exit(1);
540     }
541
542     /*
543      * Check whether the user tried to override certain values
544      * set by root.
545      */
546     if (!auth_required && auth_req_info.priv > 0) {
547         if (!default_device && devnam_info.priv == 0) {
548             option_error("can't override device name when noauth option used");
549             exit(1);
550         }
551         if ((connector != NULL && connector_info.priv == 0)
552             || (disconnector != NULL && disconnector_info.priv == 0)
553             || (welcomer != NULL && welcomer_info.priv == 0)) {
554             option_error("can't override connect, disconnect or welcome");
555             option_error("option values when noauth option used");
556             exit(1);
557         }
558     }
559 }
560
561 /*
562  * auth_reset - called when LCP is starting negotiations to recheck
563  * authentication options, i.e. whether we have appropriate secrets
564  * to use for authenticating ourselves and/or the peer.
565  */
566 void
567 auth_reset(unit)
568     int unit;
569 {
570     lcp_options *go = &lcp_gotoptions[unit];
571     lcp_options *ao = &lcp_allowoptions[0];
572     ipcp_options *ipwo = &ipcp_wantoptions[0];
573     u_int32_t remote;
574
575     ao->neg_upap = !refuse_pap && (passwd[0] != 0 || get_pap_passwd(NULL));
576     ao->neg_chap = !refuse_chap
577         && have_chap_secret(user, remote_name, (u_int32_t)0);
578
579     if (go->neg_upap && !uselogin && !have_pap_secret())
580         go->neg_upap = 0;
581     if (go->neg_chap) {
582         remote = ipwo->accept_remote? 0: ipwo->hisaddr;
583         if (!have_chap_secret(remote_name, our_name, remote))
584             go->neg_chap = 0;
585     }
586 }
587
588
589 /*
590  * check_passwd - Check the user name and passwd against the PAP secrets
591  * file.  If requested, also check against the system password database,
592  * and login the user if OK.
593  *
594  * returns:
595  *      UPAP_AUTHNAK: Authentication failed.
596  *      UPAP_AUTHACK: Authentication succeeded.
597  * In either case, msg points to an appropriate message.
598  */
599 int
600 check_passwd(unit, auser, userlen, apasswd, passwdlen, msg, msglen)
601     int unit;
602     char *auser;
603     int userlen;
604     char *apasswd;
605     int passwdlen;
606     char **msg;
607     int *msglen;
608 {
609     int ret;
610     char *filename;
611     FILE *f;
612     struct wordlist *addrs;
613     u_int32_t remote;
614     ipcp_options *ipwo = &ipcp_wantoptions[unit];
615     char passwd[256], user[256];
616     char secret[MAXWORDLEN];
617     static int attempts = 0;
618
619     /*
620      * Make copies of apasswd and auser, then null-terminate them.
621      */
622     BCOPY(apasswd, passwd, passwdlen);
623     passwd[passwdlen] = '\0';
624     BCOPY(auser, user, userlen);
625     user[userlen] = '\0';
626     *msg = (char *) 0;
627
628     /*
629      * Open the file of pap secrets and scan for a suitable secret
630      * for authenticating this user.
631      */
632     filename = _PATH_UPAPFILE;
633     addrs = NULL;
634     ret = UPAP_AUTHACK;
635     f = fopen(filename, "r");
636     if (f == NULL) {
637         syslog(LOG_ERR, "Can't open PAP password file %s: %m", filename);
638         ret = UPAP_AUTHNAK;
639
640     } else {
641         check_access(f, filename);
642         remote = ipwo->accept_remote? 0: ipwo->hisaddr;
643         if (scan_authfile(f, user, our_name, remote,
644                           secret, &addrs, filename) < 0
645             || (secret[0] != 0 && (cryptpap || strcmp(passwd, secret) != 0)
646                 && strcmp(crypt(passwd, secret), secret) != 0)) {
647             syslog(LOG_WARNING, "PAP authentication failure for %s", user);
648             ret = UPAP_AUTHNAK;
649         }
650         fclose(f);
651     }
652
653     if (uselogin && ret == UPAP_AUTHACK) {
654         ret = plogin(user, passwd, msg, msglen);
655         if (ret == UPAP_AUTHNAK) {
656             syslog(LOG_WARNING, "PAP login failure for %s", user);
657         }
658     }
659
660     if (ret == UPAP_AUTHNAK) {
661         if (*msg == (char *) 0)
662             *msg = "Login incorrect";
663         *msglen = strlen(*msg);
664         /*
665          * Frustrate passwd stealer programs.
666          * Allow 10 tries, but start backing off after 3 (stolen from login).
667          * On 10'th, drop the connection.
668          */
669         if (attempts++ >= 10) {
670             syslog(LOG_WARNING, "%d LOGIN FAILURES ON %s, %s",
671                    attempts, devnam, user);
672             quit();
673         }
674         if (attempts > 3)
675             sleep((u_int) (attempts - 3) * 5);
676         if (addrs != NULL)
677             free_wordlist(addrs);
678
679     } else {
680         attempts = 0;                   /* Reset count */
681         if (*msg == (char *) 0)
682             *msg = "Login ok";
683         *msglen = strlen(*msg);
684         set_allowed_addrs(unit, addrs);
685     }
686
687     BZERO(passwd, sizeof(passwd));
688     BZERO(secret, sizeof(secret));
689
690     return ret;
691 }
692
693 /*
694  * This function is needed for PAM.
695  */
696
697 #ifdef USE_PAM
698 static char *PAM_username = "";
699 static char *PAM_password = "";
700
701 #ifdef PAM_ESTABLISH_CRED       /* new PAM defines :(^ */
702 #define MY_PAM_STRERROR(err_code)  (char *) pam_strerror(pamh,err_code)
703 #else
704 #define MY_PAM_STRERROR(err_code)  (char *) pam_strerror(err_code)
705 #endif
706
707 static int pam_conv (int num_msg,
708                      const struct pam_message **msg,
709                      struct pam_response **resp,
710                      void *appdata_ptr)
711 {
712     int count = 0, replies = 0;
713     struct pam_response *reply = NULL;
714     int size = 0;
715
716     for (count = 0; count < num_msg; count++)
717       {
718         size += sizeof (struct pam_response);
719         reply = realloc (reply, size); /* ANSI: is malloc() if reply==NULL */
720         if (!reply)
721             return PAM_CONV_ERR;
722
723         switch (msg[count]->msg_style)
724           {
725         case PAM_PROMPT_ECHO_ON:
726             reply[replies].resp_retcode = PAM_SUCCESS;
727             reply[replies++].resp = strdup(PAM_username); /* never NULL */
728             break;
729
730         case PAM_PROMPT_ECHO_OFF:
731             reply[replies].resp_retcode = PAM_SUCCESS;
732             reply[replies++].resp = strdup(PAM_password); /* never NULL */
733             break;
734
735         case PAM_TEXT_INFO:
736             reply[replies].resp_retcode = PAM_SUCCESS;
737             reply[replies++].resp = NULL;
738             break;
739
740         case PAM_ERROR_MSG:
741         default:
742             free (reply);
743             return PAM_CONV_ERR;
744           }
745       }
746
747     if (resp)
748         *resp = reply;
749     else
750         free (reply);
751
752     return PAM_SUCCESS;
753 }
754 #endif
755
756 /*
757  * plogin - Check the user name and password against the system
758  * password database, and login the user if OK.
759  *
760  * returns:
761  *      UPAP_AUTHNAK: Login failed.
762  *      UPAP_AUTHACK: Login succeeded.
763  * In either case, msg points to an appropriate message.
764  */
765
766 static int
767 plogin(user, passwd, msg, msglen)
768     char *user;
769     char *passwd;
770     char **msg;
771     int *msglen;
772 {
773
774 #ifdef USE_PAM
775
776     struct pam_conv pam_conversation;
777     pam_handle_t *pamh;
778     int pam_error;
779 /*
780  * Fill the pam_conversion structure
781  */
782     memset (&pam_conversation, '\0', sizeof (struct pam_conv));
783     pam_conversation.conv = &pam_conv;
784
785     pam_error = pam_start ("ppp", user, &pam_conversation, &pamh);
786
787     if (pam_error != PAM_SUCCESS) {
788         *msg = MY_PAM_STRERROR (pam_error);
789         return UPAP_AUTHNAK;
790     }
791 /*
792  * Define the fields for the credintial validation
793  */
794     (void) pam_set_item (pamh, PAM_TTY, devnam);
795     PAM_username = user;
796     PAM_password = passwd;
797 /*
798  * Validate the user
799  */
800     pam_error = pam_authenticate (pamh, PAM_SILENT);
801     if (pam_error == PAM_SUCCESS) {
802         pam_error = pam_acct_mgmt (pamh, PAM_SILENT);
803
804         /* start a session for this user. Session closed when link ends. */
805         if (pam_error == PAM_SUCCESS)
806            (void) pam_open_session (pamh, PAM_SILENT);
807     }
808
809     *msg = MY_PAM_STRERROR (pam_error);
810
811     PAM_username =
812     PAM_password = "";
813 /*
814  * Clean up the mess
815  */
816     (void) pam_end (pamh, pam_error);
817
818     if (pam_error != PAM_SUCCESS)
819         return UPAP_AUTHNAK;
820 /*
821  * Use the non-PAM methods directly
822  */
823 #else /* #ifdef USE_PAM */
824
825     struct passwd *pw;
826     char *tty;
827
828 #ifdef HAS_SHADOW
829     struct spwd *spwd;
830     struct spwd *getspnam();
831 #endif
832
833     pw = getpwnam(user);
834     endpwent();
835     if (pw == NULL) {
836         return (UPAP_AUTHNAK);
837     }
838
839 #ifdef HAS_SHADOW
840     spwd = getspnam(user);
841     endspent();
842     if (spwd) {
843         /* check the age of the password entry */
844         long now = time(NULL) / 86400L;
845
846         if ((spwd->sp_expire > 0 && now >= spwd->sp_expire)
847             || ((spwd->sp_max >= 0 && spwd->sp_max < 10000)
848                 && spwd->sp_lstchg >= 0
849                 && now >= spwd->sp_lstchg + spwd->sp_max)) {
850             syslog(LOG_WARNING, "Password for %s has expired", user);
851             return (UPAP_AUTHNAK);
852         }
853         pw->pw_passwd = spwd->sp_pwdp;
854     }
855 #endif
856
857     /*
858      * If no passwd, don't let them login.
859      */
860     if (pw->pw_passwd == NULL || *pw->pw_passwd == '\0'
861         || strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd) != 0)
862         return (UPAP_AUTHNAK);
863
864     /* These functions are not enabled for PAM. The reason for this is that */
865     /* there is not necessarily a "passwd" entry for this user. That is     */
866     /* real purpose of 'PAM' -- to virtualize the account data from the     */
867     /* application. If you want to do the same thing, write the entry in    */
868     /* the 'session' hook.                                                  */
869
870     /*
871      * Write a wtmp entry for this user.
872      */
873
874     tty = devnam;
875     if (strncmp(tty, "/dev/", 5) == 0)
876         tty += 5;
877     logwtmp(tty, user, remote_name);            /* Add wtmp login entry */
878
879 #if defined(_PATH_LASTLOG)
880     {
881             struct lastlog ll;
882             int fd;
883
884             if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
885                 (void)lseek(fd, (off_t)(pw->pw_uid * sizeof(ll)), SEEK_SET);
886                 memset((void *)&ll, 0, sizeof(ll));
887                 (void)time(&ll.ll_time);
888                 (void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
889                 (void)write(fd, (char *)&ll, sizeof(ll));
890                 (void)close(fd);
891             }
892     }
893 #endif
894
895 #endif /* #ifdef USE_PAM */
896
897     syslog(LOG_INFO, "user %s logged in", user);
898     logged_in = TRUE;
899
900     return (UPAP_AUTHACK);
901 }
902
903 /*
904  * plogout - Logout the user.
905  */
906 static void
907 plogout()
908 {
909 #ifdef USE_PAM
910     struct pam_conv pam_conversation;
911     pam_handle_t *pamh;
912     int pam_error;
913 /*
914  * Fill the pam_conversion structure. The PAM specification states that the
915  * session must be able to be closed by a totally different handle from which
916  * it was created. Hold the PAM group to their own specification!
917  */
918     memset (&pam_conversation, '\0', sizeof (struct pam_conv));
919     pam_conversation.conv = &pam_conv;
920
921     pam_error = pam_start ("ppp", user, &pam_conversation, &pamh);
922     if (pam_error == PAM_SUCCESS) {
923         (void) pam_set_item (pamh, PAM_TTY, devnam);
924         (void) pam_close_session (pamh, PAM_SILENT);
925         (void) pam_end (pamh, PAM_SUCCESS);
926     }
927
928 #else
929     char *tty;
930
931     tty = devnam;
932     if (strncmp(tty, "/dev/", 5) == 0)
933         tty += 5;
934     logwtmp(tty, "", "");               /* Wipe out utmp logout entry */
935 #endif
936
937     logged_in = FALSE;
938 }
939
940
941 /*
942  * null_login - Check if a username of "" and a password of "" are
943  * acceptable, and iff so, set the list of acceptable IP addresses
944  * and return 1.
945  */
946 static int
947 null_login(unit)
948     int unit;
949 {
950     char *filename;
951     FILE *f;
952     int i, ret;
953     struct wordlist *addrs;
954     char secret[MAXWORDLEN];
955
956     /*
957      * Open the file of pap secrets and scan for a suitable secret.
958      * We don't accept a wildcard client.
959      */
960     filename = _PATH_UPAPFILE;
961     addrs = NULL;
962     f = fopen(filename, "r");
963     if (f == NULL)
964         return 0;
965     check_access(f, filename);
966
967     i = scan_authfile(f, "", our_name, (u_int32_t)0, secret, &addrs, filename);
968     ret = i >= 0 && (i & NONWILD_CLIENT) != 0 && secret[0] == 0;
969     BZERO(secret, sizeof(secret));
970
971     if (ret)
972         set_allowed_addrs(unit, addrs);
973     else
974         free_wordlist(addrs);
975
976     fclose(f);
977     return ret;
978 }
979
980
981 /*
982  * get_pap_passwd - get a password for authenticating ourselves with
983  * our peer using PAP.  Returns 1 on success, 0 if no suitable password
984  * could be found.
985  */
986 static int
987 get_pap_passwd(passwd)
988     char *passwd;
989 {
990     char *filename;
991     FILE *f;
992     int ret;
993     struct wordlist *addrs;
994     char secret[MAXWORDLEN];
995
996     filename = _PATH_UPAPFILE;
997     addrs = NULL;
998     f = fopen(filename, "r");
999     if (f == NULL)
1000         return 0;
1001     check_access(f, filename);
1002     ret = scan_authfile(f, user,
1003                         remote_name[0]? remote_name: NULL,
1004                         (u_int32_t)0, secret, NULL, filename);
1005     fclose(f);
1006     if (ret < 0)
1007         return 0;
1008     if (passwd != NULL) {
1009         strncpy(passwd, secret, MAXSECRETLEN);
1010         passwd[MAXSECRETLEN-1] = 0;
1011     }
1012     BZERO(secret, sizeof(secret));
1013     return 1;
1014 }
1015
1016
1017 /*
1018  * have_pap_secret - check whether we have a PAP file with any
1019  * secrets that we could possibly use for authenticating the peer.
1020  */
1021 static int
1022 have_pap_secret()
1023 {
1024     FILE *f;
1025     int ret;
1026     char *filename;
1027     ipcp_options *ipwo = &ipcp_wantoptions[0];
1028     u_int32_t remote;
1029
1030     filename = _PATH_UPAPFILE;
1031     f = fopen(filename, "r");
1032     if (f == NULL)
1033         return 0;
1034
1035     remote = ipwo->accept_remote? 0: ipwo->hisaddr;
1036     ret = scan_authfile(f, NULL, our_name, remote, NULL, NULL, filename);
1037     fclose(f);
1038     if (ret < 0)
1039         return 0;
1040
1041     return 1;
1042 }
1043
1044
1045 /*
1046  * have_chap_secret - check whether we have a CHAP file with a
1047  * secret that we could possibly use for authenticating `client'
1048  * on `server'.  Either can be the null string, meaning we don't
1049  * know the identity yet.
1050  */
1051 static int
1052 have_chap_secret(client, server, remote)
1053     char *client;
1054     char *server;
1055     u_int32_t remote;
1056 {
1057     FILE *f;
1058     int ret;
1059     char *filename;
1060
1061     filename = _PATH_CHAPFILE;
1062     f = fopen(filename, "r");
1063     if (f == NULL)
1064         return 0;
1065
1066     if (client[0] == 0)
1067         client = NULL;
1068     else if (server[0] == 0)
1069         server = NULL;
1070
1071     ret = scan_authfile(f, client, server, remote, NULL, NULL, filename);
1072     fclose(f);
1073     if (ret < 0)
1074         return 0;
1075
1076     return 1;
1077 }
1078
1079
1080 /*
1081  * get_secret - open the CHAP secret file and return the secret
1082  * for authenticating the given client on the given server.
1083  * (We could be either client or server).
1084  */
1085 int
1086 get_secret(unit, client, server, secret, secret_len, save_addrs)
1087     int unit;
1088     char *client;
1089     char *server;
1090     char *secret;
1091     int *secret_len;
1092     int save_addrs;
1093 {
1094     FILE *f;
1095     int ret, len;
1096     char *filename;
1097     struct wordlist *addrs;
1098     char secbuf[MAXWORDLEN];
1099
1100     filename = _PATH_CHAPFILE;
1101     addrs = NULL;
1102     secbuf[0] = 0;
1103
1104     f = fopen(filename, "r");
1105     if (f == NULL) {
1106         syslog(LOG_ERR, "Can't open chap secret file %s: %m", filename);
1107         return 0;
1108     }
1109     check_access(f, filename);
1110
1111     ret = scan_authfile(f, client, server, (u_int32_t)0,
1112                         secbuf, &addrs, filename);
1113     fclose(f);
1114     if (ret < 0)
1115         return 0;
1116
1117     if (save_addrs)
1118         set_allowed_addrs(unit, addrs);
1119
1120     len = strlen(secbuf);
1121     if (len > MAXSECRETLEN) {
1122         syslog(LOG_ERR, "Secret for %s on %s is too long", client, server);
1123         len = MAXSECRETLEN;
1124     }
1125     BCOPY(secbuf, secret, len);
1126     BZERO(secbuf, sizeof(secbuf));
1127     *secret_len = len;
1128
1129     return 1;
1130 }
1131
1132 /*
1133  * set_allowed_addrs() - set the list of allowed addresses.
1134  */
1135 static void
1136 set_allowed_addrs(unit, addrs)
1137     int unit;
1138     struct wordlist *addrs;
1139 {
1140     if (addresses[unit] != NULL)
1141         free_wordlist(addresses[unit]);
1142     addresses[unit] = addrs;
1143
1144     /*
1145      * If there's only one authorized address we might as well
1146      * ask our peer for that one right away
1147      */
1148     if (addrs != NULL && addrs->next == NULL) {
1149         char *p = addrs->word;
1150         struct ipcp_options *wo = &ipcp_wantoptions[unit];
1151         u_int32_t a;
1152         struct hostent *hp;
1153
1154         if (*p != '!' && *p != '-' && strchr(p, '/') == NULL) {
1155             hp = gethostbyname(p);
1156             if (hp != NULL && hp->h_addrtype == AF_INET)
1157                 a = *(u_int32_t *)hp->h_addr;
1158             else
1159                 a = inet_addr(p);
1160             if (a != (u_int32_t) -1)
1161                 wo->hisaddr = a;
1162         }
1163     }
1164 }
1165
1166 /*
1167  * auth_ip_addr - check whether the peer is authorized to use
1168  * a given IP address.  Returns 1 if authorized, 0 otherwise.
1169  */
1170 int
1171 auth_ip_addr(unit, addr)
1172     int unit;
1173     u_int32_t addr;
1174 {
1175     return ip_addr_check(addr, addresses[unit]);
1176 }
1177
1178 static int
1179 ip_addr_check(addr, addrs)
1180     u_int32_t addr;
1181     struct wordlist *addrs;
1182 {
1183     u_int32_t a, mask, ah;
1184     int accept;
1185     char *ptr_word, *ptr_mask;
1186     struct hostent *hp;
1187     struct netent *np;
1188
1189     /* don't allow loopback or multicast address */
1190     if (bad_ip_adrs(addr))
1191         return 0;
1192
1193     if (addrs == NULL)
1194         return !auth_required;          /* no addresses authorized */
1195
1196     for (; addrs != NULL; addrs = addrs->next) {
1197         /* "-" means no addresses authorized, "*" means any address allowed */
1198         ptr_word = addrs->word;
1199         if (strcmp(ptr_word, "-") == 0)
1200             break;
1201         if (strcmp(ptr_word, "*") == 0)
1202             return 1;
1203
1204         accept = 1;
1205         if (*ptr_word == '!') {
1206             accept = 0;
1207             ++ptr_word;
1208         }
1209
1210         mask = ~ (u_int32_t) 0;
1211         ptr_mask = strchr (ptr_word, '/');
1212         if (ptr_mask != NULL) {
1213             int bit_count;
1214
1215             bit_count = (int) strtol (ptr_mask+1, (char **) 0, 10);
1216             if (bit_count <= 0 || bit_count > 32) {
1217                 syslog (LOG_WARNING,
1218                         "invalid address length %s in auth. address list",
1219                         ptr_mask);
1220                 continue;
1221             }
1222             *ptr_mask = '\0';
1223             mask <<= 32 - bit_count;
1224         }
1225
1226         hp = gethostbyname(ptr_word);
1227         if (hp != NULL && hp->h_addrtype == AF_INET) {
1228             a = *(u_int32_t *)hp->h_addr;
1229         } else {
1230             np = getnetbyname (ptr_word);
1231             if (np != NULL && np->n_addrtype == AF_INET) {
1232                 a = htonl (*(u_int32_t *)np->n_net);
1233                 if (ptr_mask == NULL) {
1234                     /* calculate appropriate mask for net */
1235                     ah = ntohl(a);
1236                     if (IN_CLASSA(ah))
1237                         mask = IN_CLASSA_NET;
1238                     else if (IN_CLASSB(ah))
1239                         mask = IN_CLASSB_NET;
1240                     else if (IN_CLASSC(ah))
1241                         mask = IN_CLASSC_NET;
1242                 }
1243             } else {
1244                 a = inet_addr (ptr_word);
1245             }
1246         }
1247
1248         if (ptr_mask != NULL)
1249             *ptr_mask = '/';
1250
1251         if (a == (u_int32_t)-1L)
1252             syslog (LOG_WARNING,
1253                     "unknown host %s in auth. address list",
1254                     addrs->word);
1255         else
1256             /* Here a and addr are in network byte order,
1257                and mask is in host order. */
1258             if (((addr ^ a) & htonl(mask)) == 0)
1259                 return accept;
1260     }
1261     return 0;                   /* not in list => can't have it */
1262 }
1263
1264 /*
1265  * bad_ip_adrs - return 1 if the IP address is one we don't want
1266  * to use, such as an address in the loopback net or a multicast address.
1267  * addr is in network byte order.
1268  */
1269 int
1270 bad_ip_adrs(addr)
1271     u_int32_t addr;
1272 {
1273     addr = ntohl(addr);
1274     return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
1275         || IN_MULTICAST(addr) || IN_BADCLASS(addr);
1276 }
1277
1278 /*
1279  * check_access - complain if a secret file has too-liberal permissions.
1280  */
1281 void
1282 check_access(f, filename)
1283     FILE *f;
1284     char *filename;
1285 {
1286     struct stat sbuf;
1287
1288     if (fstat(fileno(f), &sbuf) < 0) {
1289         syslog(LOG_WARNING, "cannot stat secret file %s: %m", filename);
1290     } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1291         syslog(LOG_WARNING, "Warning - secret file %s has world and/or group access", filename);
1292     }
1293 }
1294
1295
1296 /*
1297  * scan_authfile - Scan an authorization file for a secret suitable
1298  * for authenticating `client' on `server'.  The return value is -1
1299  * if no secret is found, otherwise >= 0.  The return value has
1300  * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
1301  * NONWILD_SERVER set if the secret didn't have "*" for the server.
1302  * Any following words on the line (i.e. address authorization
1303  * info) are placed in a wordlist and returned in *addrs.  
1304  */
1305 static int
1306 scan_authfile(f, client, server, ipaddr, secret, addrs, filename)
1307     FILE *f;
1308     char *client;
1309     char *server;
1310     u_int32_t ipaddr;
1311     char *secret;
1312     struct wordlist **addrs;
1313     char *filename;
1314 {
1315     int newline, xxx;
1316     int got_flag, best_flag;
1317     FILE *sf;
1318     struct wordlist *ap, *addr_list, *alist, *alast;
1319     char word[MAXWORDLEN];
1320     char atfile[MAXWORDLEN];
1321     char lsecret[MAXWORDLEN];
1322
1323     if (addrs != NULL)
1324         *addrs = NULL;
1325     addr_list = NULL;
1326     if (!getword(f, word, &newline, filename))
1327         return -1;              /* file is empty??? */
1328     newline = 1;
1329     best_flag = -1;
1330     for (;;) {
1331         /*
1332          * Skip until we find a word at the start of a line.
1333          */
1334         while (!newline && getword(f, word, &newline, filename))
1335             ;
1336         if (!newline)
1337             break;              /* got to end of file */
1338
1339         /*
1340          * Got a client - check if it's a match or a wildcard.
1341          */
1342         got_flag = 0;
1343         if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
1344             newline = 0;
1345             continue;
1346         }
1347         if (!ISWILD(word))
1348             got_flag = NONWILD_CLIENT;
1349
1350         /*
1351          * Now get a server and check if it matches.
1352          */
1353         if (!getword(f, word, &newline, filename))
1354             break;
1355         if (newline)
1356             continue;
1357         if (server != NULL && strcmp(word, server) != 0 && !ISWILD(word))
1358             continue;
1359         if (!ISWILD(word))
1360             got_flag |= NONWILD_SERVER;
1361
1362         /*
1363          * Got some sort of a match - see if it's better than what
1364          * we have already.
1365          */
1366         if (got_flag <= best_flag)
1367             continue;
1368
1369         /*
1370          * Get the secret.
1371          */
1372         if (!getword(f, word, &newline, filename))
1373             break;
1374         if (newline)
1375             continue;
1376
1377         /*
1378          * Special syntax: @filename means read secret from file.
1379          */
1380         if (word[0] == '@') {
1381             strcpy(atfile, word+1);
1382             if ((sf = fopen(atfile, "r")) == NULL) {
1383                 syslog(LOG_WARNING, "can't open indirect secret file %s",
1384                        atfile);
1385                 continue;
1386             }
1387             check_access(sf, atfile);
1388             if (!getword(sf, word, &xxx, atfile)) {
1389                 syslog(LOG_WARNING, "no secret in indirect secret file %s",
1390                        atfile);
1391                 fclose(sf);
1392                 continue;
1393             }
1394             fclose(sf);
1395         }
1396         if (secret != NULL)
1397             strcpy(lsecret, word);
1398
1399         /*
1400          * Now read address authorization info and make a wordlist.
1401          */
1402         alist = alast = NULL;
1403         for (;;) {
1404             if (!getword(f, word, &newline, filename) || newline)
1405                 break;
1406             ap = (struct wordlist *) malloc(sizeof(struct wordlist)
1407                                             + strlen(word));
1408             if (ap == NULL)
1409                 novm("authorized addresses");
1410             ap->next = NULL;
1411             strcpy(ap->word, word);
1412             if (alist == NULL)
1413                 alist = ap;
1414             else
1415                 alast->next = ap;
1416             alast = ap;
1417         }
1418
1419         /*
1420          * Check if the given IP address is allowed by the wordlist.
1421          */
1422         if (ipaddr != 0 && !ip_addr_check(ipaddr, alist)) {
1423             free_wordlist(alist);
1424             continue;
1425         }
1426
1427         /*
1428          * This is the best so far; remember it.
1429          */
1430         best_flag = got_flag;
1431         if (addr_list)
1432             free_wordlist(addr_list);
1433         addr_list = alist;
1434         if (secret != NULL)
1435             strcpy(secret, lsecret);
1436
1437         if (!newline)
1438             break;
1439     }
1440
1441     if (addrs != NULL)
1442         *addrs = addr_list;
1443     else if (addr_list != NULL)
1444         free_wordlist(addr_list);
1445
1446     return best_flag;
1447 }
1448
1449 /*
1450  * free_wordlist - release memory allocated for a wordlist.
1451  */
1452 static void
1453 free_wordlist(wp)
1454     struct wordlist *wp;
1455 {
1456     struct wordlist *next;
1457
1458     while (wp != NULL) {
1459         next = wp->next;
1460         free(wp);
1461         wp = next;
1462     }
1463 }
1464
1465 /*
1466  * auth_script - execute a script with arguments
1467  * interface-name peer-name real-user tty speed
1468  */
1469 static void
1470 auth_script(script)
1471     char *script;
1472 {
1473     char strspeed[32];
1474     struct passwd *pw;
1475     char struid[32];
1476     char *user_name;
1477     char *argv[8];
1478
1479     if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
1480         user_name = pw->pw_name;
1481     else {
1482         sprintf(struid, "%d", getuid());
1483         user_name = struid;
1484     }
1485     sprintf(strspeed, "%d", baud_rate);
1486
1487     argv[0] = script;
1488     argv[1] = ifname;
1489     argv[2] = peer_authname;
1490     argv[3] = user_name;
1491     argv[4] = devnam;
1492     argv[5] = strspeed;
1493     argv[6] = NULL;
1494
1495     run_program(script, argv, 0);
1496 }