Merge remote-tracking branch 'origin/master'
[unleashed/lotheac.git] / usr / src / cmd / cmd-inet / usr.bin / pppd / auth.c
blob8fb90d1c5ff4dd0a213041b457b60ede4e90cf6a
1 /*
2 * auth.c - PPP authentication and phase control.
4 * Copyright 2007 Sun Microsystems, Inc. All rights reserved.
5 * Use is subject to license terms.
7 * Copyright (c) 1993 The Australian National University.
8 * All rights reserved.
10 * Redistribution and use in source and binary forms are permitted
11 * provided that the above copyright notice and this paragraph are
12 * duplicated in all such forms and that any documentation,
13 * advertising materials, and other materials related to such
14 * distribution and use acknowledge that the software was developed
15 * by the Australian National University. The name of the University
16 * may not be used to endorse or promote products derived from this
17 * software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
20 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
22 * Copyright (c) 1989 Carnegie Mellon University.
23 * All rights reserved.
25 * Redistribution and use in source and binary forms are permitted
26 * provided that the above copyright notice and this paragraph are
27 * duplicated in all such forms and that any documentation,
28 * advertising materials, and other materials related to such
29 * distribution and use acknowledge that the software was developed
30 * by Carnegie Mellon University. The name of the
31 * University may not be used to endorse or promote products derived
32 * from this software without specific prior written permission.
33 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
34 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
35 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
38 /* Pull in crypt() definition. */
39 #define __EXTENSIONS__
41 #include <stdio.h>
42 #include <stddef.h>
43 #include <stdlib.h>
44 #include <unistd.h>
45 #include <pwd.h>
46 #include <grp.h>
47 #include <string.h>
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <sys/socket.h>
51 #include <utmp.h>
52 #include <fcntl.h>
53 #if defined(_PATH_LASTLOG) && (defined(_linux_) || defined(__linux__))
54 #include <lastlog.h>
55 #endif
57 #if defined(_linux_) || defined(__linux__)
58 #include <crypt.h>
59 #endif
61 #include <netdb.h>
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
65 /* Backward compatibility with old Makefiles */
66 #if defined(USE_PAM) && !defined(ALLOW_PAM)
67 #define ALLOW_PAM
68 #endif
70 #ifdef ALLOW_PAM
71 #include <security/pam_appl.h>
72 #endif
74 #ifdef HAS_SHADOW
75 #include <shadow.h>
76 #ifndef PW_PPP
77 #define PW_PPP PW_LOGIN
78 #endif
79 #endif
81 #include "pppd.h"
82 #include "fsm.h"
83 #include "lcp.h"
84 #include "ipcp.h"
85 #include "upap.h"
86 #include "chap.h"
87 #ifdef CBCP_SUPPORT
88 #include "cbcp.h"
89 #endif
90 #include "pathnames.h"
92 /* Bits in scan_authfile return value */
93 #define NONWILD_SERVER 1
94 #define NONWILD_CLIENT 2
96 #define ISWILD(word) (word[0] == '*' && word[1] == '\0')
98 /* The name by which the peer authenticated itself to us. */
99 char peer_authname[MAXNAMELEN];
101 /* Records which authentication operations haven't completed yet. */
102 static int auth_pending[NUM_PPP];
104 /* Set if we have successfully called plogin() */
105 static int logged_in;
107 /* List of addresses which the peer may use. */
108 static struct permitted_ip *addresses[NUM_PPP];
110 /* Wordlist giving addresses which the peer may use
111 without authenticating itself. */
112 static struct wordlist *noauth_addrs;
114 /* Extra options to apply, from the secrets file entry for the peer. */
115 static struct wordlist *extra_options;
117 /* Source of those extra options. */
118 static const char *extra_opt_filename;
119 static int extra_opt_line;
121 /* Number of network protocols which we have opened. */
122 static int num_np_open;
124 /* Number of network protocols which have come up. */
125 static int num_np_up;
127 /* Set if we got the contents of passwd[] from the pap-secrets file. */
128 static int passwd_from_file;
130 /* Set if we require authentication only because we have a default route. */
131 static bool default_auth;
133 /* Hook to enable a plugin to control the idle time limit */
134 int (*idle_time_hook) __P((struct ppp_idle *)) = NULL;
136 /* Hook for a plugin to say whether we can possibly authenticate any peer */
137 int (*pap_check_hook) __P((void)) = NULL;
139 /* Hook for a plugin to check the PAP user and password */
140 int (*pap_auth_hook) __P((char *user, char *passwd, char **msgp,
141 struct wordlist **paddrs,
142 struct wordlist **popts)) = NULL;
144 /* Hook for a plugin to know about the PAP user logout */
145 void (*pap_logout_hook) __P((void)) = NULL;
147 /* Hook for a plugin to get the PAP password for authenticating us */
148 int (*pap_passwd_hook) __P((char *user, char *passwd)) = NULL;
151 * This is used to ensure that we don't start an auth-up/down
152 * script while one is already running.
154 enum script_state {
155 s_down,
156 s_up
159 static enum script_state auth_state = s_down;
160 static enum script_state auth_script_state = s_down;
161 static pid_t auth_script_pid = 0;
164 * This is set by scan_authfile if a client matches, but server doesn't
165 * (possible configuration error).
167 static char scan_server_match_failed[MAXWORDLEN];
170 * Option variables.
172 bool uselogin = 0; /* Use /etc/passwd for checking PAP */
173 bool cryptpap = 0; /* Passwords in pap-secrets are encrypted */
174 bool refuse_pap = 0; /* Don't wanna auth. ourselves with PAP */
175 bool refuse_chap = 0; /* Don't wanna auth. ourselves with CHAP */
176 bool usehostname = 0; /* Use hostname for our_name */
177 bool auth_required = 0; /* Always require authentication from peer */
178 bool allow_any_ip = 0; /* Allow peer to use any IP address */
179 bool explicit_remote = 0; /* User specified explicit remote name */
180 char remote_name[MAXNAMELEN]; /* Peer's name for authentication */
182 #ifdef CHAPMS
183 bool refuse_mschap = 0; /* Don't wanna auth. ourself with MS-CHAPv1 */
184 #else
185 bool refuse_mschap = 1; /* Never auth. ourself with MS-CHAPv1 */
186 #endif
187 #ifdef CHAPMSV2
188 bool refuse_mschapv2 = 0; /* Don't wanna auth. ourself with MS-CHAPv2 */
189 #else
190 bool refuse_mschapv2 = 1; /* Never auth. ourself with MS-CHAPv2 */
191 #endif
193 #ifdef USE_PAM
194 bool use_pam = 1; /* Enable use of PAM by default */
195 #else
196 bool use_pam = 0; /* Disable use of PAM by default */
197 #endif
199 /* Bits in auth_pending[] */
200 #define PAP_WITHPEER 1
201 #define PAP_PEER 2
202 #define CHAP_WITHPEER 4
203 #define CHAP_PEER 8
205 /* Prototypes for procedures local to this file. */
207 static void network_phase __P((int));
208 static void check_idle __P((void *));
209 static void connect_time_expired __P((void *));
210 static int plogin __P((char *, char *, char **));
211 static void plogout __P((void));
212 static int null_login __P((int));
213 static int get_pap_passwd __P((char *));
214 static int have_pap_secret __P((int *));
215 static int have_chap_secret __P((char *, char *, int, int *));
216 static int ip_addr_check __P((u_int32_t, struct permitted_ip *));
217 static int scan_authfile __P((FILE *, char *, char *, char *,
218 struct wordlist **, struct wordlist **,
219 char *));
220 static void free_wordlist __P((struct wordlist *));
221 static void auth_script __P((char *));
222 static void auth_script_done __P((void *, int));
223 static void set_allowed_addrs __P((int, struct wordlist *, struct wordlist *));
224 static int some_ip_ok __P((struct wordlist *));
225 static int setupapfile __P((char **, option_t *));
226 static int privgroup __P((char **, option_t *));
227 static int set_noauth_addr __P((char **, option_t *));
228 static void check_access __P((FILE *, char *));
231 * Authentication-related options.
233 option_t auth_options[] = {
234 { "require-pap", o_bool, &lcp_wantoptions[0].neg_upap,
235 "Require PAP authentication from peer", 1, &auth_required },
236 { "+pap", o_bool, &lcp_wantoptions[0].neg_upap,
237 "Require PAP authentication from peer", 1, &auth_required },
238 { "refuse-pap", o_bool, &refuse_pap,
239 "Don't agree to auth to peer with PAP", 1 },
240 { "-pap", o_bool, &refuse_pap,
241 "Don't allow PAP authentication with peer", 1 },
242 { "require-chap", o_bool, &lcp_wantoptions[0].neg_chap,
243 "Require CHAP authentication from peer", 1, &auth_required },
244 { "+chap", o_bool, &lcp_wantoptions[0].neg_chap,
245 "Require CHAP authentication from peer", 1, &auth_required },
246 { "refuse-chap", o_bool, &refuse_chap,
247 "Don't agree to auth to peer with CHAP", 1 },
248 { "-chap", o_bool, &refuse_chap,
249 "Don't allow CHAP authentication with peer", 1 },
250 { "name", o_string, our_name,
251 "Set local name for authentication",
252 OPT_PRIV|OPT_STATIC, NULL, MAXNAMELEN },
253 { "user", o_string, user,
254 "Set name for auth with peer", OPT_STATIC, NULL, MAXNAMELEN },
255 { "usehostname", o_bool, &usehostname,
256 "Must use hostname for authentication", 1 },
257 { "remotename", o_string, remote_name,
258 "Set remote name for authentication", OPT_STATIC,
259 &explicit_remote, MAXNAMELEN },
260 { "auth", o_bool, &auth_required,
261 "Require authentication from peer", 1 },
262 { "noauth", o_bool, &auth_required,
263 "Don't require peer to authenticate", OPT_PRIV, &allow_any_ip },
264 { "login", o_bool, &uselogin,
265 "Use system password database for PAP", 1 },
266 { "papcrypt", o_bool, &cryptpap,
267 "PAP passwords are encrypted", 1 },
268 { "+ua", o_special, (void *)setupapfile,
269 "Get PAP user and password from file" },
270 { "password", o_string, passwd,
271 "Password for authenticating us to the peer", OPT_STATIC,
272 NULL, MAXSECRETLEN },
273 { "privgroup", o_special, (void *)privgroup,
274 "Allow group members to use privileged options", OPT_PRIV },
275 { "allow-ip", o_special, (void *)set_noauth_addr,
276 "Set peer IP address(es) usable without authentication",
277 OPT_PRIV },
278 #ifdef CHAPMS
279 { "require-mschap", o_bool, &lcp_wantoptions[0].neg_mschap,
280 "Require MS-CHAPv1 authentication from peer", 1, &auth_required },
281 { "refuse-mschap", o_bool, &refuse_mschap,
282 "Don't agree to authenticate to peer with MS-CHAPv1", 1 },
283 #endif
284 #ifdef CHAPMSV2
285 { "require-mschapv2", o_bool, &lcp_wantoptions[0].neg_mschapv2,
286 "Require MS-CHAPv2 authentication from peer", 1, &auth_required },
287 { "refuse-mschapv2", o_bool, &refuse_mschapv2,
288 "Don't agree to authenticate to peer with MS-CHAPv2", 1 },
289 #endif
290 #ifdef ALLOW_PAM
291 { "pam", o_bool, &use_pam,
292 "Enable use of Pluggable Authentication Modules", OPT_PRIV|1 },
293 { "nopam", o_bool, &use_pam,
294 "Disable use of Pluggable Authentication Modules", OPT_PRIV|0 },
295 #endif
296 { NULL }
300 * setupapfile - specifies UPAP info for authenticating with peer.
302 /*ARGSUSED*/
303 static int
304 setupapfile(argv, opt)
305 char **argv;
306 option_t *opt;
308 FILE * ufile;
309 int l;
311 lcp_allowoptions[0].neg_upap = 1;
313 /* open user info file */
314 (void) seteuid(getuid());
315 ufile = fopen(*argv, "r");
316 (void) seteuid(0);
317 if (ufile == NULL) {
318 option_error("unable to open user login data file %s", *argv);
319 return 0;
321 check_access(ufile, *argv);
323 /* get username */
324 if (fgets(user, MAXNAMELEN - 1, ufile) == NULL
325 || fgets(passwd, MAXSECRETLEN - 1, ufile) == NULL){
326 option_error("unable to read user login data file %s", *argv);
327 return 0;
329 (void) fclose(ufile);
331 /* get rid of newlines */
332 l = strlen(user);
333 if (l > 0 && user[l-1] == '\n')
334 user[l-1] = '\0';
335 l = strlen(passwd);
336 if (l > 0 && passwd[l-1] == '\n')
337 passwd[l-1] = '\0';
339 return (1);
344 * privgroup - allow members of the group to have privileged access.
346 /*ARGSUSED*/
347 static int
348 privgroup(argv, opt)
349 char **argv;
350 option_t *opt;
352 struct group *g;
353 int i;
355 g = getgrnam(*argv);
356 if (g == NULL) {
357 option_error("group %s is unknown", *argv);
358 return 0;
360 for (i = 0; i < ngroups; ++i) {
361 if (groups[i] == g->gr_gid) {
362 privileged = 1;
363 break;
366 return 1;
371 * set_noauth_addr - set address(es) that can be used without authentication.
372 * Equivalent to specifying an entry like `"" * "" addr' in pap-secrets.
374 /*ARGSUSED*/
375 static int
376 set_noauth_addr(argv, opt)
377 char **argv;
378 option_t *opt;
380 char *addr = *argv;
381 int l = strlen(addr);
382 struct wordlist *wp;
384 wp = (struct wordlist *) malloc(sizeof(struct wordlist) + l + 1);
385 if (wp == NULL)
386 novm("allow-ip argument");
387 wp->word = (char *) (wp + 1);
388 wp->next = noauth_addrs;
389 (void) strcpy(wp->word, addr);
390 noauth_addrs = wp;
391 return 1;
395 * An Open on LCP has requested a change from Dead to Establish phase.
396 * Do what's necessary to bring the physical layer up.
398 /*ARGSUSED*/
399 void
400 link_required(unit)
401 int unit;
406 * LCP has terminated the link; go to the Dead phase and take the
407 * physical layer down.
409 /*ARGSUSED*/
410 void
411 link_terminated(unit)
412 int unit;
414 const char *pn1, *pn2;
416 if (phase == PHASE_DEAD)
417 return;
418 if (pap_logout_hook != NULL) {
419 (*pap_logout_hook)();
420 } else {
421 if (logged_in)
422 plogout();
424 new_phase(PHASE_DEAD);
425 if (peer_nak_auth) {
426 if ((pn1 = protocol_name(nak_auth_orig)) == NULL)
427 pn1 = "?";
428 if ((pn2 = protocol_name(nak_auth_proto)) == NULL)
429 pn2 = "?";
430 warn("Peer sent Configure-Nak for 0x%x (%s) to suggest 0x%x (%s)",
431 nak_auth_orig, pn1, nak_auth_proto, pn2);
433 if (unsolicited_nak_auth) {
434 if ((pn1 = protocol_name(unsolicit_auth_proto)) == NULL)
435 pn1 = "?";
436 warn("Peer unexpectedly asked us to authenticate with 0x%x (%s)",
437 unsolicit_auth_proto, pn1);
439 if (peer_reject_auth) {
440 if ((pn1 = protocol_name(reject_auth_proto)) == NULL)
441 pn1 = "?";
442 warn("Peer rejected our demand for 0x%x (%s)",
443 reject_auth_proto, pn1);
445 if (naked_peers_auth) {
446 if ((pn1 = protocol_name(naked_auth_orig)) == NULL)
447 pn1 = "?";
448 if ((pn2 = protocol_name(naked_auth_proto)) == NULL)
449 pn2 = "?";
450 warn("We set Configure-Nak for 0x%x (%s) to suggest 0x%x (%s)",
451 naked_auth_orig, pn1, naked_auth_proto, pn2);
453 if (rejected_peers_auth) {
454 if ((pn1 = protocol_name(rejected_auth_proto)) == NULL)
455 pn1 = "?";
456 warn("We rejected the peer's demand for 0x%x (%s)",
457 rejected_auth_proto, pn1);
460 peer_nak_auth = unsolicited_nak_auth = peer_reject_auth =
461 rejected_peers_auth = naked_peers_auth = 0;
462 nak_auth_proto = nak_auth_orig = unsolicit_auth_proto = reject_auth_proto =
463 rejected_auth_proto = naked_auth_orig = naked_auth_proto = 0;
464 notice("Connection terminated.");
468 * LCP has gone down; it will either die or try to re-establish.
470 void
471 link_down(unit)
472 int unit;
474 int i;
475 struct protent *protp;
477 auth_state = s_down;
478 if (auth_script_state == s_up && auth_script_pid == 0) {
479 update_link_stats(unit);
480 auth_script_state = s_down;
481 auth_script(_PATH_AUTHDOWN);
483 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
484 if (!protp->enabled_flag)
485 continue;
486 if (protp->protocol != PPP_LCP && protp->lowerdown != NULL)
487 (*protp->lowerdown)(unit);
488 if (protp->protocol < 0xC000 && protp->close != NULL)
489 (*protp->close)(unit, "LCP down");
491 num_np_open = 0;
492 num_np_up = 0;
493 if (phase != PHASE_DEAD)
494 new_phase(PHASE_TERMINATE);
498 * The link is established.
499 * Proceed to the Dead, Authenticate or Network phase as appropriate.
501 void
502 link_established(unit)
503 int unit;
505 int auth;
506 lcp_options *wo = &lcp_wantoptions[unit];
507 lcp_options *go = &lcp_gotoptions[unit];
508 lcp_options *ho = &lcp_hisoptions[unit];
509 int i;
510 struct protent *protp;
513 * Tell higher-level protocols that LCP is up.
515 for (i = 0; (protp = protocols[i]) != NULL; ++i)
516 if (protp->protocol != PPP_LCP && protp->enabled_flag
517 && protp->lowerup != NULL)
518 (*protp->lowerup)(unit);
520 if (auth_required && !(go->neg_chap || go->neg_mschap ||
521 go->neg_mschapv2 || go->neg_upap)) {
523 * We wanted the peer to authenticate itself, and it refused:
524 * if we have some address(es) it can use without auth, fine,
525 * otherwise treat it as though it authenticated with PAP using
526 * a username * of "" and a password of "". If that's not OK,
527 * boot it out.
529 if (noauth_addrs != NULL) {
530 set_allowed_addrs(unit, noauth_addrs, NULL);
531 } else if (!wo->neg_upap || !null_login(unit)) {
532 warn("peer refused to authenticate: terminating link");
533 lcp_close(unit, "peer refused to authenticate");
534 status = EXIT_PEER_AUTH_FAILED;
535 return;
539 new_phase(PHASE_AUTHENTICATE);
540 auth = 0;
541 if (go->neg_chap || go->neg_mschap || go->neg_mschapv2) {
542 if (go->neg_chap) {
543 if (debug)
544 dbglog("Authenticating peer with standard CHAP");
545 go->chap_mdtype = CHAP_DIGEST_MD5;
546 } else if (go->neg_mschap) {
547 if (debug)
548 dbglog("Authenticating peer with MS-CHAPv1");
549 go->chap_mdtype = CHAP_MICROSOFT;
550 } else {
551 if (debug)
552 dbglog("Authenticating peer with MS-CHAPv2");
553 go->chap_mdtype = CHAP_MICROSOFT_V2;
555 ChapAuthPeer(unit, our_name, go->chap_mdtype);
556 auth |= CHAP_PEER;
557 } else if (go->neg_upap) {
558 if (debug)
559 dbglog("Authenticating peer with PAP");
560 upap_authpeer(unit);
561 auth |= PAP_PEER;
563 if (ho->neg_chap || ho->neg_mschap || ho->neg_mschapv2) {
564 switch (ho->chap_mdtype) {
565 case CHAP_DIGEST_MD5:
566 if (debug)
567 dbglog("Authenticating to peer with standard CHAP");
568 break;
569 case CHAP_MICROSOFT:
570 if (debug)
571 dbglog("Authenticating to peer with MS-CHAPv1");
572 break;
573 case CHAP_MICROSOFT_V2:
574 if (debug)
575 dbglog("Authenticating to peer with MS-CHAPv2");
576 break;
577 default:
578 if (debug)
579 dbglog("Authenticating to peer with CHAP 0x%x", ho->chap_mdtype);
580 break;
582 ChapAuthWithPeer(unit, user, ho->chap_mdtype);
583 auth |= CHAP_WITHPEER;
584 } else if (ho->neg_upap) {
585 if (passwd[0] == '\0') {
586 passwd_from_file = 1;
587 if (!get_pap_passwd(passwd))
588 error("No secret found for PAP login");
590 if (debug)
591 dbglog("Authenticating to peer with PAP");
592 upap_authwithpeer(unit, user, passwd);
593 auth |= PAP_WITHPEER;
595 auth_pending[unit] = auth;
597 if (!auth)
598 network_phase(unit);
602 * Proceed to the network phase.
604 static void
605 network_phase(unit)
606 int unit;
608 lcp_options *go = &lcp_gotoptions[unit];
611 * If the peer had to authenticate, run the auth-up script now.
613 if (go->neg_chap || go->neg_mschap || go->neg_mschapv2 || go->neg_upap) {
614 auth_state = s_up;
615 if (auth_script_state == s_down && auth_script_pid == 0) {
616 auth_script_state = s_up;
617 auth_script(_PATH_AUTHUP);
622 * Process extra options from the secrets file
624 if (extra_options != NULL) {
625 option_source = (char *)extra_opt_filename;
626 option_line = extra_opt_line;
627 (void) options_from_list(extra_options, 1);
628 free_wordlist(extra_options);
629 extra_options = NULL;
632 #ifdef CBCP_SUPPORT
634 * If we negotiated callback, do it now.
636 if (go->neg_cbcp) {
637 new_phase(PHASE_CALLBACK);
638 (*cbcp_protent.open)(unit);
639 return;
641 #endif
643 start_networks();
646 void
647 start_networks()
649 int i;
650 struct protent *protp;
652 new_phase(PHASE_NETWORK);
654 #ifdef HAVE_MULTILINK
655 if (multilink) {
656 if (mp_join_bundle()) {
657 if (updetach && !nodetach)
658 detach();
659 return;
662 #endif /* HAVE_MULTILINK */
664 #if 0
665 if (!demand)
666 set_filters(&pass_filter, &active_filter);
667 #endif
668 for (i = 0; (protp = protocols[i]) != NULL; ++i)
669 if (protp->protocol < 0xC000 && protp->enabled_flag
670 && protp->open != NULL) {
671 (*protp->open)(0);
672 if (protp->protocol != PPP_CCP)
673 ++num_np_open;
676 if (num_np_open == 0)
677 /* nothing to do */
678 lcp_close(0, "No network protocols running");
682 * The peer has failed to authenticate himself using `protocol'.
684 /*ARGSUSED*/
685 void
686 auth_peer_fail(unit, protocol)
687 int unit, protocol;
690 * Authentication failure: take the link down
692 lcp_close(unit, "Authentication failed");
693 status = EXIT_PEER_AUTH_FAILED;
697 * The peer has been successfully authenticated using `protocol'.
699 void
700 auth_peer_success(unit, protocol, name, namelen)
701 int unit, protocol;
702 char *name;
703 int namelen;
705 int bit;
707 switch (protocol) {
708 case PPP_CHAP:
709 bit = CHAP_PEER;
710 break;
711 case PPP_PAP:
712 bit = PAP_PEER;
713 break;
714 default:
715 warn("auth_peer_success: unknown protocol %x", protocol);
716 return;
720 * Save the authenticated name of the peer for later.
722 if (namelen > sizeof(peer_authname) - 1)
723 namelen = sizeof(peer_authname) - 1;
724 BCOPY(name, peer_authname, namelen);
725 peer_authname[namelen] = '\0';
726 script_setenv("PEERNAME", peer_authname, 0);
729 * If there is no more authentication still to be done,
730 * proceed to the network (or callback) phase.
732 if ((auth_pending[unit] &= ~bit) == 0)
733 network_phase(unit);
737 * We have failed to authenticate ourselves to the peer using `protocol'.
739 /*ARGSUSED*/
740 void
741 auth_withpeer_fail(unit, protocol)
742 int unit, protocol;
744 if (passwd_from_file)
745 BZERO(passwd, MAXSECRETLEN);
747 * We've failed to authenticate ourselves to our peer.
748 * Some servers keep sending CHAP challenges, but there
749 * is no point in persisting without any way to get updated
750 * authentication secrets.
752 lcp_close(unit, "Failed to authenticate ourselves to peer");
753 status = EXIT_AUTH_TOPEER_FAILED;
757 * We have successfully authenticated ourselves with the peer using `protocol'.
759 void
760 auth_withpeer_success(unit, protocol)
761 int unit, protocol;
763 int bit;
765 switch (protocol) {
766 case PPP_CHAP:
767 bit = CHAP_WITHPEER;
768 break;
769 case PPP_PAP:
770 if (passwd_from_file)
771 BZERO(passwd, MAXSECRETLEN);
772 bit = PAP_WITHPEER;
773 break;
774 default:
775 warn("auth_withpeer_success: unknown protocol %x", protocol);
776 bit = 0;
780 * If there is no more authentication still being done,
781 * proceed to the network (or callback) phase.
783 if ((auth_pending[unit] &= ~bit) == 0)
784 network_phase(unit);
789 * np_up - a network protocol has come up.
791 /*ARGSUSED*/
792 void
793 np_up(unit, proto)
794 int unit, proto;
796 int tlim;
798 if (num_np_up == 0) {
800 * At this point we consider that the link has come up successfully.
802 status = EXIT_OK;
803 unsuccess = 0;
805 peer_nak_auth = unsolicited_nak_auth = peer_reject_auth =
806 rejected_peers_auth = naked_peers_auth = 0;
807 nak_auth_proto = nak_auth_orig = unsolicit_auth_proto =
808 reject_auth_proto = rejected_auth_proto = naked_auth_orig =
809 naked_auth_proto = 0;
811 new_phase(PHASE_RUNNING);
813 if (idle_time_hook != NULL)
814 tlim = (*idle_time_hook)(NULL);
815 else
816 tlim = idle_time_limit;
817 if (tlim > 0)
818 TIMEOUT(check_idle, NULL, tlim);
821 * Set a timeout to close the connection once the maximum
822 * connect time has expired.
824 if (maxconnect > 0) {
825 TIMEOUT(connect_time_expired, &lcp_fsm[unit], maxconnect);
828 * Tell LCP to send Time-Remaining packets. One should be
829 * sent out now, at maxconnect-300, at maxconnect-120, and
830 * again at maxconnect-30.
832 lcp_settimeremaining(unit, maxconnect, maxconnect);
833 if (maxconnect > 300)
834 lcp_settimeremaining(unit, maxconnect, 300);
835 if (maxconnect > 120)
836 lcp_settimeremaining(unit, maxconnect, 120);
837 if (maxconnect > 30)
838 lcp_settimeremaining(unit, maxconnect, 30);
842 * Detach now, if the updetach option was given.
844 if (updetach && !nodetach)
845 detach();
847 ++num_np_up;
851 * np_down - a network protocol has gone down.
853 /*ARGSUSED*/
854 void
855 np_down(unit, proto)
856 int unit, proto;
858 if (--num_np_up == 0) {
859 UNTIMEOUT(check_idle, NULL);
860 new_phase(PHASE_NETWORK);
865 * np_finished - a network protocol has finished using the link.
867 /*ARGSUSED*/
868 void
869 np_finished(unit, proto)
870 int unit, proto;
872 if (--num_np_open <= 0) {
873 /* no further use for the link: shut up shop. */
874 lcp_close(0, "No network protocols running");
879 * check_idle - check whether the link has been idle for long
880 * enough that we can shut it down.
882 /*ARGSUSED*/
883 static void
884 check_idle(arg)
885 void *arg;
887 struct ppp_idle idle;
888 time_t itime;
889 int tlim;
891 if (!get_idle_time(0, &idle))
892 return;
893 if (idle_time_hook != NULL) {
894 tlim = (*idle_time_hook)(&idle);
895 } else {
896 itime = MIN(idle.xmit_idle, idle.recv_idle);
897 tlim = idle_time_limit - itime;
899 if (tlim <= 0) {
900 /* link is idle: shut it down. */
901 notice("Terminating connection due to lack of activity.");
902 lcp_close(0, "Link inactive");
903 need_holdoff = 0;
904 status = EXIT_IDLE_TIMEOUT;
905 } else {
906 TIMEOUT(check_idle, NULL, tlim);
911 * connect_time_expired - log a message and close the connection.
913 /*ARGSUSED*/
914 static void
915 connect_time_expired(arg)
916 void *arg;
918 fsm *f = (fsm *)arg;
920 info("Connect time expired");
921 lcp_close(f->unit, "Connect time expired"); /* Close connection */
922 status = EXIT_CONNECT_TIME;
926 * auth_check_options - called to check authentication options.
928 void
929 auth_check_options()
931 lcp_options *wo = &lcp_wantoptions[0];
932 int can_auth;
933 int lacks_ip;
935 /* Default our_name to hostname, and user to our_name */
936 if (our_name[0] == '\0' || usehostname)
937 (void) strlcpy(our_name, hostname, sizeof(our_name));
938 if (user[0] == '\0')
939 (void) strlcpy(user, our_name, sizeof(user));
942 * If we have a default route, require the peer to authenticate
943 * unless the noauth option was given or the real user is root.
945 if (!auth_required && !allow_any_ip && have_route_to(0) && !privileged) {
946 auth_required = 1;
947 default_auth = 1;
950 /* If authentication is required, ask peer for CHAP or PAP. */
951 if (auth_required) {
952 if (!wo->neg_chap && !wo->neg_mschap && !wo->neg_mschapv2 &&
953 !wo->neg_upap) {
954 wo->neg_chap = 1;
955 #ifdef CHAPMS
956 wo->neg_mschap = 1;
957 #endif
958 #ifdef CHAPMSV2
959 wo->neg_mschapv2 = 1;
960 #endif
961 wo->chap_mdtype = CHAP_DIGEST_MD5;
962 wo->neg_upap = 1;
964 } else {
965 wo->neg_chap = 0;
966 wo->neg_mschap = 0;
967 wo->neg_mschapv2 = 0;
968 wo->neg_upap = 0;
972 * Check whether we have appropriate secrets to use
973 * to authenticate the peer.
975 lacks_ip = 0;
976 can_auth = wo->neg_upap && (uselogin || have_pap_secret(&lacks_ip));
977 if (!can_auth && (wo->neg_chap || wo->neg_mschap || wo->neg_mschapv2)) {
978 can_auth = have_chap_secret((explicit_remote? remote_name: NULL),
979 our_name, 1, &lacks_ip);
982 if (auth_required && !can_auth && noauth_addrs == NULL) {
983 if (default_auth) {
984 option_error(
985 "By default the remote system is required to authenticate itself");
986 option_error(
987 "(because this system has a default route to the Internet)");
988 } else if (explicit_remote)
989 option_error(
990 "The remote system (%s) is required to authenticate itself",
991 remote_name);
992 else
993 option_error(
994 "The remote system is required to authenticate itself");
995 option_error(
996 "but I couldn't find any suitable secret (password) for it to use to do so.");
997 if (lacks_ip)
998 option_error(
999 "(None of the available passwords would let it use an IP address.)");
1001 exit(1);
1006 * auth_reset - called when LCP is starting negotiations to recheck
1007 * authentication options, i.e. whether we have appropriate secrets
1008 * to use for authenticating ourselves and/or the peer.
1010 void
1011 auth_reset(unit)
1012 int unit;
1014 lcp_options *go = &lcp_gotoptions[unit];
1015 lcp_options *ao = &lcp_allowoptions[unit];
1016 int havesecret;
1018 ao->neg_upap = !refuse_pap && (passwd[0] != '\0' || get_pap_passwd(NULL));
1020 havesecret = passwd[0] != '\0' ||
1021 have_chap_secret(user, (explicit_remote? remote_name: NULL), 0, NULL);
1022 ao->neg_chap = !refuse_chap && havesecret;
1023 ao->neg_mschap = !refuse_mschap && havesecret;
1024 ao->neg_mschapv2 = !refuse_mschapv2 && havesecret;
1025 if (ao->neg_chap)
1026 ao->chap_mdtype = CHAP_DIGEST_MD5;
1027 else if (ao->neg_mschap)
1028 ao->chap_mdtype = CHAP_MICROSOFT;
1029 else
1030 ao->chap_mdtype = CHAP_MICROSOFT_V2;
1032 if (go->neg_upap && !uselogin && !have_pap_secret(NULL))
1033 go->neg_upap = 0;
1034 if (go->neg_chap || go->neg_mschap || go->neg_mschapv2) {
1035 havesecret = have_chap_secret((explicit_remote? remote_name: NULL),
1036 our_name, 1, NULL);
1037 if (!havesecret)
1038 go->neg_chap = go->neg_mschap = go->neg_mschapv2 = 0;
1039 else if (go->neg_chap)
1040 go->chap_mdtype = CHAP_DIGEST_MD5;
1041 else if (go->neg_mschap)
1042 go->chap_mdtype = CHAP_MICROSOFT;
1043 else
1044 go->chap_mdtype = CHAP_MICROSOFT_V2;
1050 * check_passwd - Check the user name and passwd against the PAP secrets
1051 * file. If requested, also check against the system password database,
1052 * and login the user if OK.
1054 * returns:
1055 * UPAP_AUTHNAK: Authentication failed.
1056 * UPAP_AUTHACK: Authentication succeeded.
1057 * In either case, msg points to an appropriate message.
1060 check_passwd(unit, auser, userlen, apasswd, passwdlen, msg)
1061 int unit;
1062 char *auser;
1063 int userlen;
1064 char *apasswd;
1065 int passwdlen;
1066 char **msg;
1068 int ret;
1069 char *filename;
1070 FILE *f;
1071 struct wordlist *addrs = NULL, *opts = NULL;
1072 char passwd[256], user[256];
1073 char secret[MAXWORDLEN];
1074 static int attempts = 0;
1077 * Make copies of apasswd and auser, then null-terminate them.
1078 * If there are unprintable characters in the password, make
1079 * them visible.
1081 (void) slprintf(passwd, sizeof(passwd), "%.*v", passwdlen, apasswd);
1082 (void) slprintf(user, sizeof(user), "%.*v", userlen, auser);
1083 *msg = "";
1086 * Check if a plugin wants to handle this.
1088 if (pap_auth_hook != NULL) {
1089 /* Set a default and allow the plug-in to change it. */
1090 extra_opt_filename = "plugin";
1091 extra_opt_line = 0;
1092 ret = (*pap_auth_hook)(user, passwd, msg, &addrs, &opts);
1093 if (ret >= 0) {
1094 if (ret > 0)
1095 set_allowed_addrs(unit, addrs, opts);
1096 BZERO(passwd, sizeof(passwd));
1097 if (addrs != NULL)
1098 free_wordlist(addrs);
1099 return ret? UPAP_AUTHACK: UPAP_AUTHNAK;
1104 * Open the file of pap secrets and scan for a suitable secret
1105 * for authenticating this user.
1107 filename = _PATH_UPAPFILE;
1108 addrs = opts = NULL;
1109 ret = UPAP_AUTHNAK;
1110 f = fopen(filename, "r");
1111 if (f == NULL) {
1112 error("Can't open PAP password file %s: %m", filename);
1114 } else {
1115 check_access(f, filename);
1116 if (scan_authfile(f, user, our_name, secret, &addrs, &opts, filename) < 0) {
1117 warn("no PAP secret found for %s", user);
1118 if (scan_server_match_failed[0] != '\0')
1119 warn("possible configuration error: local name is %q, but "
1120 "found %q instead", our_name, scan_server_match_failed);
1121 } else if (secret[0] != '\0') {
1122 /* password given in pap-secrets - must match */
1123 if ((!cryptpap && strcmp(passwd, secret) == 0)
1124 || strcmp(crypt(passwd, secret), secret) == 0)
1125 ret = UPAP_AUTHACK;
1126 else
1127 warn("PAP authentication failure for %s", user);
1128 } else if (uselogin) {
1129 /* empty password in pap-secrets and login option */
1130 ret = plogin(user, passwd, msg);
1131 if (ret == UPAP_AUTHNAK)
1132 warn("PAP login failure for %s", user);
1133 } else {
1134 /* empty password in pap-secrets and login option not used */
1135 ret = UPAP_AUTHACK;
1137 (void) fclose(f);
1140 if (ret == UPAP_AUTHNAK) {
1141 if (**msg == '\0')
1142 *msg = "Login incorrect";
1144 * Frustrate passwd stealer programs.
1145 * Allow 10 tries, but start backing off after 3 (stolen from login).
1146 * On 10'th, drop the connection.
1148 if (attempts++ >= 10) {
1149 warn("%d LOGIN FAILURES ON %s, %s", attempts, devnam, user);
1150 lcp_close(unit, "login failed");
1152 if (attempts > 3)
1153 (void) sleep((u_int) (attempts - 3) * 5);
1154 if (opts != NULL)
1155 free_wordlist(opts);
1157 } else {
1158 attempts = 0; /* Reset count */
1159 if (**msg == '\0')
1160 *msg = "Login ok";
1161 set_allowed_addrs(unit, addrs, opts);
1164 if (addrs != NULL)
1165 free_wordlist(addrs);
1166 BZERO(passwd, sizeof(passwd));
1167 BZERO(secret, sizeof(secret));
1169 return ret;
1173 * This function is needed for PAM.
1176 #ifdef ALLOW_PAM
1177 /* Static variables used to communicate between the conversation function
1178 * and the server_login function
1180 static char *PAM_username;
1181 static char *PAM_password;
1182 static int PAM_error = 0;
1183 static pam_handle_t *pamh = NULL;
1185 /* PAM conversation function
1186 * Here we assume (for now, at least) that echo on means login name, and
1187 * echo off means password.
1190 /*ARGSUSED*/
1191 static int PAM_conv (int num_msg,
1192 #ifndef SOL2
1193 const
1194 #endif
1195 struct pam_message **msg, struct pam_response **resp, void *appdata_ptr)
1197 int replies = 0;
1198 struct pam_response *reply = NULL;
1200 #define COPY_STRING(s) (s) ? strdup(s) : NULL
1202 reply = malloc(sizeof(struct pam_response) * num_msg);
1203 if (reply == NULL)
1204 return PAM_CONV_ERR;
1206 for (replies = 0; replies < num_msg; replies++) {
1207 switch (msg[replies]->msg_style) {
1208 case PAM_PROMPT_ECHO_ON:
1209 reply[replies].resp_retcode = PAM_SUCCESS;
1210 reply[replies].resp = COPY_STRING(PAM_username);
1211 /* PAM frees resp */
1212 break;
1213 case PAM_PROMPT_ECHO_OFF:
1214 reply[replies].resp_retcode = PAM_SUCCESS;
1215 reply[replies].resp = COPY_STRING(PAM_password);
1216 /* PAM frees resp */
1217 break;
1218 case PAM_TEXT_INFO:
1219 /* fall through */
1220 case PAM_ERROR_MSG:
1221 /* ignore it, but pam still wants a NULL response... */
1222 reply[replies].resp_retcode = PAM_SUCCESS;
1223 reply[replies].resp = NULL;
1224 break;
1225 default:
1226 /* Must be an error of some sort... */
1227 free (reply);
1228 PAM_error = 1;
1229 return PAM_CONV_ERR;
1232 *resp = reply;
1233 return PAM_SUCCESS;
1236 static struct pam_conv PAM_conversation = {
1237 PAM_conv, NULL
1239 #endif /* ALLOW_PAM */
1242 * plogin - Check the user name and password against the system
1243 * password database, and login the user if OK.
1245 * returns:
1246 * UPAP_AUTHNAK: Login failed.
1247 * UPAP_AUTHACK: Login succeeded.
1248 * In either case, msg points to an appropriate message.
1251 static int
1252 plogin(user, passwd, msg)
1253 char *user;
1254 char *passwd;
1255 char **msg;
1257 char *tty;
1258 #ifdef HAS_SHADOW
1259 struct spwd *spwd;
1260 #endif
1261 struct passwd *pw = NULL;
1263 #ifdef ALLOW_PAM
1264 int pam_error;
1266 if (use_pam) {
1267 if (debug)
1268 dbglog("using PAM for user authentication");
1269 pam_error = pam_start ("ppp", user, &PAM_conversation, &pamh);
1270 if (pam_error != PAM_SUCCESS) {
1271 *msg = (char *) pam_strerror (pamh, pam_error);
1272 reopen_log();
1273 return UPAP_AUTHNAK;
1276 * Define the fields for the credential validation
1279 PAM_username = user;
1280 PAM_password = passwd;
1281 PAM_error = 0;
1282 /* this might be useful to some modules; required for Solaris */
1283 tty = devnam;
1284 if (*tty == '\0')
1285 tty = ppp_devnam;
1286 (void) pam_set_item(pamh, PAM_TTY, tty);
1287 #ifdef PAM_RHOST
1288 (void) pam_set_item(pamh, PAM_RHOST, "");
1289 #endif
1292 * Validate the user
1294 pam_error = pam_authenticate (pamh, PAM_SILENT);
1295 if (pam_error == PAM_SUCCESS && !PAM_error) {
1296 pam_error = pam_acct_mgmt (pamh, PAM_SILENT);
1297 if (pam_error == PAM_SUCCESS)
1298 (void) pam_open_session (pamh, PAM_SILENT);
1301 *msg = (char *) pam_strerror (pamh, pam_error);
1304 * Clean up the mess
1306 reopen_log(); /* apparently the PAM stuff does closelog() */
1307 PAM_username = NULL;
1308 PAM_password = NULL;
1309 if (pam_error != PAM_SUCCESS)
1310 return UPAP_AUTHNAK;
1311 } else
1312 #endif /* ALLOW_PAM */
1315 if (debug) {
1316 #ifdef HAS_SHADOW
1317 dbglog("using passwd/shadow for user authentication");
1318 #else
1319 dbglog("using passwd for user authentication");
1320 #endif
1323 * Use the non-PAM methods directly
1326 pw = getpwnam(user);
1328 endpwent();
1329 if (pw == NULL)
1330 return (UPAP_AUTHNAK);
1332 #ifdef HAS_SHADOW
1333 spwd = getspnam(user);
1334 endspent();
1335 if (spwd != NULL) {
1336 /* check the age of the password entry */
1337 long now = time(NULL) / 86400L;
1339 if ((spwd->sp_expire > 0 && now >= spwd->sp_expire)
1340 || ((spwd->sp_max >= 0 && spwd->sp_max < 10000)
1341 && spwd->sp_lstchg >= 0
1342 && now >= spwd->sp_lstchg + spwd->sp_max)) {
1343 warn("Password for %s has expired", user);
1344 return (UPAP_AUTHNAK);
1346 pw->pw_passwd = spwd->sp_pwdp;
1348 #endif
1351 * If no passwd, don't let them login.
1353 if (pw->pw_passwd == NULL || strlen(pw->pw_passwd) < 2 ||
1354 strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd) != 0)
1355 return (UPAP_AUTHNAK);
1359 * Write a wtmp entry for this user.
1362 tty = devnam;
1363 if (strncmp(tty, "/dev/", 5) == 0)
1364 tty += 5;
1365 logwtmp(tty, user, remote_name); /* Add wtmp login entry */
1367 info("user %s logged in", user);
1368 logged_in = 1;
1370 return (UPAP_AUTHACK);
1374 * plogout - Logout the user.
1376 static void
1377 plogout()
1379 char *tty;
1381 #ifdef ALLOW_PAM
1382 int pam_error;
1384 if (use_pam) {
1385 if (pamh != NULL) {
1386 pam_error = pam_close_session (pamh, PAM_SILENT);
1387 (void) pam_end (pamh, pam_error);
1388 pamh = NULL;
1390 /* Apparently the pam stuff does closelog(). */
1391 reopen_log();
1392 } else
1393 #endif /* ALLOW_PAM */
1396 tty = devnam;
1397 if (strncmp(tty, "/dev/", 5) == 0)
1398 tty += 5;
1399 /* Wipe out utmp logout entry */
1400 logwtmp(tty, "", "");
1402 logged_in = 0;
1407 * null_login - Check if a username of "" and a password of "" are
1408 * acceptable, and iff so, set the list of acceptable IP addresses
1409 * and return 1.
1411 static int
1412 null_login(unit)
1413 int unit;
1415 char *filename;
1416 FILE *f;
1417 int i, ret;
1418 struct wordlist *addrs, *opts;
1419 char secret[MAXWORDLEN];
1422 * Open the file of pap secrets and scan for a suitable secret.
1424 filename = _PATH_UPAPFILE;
1425 addrs = NULL;
1426 f = fopen(filename, "r");
1427 if (f == NULL)
1428 return 0;
1429 check_access(f, filename);
1431 i = scan_authfile(f, "", our_name, secret, &addrs, &opts, filename);
1432 ret = i >= 0 && secret[0] == '\0';
1433 BZERO(secret, sizeof(secret));
1435 if (ret)
1436 set_allowed_addrs(unit, addrs, opts);
1437 else if (opts != NULL)
1438 free_wordlist(opts);
1439 if (addrs != NULL)
1440 free_wordlist(addrs);
1442 (void) fclose(f);
1443 return ret;
1448 * get_pap_passwd - get a password for authenticating ourselves with
1449 * our peer using PAP. Returns 1 on success, 0 if no suitable password
1450 * could be found.
1451 * Assumes passwd points to MAXSECRETLEN bytes of space (if non-null).
1453 static int
1454 get_pap_passwd(passwd)
1455 char *passwd;
1457 char *filename;
1458 FILE *f;
1459 int ret;
1460 char secret[MAXWORDLEN];
1463 * Check whether a plugin wants to supply this.
1465 if (pap_passwd_hook != NULL) {
1466 ret = (*pap_passwd_hook)(user, passwd);
1467 if (ret >= 0)
1468 return ret;
1471 filename = _PATH_UPAPFILE;
1472 f = fopen(filename, "r");
1473 if (f == NULL)
1474 return 0;
1475 check_access(f, filename);
1476 ret = scan_authfile(f, user,
1477 (remote_name[0] != '\0' ? remote_name: NULL),
1478 secret, NULL, NULL, filename);
1479 (void) fclose(f);
1480 if (ret < 0)
1481 return 0;
1482 if (passwd != NULL)
1483 (void) strlcpy(passwd, secret, MAXSECRETLEN);
1484 BZERO(secret, sizeof(secret));
1485 return 1;
1490 * have_pap_secret - check whether we have a PAP file with any
1491 * secrets that we could possibly use for authenticating the peer.
1493 static int
1494 have_pap_secret(lacks_ipp)
1495 int *lacks_ipp;
1497 FILE *f;
1498 int ret;
1499 char *filename;
1500 struct wordlist *addrs;
1502 /* let the plugin decide, if there is one */
1503 if (pap_check_hook != NULL) {
1504 ret = (*pap_check_hook)();
1505 if (ret >= 0)
1506 return ret;
1509 filename = _PATH_UPAPFILE;
1510 f = fopen(filename, "r");
1511 if (f == NULL)
1512 return 0;
1514 ret = scan_authfile(f, (explicit_remote? remote_name: NULL), our_name,
1515 NULL, &addrs, NULL, filename);
1516 (void) fclose(f);
1517 if (ret >= 0 && !some_ip_ok(addrs)) {
1518 if (lacks_ipp != NULL)
1519 *lacks_ipp = 1;
1520 ret = -1;
1522 if (addrs != NULL)
1523 free_wordlist(addrs);
1525 return ret >= 0;
1530 * have_chap_secret - check whether we have a CHAP file with a secret
1531 * that we could possibly use for authenticating `client' on `server'.
1532 * Either or both can be the null string, meaning we don't know the
1533 * identity yet.
1535 static int
1536 have_chap_secret(client, server, need_ip, lacks_ipp)
1537 char *client;
1538 char *server;
1539 int need_ip;
1540 int *lacks_ipp;
1542 FILE *f;
1543 int ret;
1544 char *filename;
1545 struct wordlist *addrs;
1547 filename = _PATH_CHAPFILE;
1548 f = fopen(filename, "r");
1549 if (f == NULL)
1550 return 0;
1552 if (client != NULL && client[0] == '\0')
1553 client = NULL;
1554 if (server != NULL && server[0] == '\0')
1555 server = NULL;
1557 ret = scan_authfile(f, client, server, NULL, &addrs, NULL, filename);
1558 (void) fclose(f);
1559 if (ret >= 0 && need_ip && !some_ip_ok(addrs)) {
1560 if (lacks_ipp != NULL)
1561 *lacks_ipp = 1;
1562 ret = -1;
1564 if (addrs != NULL)
1565 free_wordlist(addrs);
1567 return ret >= 0;
1572 * get_secret - open the CHAP secret file and return the secret
1573 * for authenticating the given client on the given server.
1575 * "am_server" means that we're the authenticator (demanding
1576 * identity from the peer).
1578 * "!am_server" means that we're the authenticatee (supplying
1579 * identity to the peer).
1582 get_secret(unit, client, server, secret, secret_len, am_server)
1583 int unit;
1584 char *client;
1585 char *server;
1586 char *secret;
1587 int *secret_len;
1588 int am_server;
1590 FILE *f;
1591 int ret, len;
1592 char *filename;
1593 struct wordlist *addrs, *opts;
1594 char secbuf[MAXWORDLEN];
1597 * Support the 'password' option on authenticatee only in order to
1598 * avoid obvious security problem (authenticator and authenticatee
1599 * within a given implementation must never share secrets).
1601 if (!am_server && passwd[0] != '\0') {
1602 (void) strlcpy(secbuf, passwd, sizeof(secbuf));
1603 } else {
1604 filename = _PATH_CHAPFILE;
1605 addrs = NULL;
1606 secbuf[0] = '\0';
1608 f = fopen(filename, "r");
1609 if (f == NULL) {
1610 error("Can't open chap secret file %s: %m", filename);
1611 return 0;
1613 check_access(f, filename);
1615 ret = scan_authfile(f, client, server, secbuf, &addrs, &opts,
1616 filename);
1617 (void) fclose(f);
1618 if (ret < 0) {
1619 if (scan_server_match_failed[0] != '\0')
1620 warn("possible configuration error: local name is %q, but "
1621 "found %q instead", our_name, scan_server_match_failed);
1622 return 0;
1625 /* Only the authenticator cares about limiting peer addresses. */
1626 if (am_server)
1627 set_allowed_addrs(unit, addrs, opts);
1628 else if (opts != NULL)
1629 free_wordlist(opts);
1630 if (addrs != NULL)
1631 free_wordlist(addrs);
1634 len = strlen(secbuf);
1635 if (len > MAXSECRETLEN) {
1636 error("Secret for %s on %s is too long", client, server);
1637 len = MAXSECRETLEN;
1639 /* Do not leave a temporary copy of the secret on the stack. */
1640 BCOPY(secbuf, secret, len);
1641 BZERO(secbuf, sizeof(secbuf));
1642 *secret_len = len;
1644 return 1;
1648 * set_allowed_addrs() - set the list of allowed addresses.
1649 * The caller must also look for `--' indicating options to apply for
1650 * this peer and leaves the following words in extra_options.
1652 static void
1653 set_allowed_addrs(unit, addrs, opts)
1654 int unit;
1655 struct wordlist *addrs;
1656 struct wordlist *opts;
1658 int n;
1659 struct wordlist *ap, **pap;
1660 struct permitted_ip *ip;
1661 char *ptr_word, *ptr_mask;
1662 struct hostent *hp;
1663 struct netent *np;
1664 u_int32_t a, mask, newmask, ah, offset;
1665 struct ipcp_options *wo = &ipcp_wantoptions[unit];
1666 u_int32_t suggested_ip = 0;
1667 int err_num;
1669 free(addresses[unit]);
1670 addresses[unit] = NULL;
1671 if (extra_options != NULL)
1672 free_wordlist(extra_options);
1673 extra_options = opts;
1676 * Count the number of IP addresses given.
1678 for (n = 0, pap = &addrs; (ap = *pap) != NULL; pap = &ap->next)
1679 ++n;
1680 if (n == 0)
1681 return;
1682 ip = (struct permitted_ip *) malloc((n + 1) * sizeof(struct permitted_ip));
1683 if (ip == NULL)
1684 return;
1686 n = 0;
1687 for (ap = addrs; ap != NULL; ap = ap->next) {
1688 /* "-" means no addresses authorized, "*" means any address allowed */
1689 ptr_word = ap->word;
1690 if (strcmp(ptr_word, "-") == 0)
1691 break;
1692 if (strcmp(ptr_word, "*") == 0) {
1693 ip[n].permit = 1;
1694 ip[n].base = ip[n].mask = 0;
1695 ++n;
1696 break;
1699 ip[n].permit = 1;
1700 if (*ptr_word == '!') {
1701 ip[n].permit = 0;
1702 ++ptr_word;
1705 mask = ~ (u_int32_t) 0;
1706 offset = 0;
1707 ptr_mask = strchr (ptr_word, '/');
1708 if (ptr_mask != NULL) {
1709 int bit_count;
1710 char *endp;
1712 bit_count = (int) strtol (ptr_mask+1, &endp, 10);
1713 if (bit_count <= 0 || bit_count > 32) {
1714 warn("invalid address length %v in authorized address list",
1715 ptr_mask+1);
1716 continue;
1718 bit_count = 32 - bit_count; /* # bits in host part */
1719 if (*endp == '+') {
1720 offset = ifunit + 1;
1721 ++endp;
1723 if (*endp != '\0') {
1724 warn("invalid address length syntax: %v", ptr_mask+1);
1725 continue;
1727 *ptr_mask = '\0';
1728 mask <<= bit_count;
1731 /* Try to interpret value as host name or numeric address first */
1732 hp = getipnodebyname(ptr_word, AF_INET, 0, &err_num);
1733 if (hp != NULL) {
1734 (void) memcpy(&a, hp->h_addr, sizeof(a));
1735 freehostent(hp);
1736 } else {
1737 char *cp = ptr_word + strlen(ptr_word);
1738 if (cp > ptr_word)
1739 cp--;
1740 if (*cp == '+') {
1741 offset = ifunit + 1;
1742 *cp = '\0';
1744 np = getnetbyname (ptr_word);
1745 if (np != NULL && np->n_addrtype == AF_INET) {
1746 ah = np->n_net;
1747 newmask = (u_int32_t)~0;
1748 if ((ah & 0xff000000ul) == 0)
1749 ah <<= 8, newmask <<= 8;
1750 if ((ah & 0xff000000ul) == 0)
1751 ah <<= 8, newmask <<= 8;
1752 if ((ah & 0xff000000ul) == 0)
1753 ah <<= 8, newmask <<= 8;
1754 if (ptr_mask == NULL)
1755 mask = newmask;
1756 a = htonl(ah);
1760 if (ptr_mask != NULL)
1761 *ptr_mask = '/';
1763 if (a == (u_int32_t)-1L) {
1764 warn("unknown host %s in auth. address list", ap->word);
1765 continue;
1767 if (offset != 0) {
1768 if (offset >= ~mask) {
1769 warn("interface unit %d too large for subnet %v",
1770 ifunit, ptr_word);
1771 continue;
1773 a = htonl((ntohl(a) & mask) + offset);
1774 mask = ~(u_int32_t)0;
1776 ip[n].mask = htonl(mask);
1777 ip[n].base = a & ip[n].mask;
1778 ++n;
1779 if (~mask == 0 && suggested_ip == 0)
1780 suggested_ip = a;
1783 /* Sentinel value at end of list */
1784 ip[n].permit = 0; /* make the last entry forbid all addresses */
1785 ip[n].base = 0; /* to terminate the list */
1786 ip[n].mask = 0;
1788 addresses[unit] = ip;
1791 * If the address given for the peer isn't authorized, or if
1792 * the user hasn't given one, AND there is an authorized address
1793 * which is a single host, then use that if we find one.
1795 if (suggested_ip != 0
1796 && (wo->hisaddr == 0 || !auth_ip_addr(unit, wo->hisaddr)))
1797 wo->hisaddr = suggested_ip;
1801 * auth_ip_addr - check whether the peer is authorized to use
1802 * a given IP address. Returns 1 if authorized, 0 otherwise.
1805 auth_ip_addr(unit, addr)
1806 int unit;
1807 u_int32_t addr;
1809 int ok;
1811 /* don't allow loopback or multicast address */
1812 if (bad_ip_adrs(addr))
1813 return 0;
1815 if (addresses[unit] != NULL) {
1816 ok = ip_addr_check(addr, addresses[unit]);
1817 if (ok >= 0)
1818 return ok;
1820 if (auth_required)
1821 return 0; /* no addresses authorized */
1822 return allow_any_ip || privileged || !have_route_to(addr);
1825 static int
1826 ip_addr_check(addr, addrs)
1827 u_int32_t addr;
1828 struct permitted_ip *addrs;
1830 /* This loop is safe because of the sentinel value in set_allowed_addrs */
1831 for (; ; ++addrs)
1832 if ((addr & addrs->mask) == addrs->base)
1833 return addrs->permit;
1837 * bad_ip_adrs - return 1 if the IP address is one we don't want
1838 * to use, such as an address in the loopback net or a multicast address.
1839 * addr is in network byte order.
1842 bad_ip_adrs(addr)
1843 u_int32_t addr;
1845 addr = ntohl(addr);
1846 return
1847 #ifndef ALLOW_127_NET
1848 (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
1849 #endif
1850 #ifndef ALLOW_0_NET
1851 ((addr >> IN_CLASSA_NSHIFT) == 0 && addr != 0) ||
1852 #endif
1853 IN_MULTICAST(addr);
1857 * some_ip_ok - check a wordlist to see if it authorizes any
1858 * IP address(es).
1860 static int
1861 some_ip_ok(addrs)
1862 struct wordlist *addrs;
1864 for (; addrs != NULL; addrs = addrs->next) {
1865 if (addrs->word[0] == '-')
1866 break;
1867 if (addrs->word[0] != '!')
1868 return 1; /* some IP address is allowed */
1870 return 0;
1874 * check_access - complain if a secret file has too-liberal permissions.
1876 static void
1877 check_access(f, filename)
1878 FILE *f;
1879 char *filename;
1881 struct stat sbuf;
1883 if (fstat(fileno(f), &sbuf) < 0) {
1884 warn("cannot stat secret file %s: %m", filename);
1885 } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1886 warn("Warning - secret file %s has world and/or group access",
1887 filename);
1893 * scan_authfile - Scan an authorization file for a secret suitable
1894 * for authenticating `client' on `server'. The return value is -1 if
1895 * no secret is found, otherwise >= 0. The return value has
1896 * NONWILD_CLIENT set if the secret didn't have "*" for the client,
1897 * and NONWILD_SERVER set if the secret didn't have "*" for the
1898 * server.
1900 * Any following words on the line up to a "--" (i.e. address
1901 * authorization info) are placed in a wordlist and returned in
1902 * *addrs. Any following words (extra options) are placed in a
1903 * wordlist and returned in *opts. If opts is NULL, these are just
1904 * discarded. Otherwise, the extra_opt_* variables are set to
1905 * indicate the source of the options.
1907 * We assume secret is NULL or points to MAXWORDLEN bytes of space.
1909 static int
1910 scan_authfile(f, client, server, secret, addrs, opts, filename)
1911 FILE *f;
1912 char *client;
1913 char *server;
1914 char *secret;
1915 struct wordlist **addrs;
1916 struct wordlist **opts;
1917 char *filename;
1919 int newline, xxx, sline;
1920 int got_flag, best_flag;
1921 FILE *sf;
1922 struct wordlist *ap, *addr_list, *alist, **app;
1923 char word[MAXWORDLEN];
1924 char atfile[MAXWORDLEN];
1925 char lsecret[MAXWORDLEN];
1927 scan_server_match_failed[0] = '\0';
1929 if (addrs != NULL)
1930 *addrs = NULL;
1931 if (opts != NULL)
1932 *opts = NULL;
1933 addr_list = NULL;
1934 option_line = 0;
1935 if (!getword(f, word, &newline, filename)) {
1936 if (debug)
1937 dbglog("%s is apparently empty", filename);
1938 return -1; /* file is empty??? */
1940 newline = 1;
1941 best_flag = -1;
1942 for (;;) {
1944 * Skip until we find a word at the start of a line.
1946 while (!newline && getword(f, word, &newline, filename))
1948 if (!newline)
1949 break; /* got to end of file */
1951 sline = option_line;
1953 * Got a client - check if it's a match or a wildcard.
1955 got_flag = 0;
1956 if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
1957 newline = 0;
1958 continue;
1960 if (!ISWILD(word))
1961 got_flag = NONWILD_CLIENT;
1964 * Now get a server and check if it matches.
1966 if (!getword(f, word, &newline, filename))
1967 break;
1968 if (newline)
1969 continue;
1970 if (!ISWILD(word)) {
1971 if (server != NULL && strcmp(word, server) != 0) {
1972 (void) strcpy(scan_server_match_failed, word);
1973 continue;
1975 got_flag |= NONWILD_SERVER;
1979 * Got some sort of a match - see if it's better than what
1980 * we have already.
1982 if (got_flag <= best_flag)
1983 continue;
1986 * Get the secret.
1988 if (!getword(f, word, &newline, filename))
1989 break;
1990 if (newline)
1991 continue;
1994 * Special syntax: @filename means read secret from file.
1995 * Because the secrets files are modifiable only by root,
1996 * it's safe to open this file as root. One small addition --
1997 * if open fails, we try as the regular user; just in case
1998 * it's over NFS and not root-equivalent.
2000 if (word[0] == '@') {
2001 (void) strlcpy(atfile, word+1, sizeof(atfile));
2002 if ((sf = fopen(atfile, "r")) == NULL) {
2003 (void) seteuid(getuid());
2004 sf = fopen(atfile, "r");
2005 (void) seteuid(0);
2007 if (sf == NULL) {
2008 warn("can't open indirect secret file %s: %m", atfile);
2009 continue;
2011 check_access(sf, atfile);
2012 if (!getword(sf, word, &xxx, atfile)) {
2013 warn("no secret in indirect secret file %s", atfile);
2014 (void) fclose(sf);
2015 continue;
2017 (void) fclose(sf);
2019 if (secret != NULL)
2020 (void) strlcpy(lsecret, word, sizeof(lsecret));
2023 * Now read address authorization info and make a wordlist.
2025 app = &alist;
2026 for (;;) {
2027 if (!getword(f, word, &newline, filename) || newline)
2028 break;
2029 ap = (struct wordlist *) malloc(sizeof(struct wordlist));
2030 if (ap == NULL)
2031 novm("authorized addresses");
2032 ap->word = strdup(word);
2033 if (ap->word == NULL)
2034 novm("authorized addresses");
2035 *app = ap;
2036 app = &ap->next;
2038 *app = NULL;
2041 * This is the best so far; remember it.
2043 best_flag = got_flag;
2044 if (addr_list != NULL)
2045 free_wordlist(addr_list);
2046 addr_list = alist;
2047 if (secret != NULL)
2048 (void) strlcpy(secret, lsecret, MAXWORDLEN);
2050 if (opts != NULL) {
2051 extra_opt_filename = filename;
2052 extra_opt_line = sline;
2055 if (!newline)
2056 break;
2059 /* scan for a -- word indicating the start of options */
2060 for (app = &addr_list; (ap = *app) != NULL; app = &ap->next)
2061 if (strcmp(ap->word, "--") == 0)
2062 break;
2063 /* ap = start of options */
2064 if (ap != NULL) {
2065 ap = ap->next; /* first option */
2066 free(*app); /* free the "--" word */
2067 *app = NULL; /* terminate addr list */
2069 if (opts != NULL)
2070 *opts = ap;
2071 else if (ap != NULL)
2072 free_wordlist(ap);
2073 if (addrs != NULL)
2074 *addrs = addr_list;
2075 else if (addr_list != NULL)
2076 free_wordlist(addr_list);
2078 return best_flag;
2082 * free_wordlist - release memory allocated for a wordlist.
2084 static void
2085 free_wordlist(wp)
2086 struct wordlist *wp;
2088 struct wordlist *next;
2090 while (wp != NULL) {
2091 next = wp->next;
2092 free(wp);
2093 wp = next;
2098 * auth_script_done - called when the auth-up or auth-down script
2099 * has finished.
2101 /*ARGSUSED*/
2102 static void
2103 auth_script_done(arg, status)
2104 void *arg;
2105 int status;
2107 auth_script_pid = 0;
2108 switch (auth_script_state) {
2109 case s_up:
2110 if (auth_state == s_down) {
2111 auth_script_state = s_down;
2112 auth_script(_PATH_AUTHDOWN);
2114 break;
2115 case s_down:
2116 if (auth_state == s_up) {
2117 auth_script_state = s_up;
2118 auth_script(_PATH_AUTHUP);
2120 break;
2125 * auth_script - execute a script with arguments
2126 * interface-name peer-name real-user tty speed
2128 static void
2129 auth_script(script)
2130 char *script;
2132 char strspeed[32];
2133 struct passwd *pw;
2134 char struid[32];
2135 char *user_name;
2136 char *argv[8];
2138 if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
2139 user_name = pw->pw_name;
2140 else {
2141 (void) slprintf(struid, sizeof(struid), "%d", getuid());
2142 user_name = struid;
2144 (void) slprintf(strspeed, sizeof(strspeed), "%d", baud_rate);
2146 argv[0] = script;
2147 argv[1] = ifname;
2148 argv[2] = peer_authname;
2149 argv[3] = user_name;
2150 argv[4] = devnam;
2151 argv[5] = strspeed;
2152 argv[6] = NULL;
2154 auth_script_pid = run_program(script, argv, 0, auth_script_done, NULL);