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