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