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