2 * auth.c - PPP authentication and phase control.
4 * Copyright (c) 1993 The Australian National University.
7 * Redistribution and use in source and binary forms are permitted
8 * provided that the above copyright notice and this paragraph are
9 * duplicated in all such forms and that any documentation,
10 * advertising materials, and other materials related to such
11 * distribution and use acknowledge that the software was developed
12 * by the Australian National University. The name of the University
13 * may not be used to endorse or promote products derived from this
14 * software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19 * Copyright (c) 1989 Carnegie Mellon University.
20 * All rights reserved.
22 * Redistribution and use in source and binary forms are permitted
23 * provided that the above copyright notice and this paragraph are
24 * duplicated in all such forms and that any documentation,
25 * advertising materials, and other materials related to such
26 * distribution and use acknowledge that the software was developed
27 * by Carnegie Mellon University. The name of the
28 * University may not be used to endorse or promote products derived
29 * from this software without specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
32 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
36 static char rcsid[] = "$Id: auth.c,v 1.54 1999/07/21 00:24:30 paulus Exp $";
46 #include <sys/types.h>
48 #include <sys/socket.h>
51 #if defined(_PATH_LASTLOG) && defined(_linux_)
56 #include <netinet/in.h>
57 #include <arpa/inet.h>
60 #include <security/pam_appl.h>
66 #define PW_PPP PW_LOGIN
79 #include "pathnames.h"
81 /* Bits in scan_authfile return value */
82 #define NONWILD_SERVER 1
83 #define NONWILD_CLIENT 2
85 #define ISWILD(word) (word[0] == '*' && word[1] == 0)
87 /* The name by which the peer authenticated itself to us. */
88 char peer_authname[MAXNAMELEN];
90 /* Records which authentication operations haven't completed yet. */
91 static int auth_pending[NUM_PPP];
93 /* Set if we have successfully called plogin() */
96 /* List of addresses which the peer may use. */
97 static struct permitted_ip *addresses[NUM_PPP];
99 /* Extra options to apply, from the secrets file entry for the peer. */
100 static struct wordlist *extra_options;
102 /* Number of network protocols which we have opened. */
103 static int num_np_open;
105 /* Number of network protocols which have come up. */
106 static int num_np_up;
108 /* Set if we got the contents of passwd[] from the pap-secrets file. */
109 static int passwd_from_file;
112 * This is used to ensure that we don't start an auth-up/down
113 * script while one is already running.
120 static enum script_state auth_state = s_down;
121 static enum script_state auth_script_state = s_down;
122 static pid_t auth_script_pid = 0;
127 bool uselogin = 0; /* Use /etc/passwd for checking PAP */
128 bool cryptpap = 0; /* Passwords in pap-secrets are encrypted */
129 bool refuse_pap = 0; /* Don't wanna auth. ourselves with PAP */
130 bool refuse_chap = 0; /* Don't wanna auth. ourselves with CHAP */
131 bool usehostname = 0; /* Use hostname for our_name */
132 bool auth_required = 0; /* Always require authentication from peer */
133 bool allow_any_ip = 0; /* Allow peer to use any IP address */
134 bool explicit_remote = 0; /* User specified explicit remote name */
135 char remote_name[MAXNAMELEN]; /* Peer's name for authentication */
137 /* Bits in auth_pending[] */
138 #define PAP_WITHPEER 1
140 #define CHAP_WITHPEER 4
143 extern char *crypt __P((const char *, const char *));
145 /* Prototypes for procedures local to this file. */
147 static void network_phase __P((int));
148 static void check_idle __P((void *));
149 static void connect_time_expired __P((void *));
150 static int plogin __P((char *, char *, char **, int *));
151 static void plogout __P((void));
152 static int null_login __P((int));
153 static int get_pap_passwd __P((char *));
154 static int have_pap_secret __P((int *));
155 static int have_chap_secret __P((char *, char *, int, int *));
156 static int ip_addr_check __P((u_int32_t, struct permitted_ip *));
157 static int scan_authfile __P((FILE *, char *, char *, char *,
158 struct wordlist **, char *));
159 static void free_wordlist __P((struct wordlist *));
160 static void auth_script __P((char *));
161 static void auth_script_done __P((void *));
162 static void set_allowed_addrs __P((int, struct wordlist *));
163 static int some_ip_ok __P((struct wordlist *));
164 static int setupapfile __P((char **));
165 static int privgroup __P((char **));
166 static void check_access __P((FILE *, char *));
169 * Authentication-related options.
171 option_t auth_options[] = {
172 { "require-pap", o_bool, &lcp_wantoptions[0].neg_upap,
173 "Require PAP authentication from peer", 1, &auth_required },
174 { "+pap", o_bool, &lcp_wantoptions[0].neg_upap,
175 "Require PAP authentication from peer", 1, &auth_required },
176 { "refuse-pap", o_bool, &refuse_pap,
177 "Don't agree to auth to peer with PAP", 1 },
178 { "-pap", o_bool, &refuse_pap,
179 "Don't allow PAP authentication with peer", 1 },
180 { "require-chap", o_bool, &lcp_wantoptions[0].neg_chap,
181 "Require CHAP authentication from peer", 1, &auth_required },
182 { "+chap", o_bool, &lcp_wantoptions[0].neg_chap,
183 "Require CHAP authentication from peer", 1, &auth_required },
184 { "refuse-chap", o_bool, &refuse_chap,
185 "Don't agree to auth to peer with CHAP", 1 },
186 { "-chap", o_bool, &refuse_chap,
187 "Don't allow CHAP authentication with peer", 1 },
188 { "name", o_string, our_name,
189 "Set local name for authentication",
190 OPT_PRIV|OPT_STATIC, NULL, MAXNAMELEN },
191 { "user", o_string, user,
192 "Set name for auth with peer", OPT_STATIC, NULL, MAXNAMELEN },
193 { "usehostname", o_bool, &usehostname,
194 "Must use hostname for authentication", 1 },
195 { "remotename", o_string, remote_name,
196 "Set remote name for authentication", OPT_STATIC,
197 &explicit_remote, MAXNAMELEN },
198 { "auth", o_bool, &auth_required,
199 "Require authentication from peer", 1 },
200 { "noauth", o_bool, &auth_required,
201 "Don't require peer to authenticate", OPT_PRIV, &allow_any_ip },
202 { "login", o_bool, &uselogin,
203 "Use system password database for PAP", 1 },
204 { "papcrypt", o_bool, &cryptpap,
205 "PAP passwords are encrypted", 1 },
206 { "+ua", o_special, setupapfile,
207 "Get PAP user and password from file" },
208 { "privgroup", o_special, privgroup,
209 "Allow group members to use privileged options", OPT_PRIV },
214 * setupapfile - specifies UPAP info for authenticating with peer.
223 lcp_allowoptions[0].neg_upap = 1;
225 /* open user info file */
227 ufile = fopen(*argv, "r");
230 option_error("unable to open user login data file %s", *argv);
233 check_access(ufile, *argv);
236 if (fgets(user, MAXNAMELEN - 1, ufile) == NULL
237 || fgets(passwd, MAXSECRETLEN - 1, ufile) == NULL){
238 option_error("unable to read user login data file %s", *argv);
243 /* get rid of newlines */
245 if (l > 0 && user[l-1] == '\n')
248 if (l > 0 && passwd[l-1] == '\n')
256 * privgroup - allow members of the group to have privileged access.
267 option_error("group %s is unknown", *argv);
270 for (i = 0; i < ngroups; ++i) {
271 if (groups[i] == g->gr_gid) {
281 * An Open on LCP has requested a change from Dead to Establish phase.
282 * Do what's necessary to bring the physical layer up.
291 * LCP has terminated the link; go to the Dead phase and take the
292 * physical layer down.
295 link_terminated(unit)
298 if (phase == PHASE_DEAD)
303 notice("Connection terminated.");
307 * LCP has gone down; it will either die or try to re-establish.
314 struct protent *protp;
317 if (auth_script_state == s_up && auth_script_pid == 0) {
318 auth_script_state = s_down;
319 auth_script(_PATH_AUTHDOWN);
321 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
322 if (!protp->enabled_flag)
324 if (protp->protocol != PPP_LCP && protp->lowerdown != NULL)
325 (*protp->lowerdown)(unit);
326 if (protp->protocol < 0xC000 && protp->close != NULL)
327 (*protp->close)(unit, "LCP down");
331 if (phase != PHASE_DEAD)
332 phase = PHASE_TERMINATE;
336 * The link is established.
337 * Proceed to the Dead, Authenticate or Network phase as appropriate.
340 link_established(unit)
344 lcp_options *wo = &lcp_wantoptions[unit];
345 lcp_options *go = &lcp_gotoptions[unit];
346 lcp_options *ho = &lcp_hisoptions[unit];
348 struct protent *protp;
351 * Tell higher-level protocols that LCP is up.
353 for (i = 0; (protp = protocols[i]) != NULL; ++i)
354 if (protp->protocol != PPP_LCP && protp->enabled_flag
355 && protp->lowerup != NULL)
356 (*protp->lowerup)(unit);
358 if (auth_required && !(go->neg_chap || go->neg_upap)) {
360 * We wanted the peer to authenticate itself, and it refused:
361 * treat it as though it authenticated with PAP using a username
362 * of "" and a password of "". If that's not OK, boot it out.
364 if (!wo->neg_upap || !null_login(unit)) {
365 warn("peer refused to authenticate: terminating link");
366 lcp_close(unit, "peer refused to authenticate");
367 status = EXIT_PEER_AUTH_FAILED;
372 phase = PHASE_AUTHENTICATE;
375 ChapAuthPeer(unit, our_name, go->chap_mdtype);
377 } else if (go->neg_upap) {
382 ChapAuthWithPeer(unit, user, ho->chap_mdtype);
383 auth |= CHAP_WITHPEER;
384 } else if (ho->neg_upap) {
385 if (passwd[0] == 0) {
386 passwd_from_file = 1;
387 if (!get_pap_passwd(passwd))
388 error("No secret found for PAP login");
390 upap_authwithpeer(unit, user, passwd);
391 auth |= PAP_WITHPEER;
393 auth_pending[unit] = auth;
400 * Proceed to the network phase.
407 struct protent *protp;
408 lcp_options *go = &lcp_gotoptions[unit];
411 * If the peer had to authenticate, run the auth-up script now.
413 if (go->neg_chap || go->neg_upap) {
415 if (auth_script_state == s_down && auth_script_pid == 0) {
416 auth_script_state = s_up;
417 auth_script(_PATH_AUTHUP);
423 * If we negotiated callback, do it now.
426 phase = PHASE_CALLBACK;
427 (*cbcp_protent.open)(unit);
433 * Process extra options from the secrets file
436 options_from_list(extra_options, 1);
437 free_wordlist(extra_options);
446 phase = PHASE_NETWORK;
449 set_filters(&pass_filter, &active_filter);
451 for (i = 0; (protp = protocols[i]) != NULL; ++i)
452 if (protp->protocol < 0xC000 && protp->enabled_flag
453 && protp->open != NULL) {
454 (*protp->open)(unit);
455 if (protp->protocol != PPP_CCP)
459 if (num_np_open == 0)
461 lcp_close(0, "No network protocols running");
465 * The peer has failed to authenticate himself using `protocol'.
468 auth_peer_fail(unit, protocol)
472 * Authentication failure: take the link down
474 lcp_close(unit, "Authentication failed");
475 status = EXIT_PEER_AUTH_FAILED;
479 * The peer has been successfully authenticated using `protocol'.
482 auth_peer_success(unit, protocol, name, namelen)
497 warn("auth_peer_success: unknown protocol %x", protocol);
502 * Save the authenticated name of the peer for later.
504 if (namelen > sizeof(peer_authname) - 1)
505 namelen = sizeof(peer_authname) - 1;
506 BCOPY(name, peer_authname, namelen);
507 peer_authname[namelen] = 0;
508 script_setenv("PEERNAME", peer_authname);
511 * If there is no more authentication still to be done,
512 * proceed to the network (or callback) phase.
514 if ((auth_pending[unit] &= ~bit) == 0)
519 * We have failed to authenticate ourselves to the peer using `protocol'.
522 auth_withpeer_fail(unit, protocol)
525 if (passwd_from_file)
526 BZERO(passwd, MAXSECRETLEN);
528 * We've failed to authenticate ourselves to our peer.
529 * He'll probably take the link down, and there's not much
530 * we can do except wait for that.
535 * We have successfully authenticated ourselves with the peer using `protocol'.
538 auth_withpeer_success(unit, protocol)
548 if (passwd_from_file)
549 BZERO(passwd, MAXSECRETLEN);
553 warn("auth_withpeer_success: unknown protocol %x", protocol);
558 * If there is no more authentication still being done,
559 * proceed to the network (or callback) phase.
561 if ((auth_pending[unit] &= ~bit) == 0)
567 * np_up - a network protocol has come up.
573 if (num_np_up == 0) {
575 * At this point we consider that the link has come up successfully.
579 if (idle_time_limit > 0)
580 TIMEOUT(check_idle, NULL, idle_time_limit);
583 * Set a timeout to close the connection once the maximum
584 * connect time has expired.
587 TIMEOUT(connect_time_expired, 0, maxconnect);
590 * Detach now, if the updetach option was given.
592 if (updetach && !nodetach)
599 * np_down - a network protocol has gone down.
605 if (--num_np_up == 0 && idle_time_limit > 0) {
606 UNTIMEOUT(check_idle, NULL);
611 * np_finished - a network protocol has finished using the link.
614 np_finished(unit, proto)
617 if (--num_np_open <= 0) {
618 /* no further use for the link: shut up shop. */
619 lcp_close(0, "No network protocols running");
624 * check_idle - check whether the link has been idle for long
625 * enough that we can shut it down.
631 struct ppp_idle idle;
634 if (!get_idle_time(0, &idle))
636 itime = MIN(idle.xmit_idle, idle.recv_idle);
637 if (itime >= idle_time_limit) {
638 /* link is idle: shut it down. */
639 notice("Terminating connection due to lack of activity.");
640 lcp_close(0, "Link inactive");
642 status = EXIT_IDLE_TIMEOUT;
644 TIMEOUT(check_idle, NULL, idle_time_limit - itime);
649 * connect_time_expired - log a message and close the connection.
652 connect_time_expired(arg)
655 info("Connect time expired");
656 lcp_close(0, "Connect time expired"); /* Close connection */
657 status = EXIT_CONNECT_TIME;
661 * auth_check_options - called to check authentication options.
666 lcp_options *wo = &lcp_wantoptions[0];
670 /* Default our_name to hostname, and user to our_name */
671 if (our_name[0] == 0 || usehostname)
672 strlcpy(our_name, hostname, sizeof(our_name));
674 strlcpy(user, our_name, sizeof(user));
677 * If we have a default route, require the peer to authenticate
678 * unless the noauth option was given.
680 if (!auth_required && !allow_any_ip && have_route_to(0))
683 /* If authentication is required, ask peer for CHAP or PAP. */
685 if (!wo->neg_chap && !wo->neg_upap) {
695 * Check whether we have appropriate secrets to use
696 * to authenticate the peer.
699 can_auth = wo->neg_upap && (uselogin || have_pap_secret(&lacks_ip));
700 if (!can_auth && wo->neg_chap) {
701 can_auth = have_chap_secret((explicit_remote? remote_name: NULL),
702 our_name, 1, &lacks_ip);
705 if (auth_required && !can_auth) {
708 "The remote system (%s) is required to authenticate itself but I",
712 "The remote system is required to authenticate itself but I");
716 "couldn't find any suitable secret (password) for it to use to do so.");
719 "couldn't find any secret (password) which would let it use an IP address.");
726 * auth_reset - called when LCP is starting negotiations to recheck
727 * authentication options, i.e. whether we have appropriate secrets
728 * to use for authenticating ourselves and/or the peer.
734 lcp_options *go = &lcp_gotoptions[unit];
735 lcp_options *ao = &lcp_allowoptions[0];
737 ao->neg_upap = !refuse_pap && (passwd[0] != 0 || get_pap_passwd(NULL));
738 ao->neg_chap = !refuse_chap
739 && have_chap_secret(user, (explicit_remote? remote_name: NULL),
742 if (go->neg_upap && !uselogin && !have_pap_secret(NULL))
745 if (!have_chap_secret((explicit_remote? remote_name: NULL),
753 * check_passwd - Check the user name and passwd against the PAP secrets
754 * file. If requested, also check against the system password database,
755 * and login the user if OK.
758 * UPAP_AUTHNAK: Authentication failed.
759 * UPAP_AUTHACK: Authentication succeeded.
760 * In either case, msg points to an appropriate message.
763 check_passwd(unit, auser, userlen, apasswd, passwdlen, msg, msglen)
775 struct wordlist *addrs;
776 char passwd[256], user[256];
777 char secret[MAXWORDLEN];
778 static int attempts = 0;
781 * Make copies of apasswd and auser, then null-terminate them.
783 BCOPY(apasswd, passwd, passwdlen);
784 passwd[passwdlen] = '\0';
785 BCOPY(auser, user, userlen);
786 user[userlen] = '\0';
790 * Open the file of pap secrets and scan for a suitable secret
791 * for authenticating this user.
793 filename = _PATH_UPAPFILE;
796 f = fopen(filename, "r");
798 error("Can't open PAP password file %s: %m", filename);
802 check_access(f, filename);
803 if (scan_authfile(f, user, our_name, secret, &addrs, filename) < 0
804 || (!uselogin && secret[0] != 0
805 && (cryptpap || strcmp(passwd, secret) != 0)
806 && strcmp(crypt(passwd, secret), secret) != 0)) {
807 warn("PAP authentication failure for %s", user);
813 if (uselogin && ret == UPAP_AUTHACK) {
814 ret = plogin(user, passwd, msg, msglen);
815 if (ret == UPAP_AUTHNAK) {
816 warn("PAP login failure for %s", user);
820 if (ret == UPAP_AUTHNAK) {
821 if (*msg == (char *) 0)
822 *msg = "Login incorrect";
823 *msglen = strlen(*msg);
825 * XXX can we ever get here more than once??
826 * Frustrate passwd stealer programs.
827 * Allow 10 tries, but start backing off after 3 (stolen from login).
828 * On 10'th, drop the connection.
830 if (attempts++ >= 10) {
831 warn("%d LOGIN FAILURES ON %s, %s", attempts, devnam, user);
832 lcp_close(unit, "login failed");
835 sleep((u_int) (attempts - 3) * 5);
837 free_wordlist(addrs);
840 attempts = 0; /* Reset count */
841 if (*msg == (char *) 0)
843 *msglen = strlen(*msg);
844 set_allowed_addrs(unit, addrs);
847 BZERO(passwd, sizeof(passwd));
848 BZERO(secret, sizeof(secret));
854 * This function is needed for PAM.
858 /* Static variables used to communicate between the conversation function
859 * and the server_login function
861 static char *PAM_username;
862 static char *PAM_password;
863 static int PAM_error = 0;
864 static pam_handle_t *pamh = NULL;
866 /* PAM conversation function
867 * Here we assume (for now, at least) that echo on means login name, and
868 * echo off means password.
871 static int PAM_conv (int num_msg, const struct pam_message **msg,
872 struct pam_response **resp, void *appdata_ptr)
875 struct pam_response *reply = NULL;
877 #define COPY_STRING(s) (s) ? strdup(s) : NULL
879 reply = malloc(sizeof(struct pam_response) * num_msg);
880 if (!reply) return PAM_CONV_ERR;
882 for (replies = 0; replies < num_msg; replies++) {
883 switch (msg[replies]->msg_style) {
884 case PAM_PROMPT_ECHO_ON:
885 reply[replies].resp_retcode = PAM_SUCCESS;
886 reply[replies].resp = COPY_STRING(PAM_username);
889 case PAM_PROMPT_ECHO_OFF:
890 reply[replies].resp_retcode = PAM_SUCCESS;
891 reply[replies].resp = COPY_STRING(PAM_password);
897 /* ignore it, but pam still wants a NULL response... */
898 reply[replies].resp_retcode = PAM_SUCCESS;
899 reply[replies].resp = NULL;
902 /* Must be an error of some sort... */
912 static struct pam_conv PAM_conversation = {
919 * plogin - Check the user name and password against the system
920 * password database, and login the user if OK.
923 * UPAP_AUTHNAK: Login failed.
924 * UPAP_AUTHACK: Login succeeded.
925 * In either case, msg points to an appropriate message.
929 plogin(user, passwd, msg, msglen)
940 pam_error = pam_start ("ppp", user, &PAM_conversation, &pamh);
941 if (pam_error != PAM_SUCCESS) {
942 *msg = (char *) pam_strerror (pamh, pam_error);
947 * Define the fields for the credential validation
951 PAM_password = passwd;
953 pam_set_item (pamh, PAM_TTY, devnam); /* this might be useful to some modules */
958 pam_error = pam_authenticate (pamh, PAM_SILENT);
959 if (pam_error == PAM_SUCCESS && !PAM_error) {
960 pam_error = pam_acct_mgmt (pamh, PAM_SILENT);
961 if (pam_error == PAM_SUCCESS)
962 pam_open_session (pamh, PAM_SILENT);
965 *msg = (char *) pam_strerror (pamh, pam_error);
970 reopen_log(); /* apparently the PAM stuff does closelog() */
973 if (pam_error != PAM_SUCCESS)
975 #else /* #ifdef USE_PAM */
978 * Use the non-PAM methods directly
983 struct spwd *getspnam();
985 struct passwd *pw = getpwnam(user);
989 return (UPAP_AUTHNAK);
992 spwd = getspnam(user);
995 /* check the age of the password entry */
996 long now = time(NULL) / 86400L;
998 if ((spwd->sp_expire > 0 && now >= spwd->sp_expire)
999 || ((spwd->sp_max >= 0 && spwd->sp_max < 10000)
1000 && spwd->sp_lstchg >= 0
1001 && now >= spwd->sp_lstchg + spwd->sp_max)) {
1002 warn("Password for %s has expired", user);
1003 return (UPAP_AUTHNAK);
1005 pw->pw_passwd = spwd->sp_pwdp;
1010 * If no passwd, don't let them login.
1012 if (pw->pw_passwd == NULL || strlen(pw->pw_passwd) < 2
1013 || strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd) != 0)
1014 return (UPAP_AUTHNAK);
1016 #endif /* #ifdef USE_PAM */
1019 * Write a wtmp entry for this user.
1023 if (strncmp(tty, "/dev/", 5) == 0)
1025 logwtmp(tty, user, remote_name); /* Add wtmp login entry */
1027 #if defined(_PATH_LASTLOG) && !defined(USE_PAM)
1028 if (pw != (struct passwd *)NULL) {
1032 if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
1033 (void)lseek(fd, (off_t)(pw->pw_uid * sizeof(ll)), SEEK_SET);
1034 memset((void *)&ll, 0, sizeof(ll));
1035 (void)time(&ll.ll_time);
1036 (void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
1037 (void)write(fd, (char *)&ll, sizeof(ll));
1041 #endif /* _PATH_LASTLOG and not USE_PAM */
1043 info("user %s logged in", user);
1046 return (UPAP_AUTHACK);
1050 * plogout - Logout the user.
1059 pam_error = pam_close_session (pamh, PAM_SILENT);
1060 pam_end (pamh, pam_error);
1063 /* Apparently the pam stuff does closelog(). */
1065 #else /* ! USE_PAM */
1069 if (strncmp(tty, "/dev/", 5) == 0)
1071 logwtmp(tty, "", ""); /* Wipe out utmp logout entry */
1072 #endif /* ! USE_PAM */
1078 * null_login - Check if a username of "" and a password of "" are
1079 * acceptable, and iff so, set the list of acceptable IP addresses
1089 struct wordlist *addrs;
1090 char secret[MAXWORDLEN];
1093 * Open the file of pap secrets and scan for a suitable secret.
1094 * We don't accept a wildcard client.
1096 filename = _PATH_UPAPFILE;
1098 f = fopen(filename, "r");
1101 check_access(f, filename);
1103 i = scan_authfile(f, "", our_name, secret, &addrs, filename);
1104 ret = i >= 0 && (i & NONWILD_CLIENT) != 0 && secret[0] == 0;
1105 BZERO(secret, sizeof(secret));
1108 set_allowed_addrs(unit, addrs);
1110 free_wordlist(addrs);
1118 * get_pap_passwd - get a password for authenticating ourselves with
1119 * our peer using PAP. Returns 1 on success, 0 if no suitable password
1121 * Assumes passwd points to MAXSECRETLEN bytes of space (if non-null).
1124 get_pap_passwd(passwd)
1130 struct wordlist *addrs;
1131 char secret[MAXWORDLEN];
1133 filename = _PATH_UPAPFILE;
1135 f = fopen(filename, "r");
1138 check_access(f, filename);
1139 ret = scan_authfile(f, user,
1140 (remote_name[0]? remote_name: NULL),
1141 secret, NULL, filename);
1146 strlcpy(passwd, secret, MAXSECRETLEN);
1147 BZERO(secret, sizeof(secret));
1153 * have_pap_secret - check whether we have a PAP file with any
1154 * secrets that we could possibly use for authenticating the peer.
1157 have_pap_secret(lacks_ipp)
1163 struct wordlist *addrs;
1165 filename = _PATH_UPAPFILE;
1166 f = fopen(filename, "r");
1170 ret = scan_authfile(f, (explicit_remote? remote_name: NULL), our_name,
1171 NULL, &addrs, filename);
1173 if (ret >= 0 && !some_ip_ok(addrs)) {
1179 free_wordlist(addrs);
1186 * have_chap_secret - check whether we have a CHAP file with a
1187 * secret that we could possibly use for authenticating `client'
1188 * on `server'. Either can be the null string, meaning we don't
1189 * know the identity yet.
1192 have_chap_secret(client, server, need_ip, lacks_ipp)
1201 struct wordlist *addrs;
1203 filename = _PATH_CHAPFILE;
1204 f = fopen(filename, "r");
1208 if (client != NULL && client[0] == 0)
1210 else if (server != NULL && server[0] == 0)
1213 ret = scan_authfile(f, client, server, NULL, &addrs, filename);
1215 if (ret >= 0 && need_ip && !some_ip_ok(addrs)) {
1221 free_wordlist(addrs);
1228 * get_secret - open the CHAP secret file and return the secret
1229 * for authenticating the given client on the given server.
1230 * (We could be either client or server).
1233 get_secret(unit, client, server, secret, secret_len, save_addrs)
1244 struct wordlist *addrs;
1245 char secbuf[MAXWORDLEN];
1247 filename = _PATH_CHAPFILE;
1251 f = fopen(filename, "r");
1253 error("Can't open chap secret file %s: %m", filename);
1256 check_access(f, filename);
1258 ret = scan_authfile(f, client, server, secbuf, &addrs, filename);
1264 set_allowed_addrs(unit, addrs);
1266 len = strlen(secbuf);
1267 if (len > MAXSECRETLEN) {
1268 error("Secret for %s on %s is too long", client, server);
1271 BCOPY(secbuf, secret, len);
1272 BZERO(secbuf, sizeof(secbuf));
1279 * set_allowed_addrs() - set the list of allowed addresses.
1280 * Also looks for `--' indicating options to apply for this peer
1281 * and leaves the following words in extra_options.
1284 set_allowed_addrs(unit, addrs)
1286 struct wordlist *addrs;
1289 struct wordlist *ap, **pap;
1290 struct permitted_ip *ip;
1291 char *ptr_word, *ptr_mask;
1294 u_int32_t a, mask, ah;
1295 struct ipcp_options *wo = &ipcp_wantoptions[unit];
1296 u_int32_t suggested_ip = 0;
1298 if (addresses[unit] != NULL)
1299 free(addresses[unit]);
1300 addresses[unit] = NULL;
1301 if (extra_options != NULL)
1302 free_wordlist(extra_options);
1303 extra_options = NULL;
1306 * Count the number of IP addresses given, and chop off
1307 * any extra options for this peer.
1309 for (n = 0, pap = &addrs; (ap = *pap) != NULL; pap = &ap->next, ++n) {
1310 if (strcmp(ap->word, "--") == 0) {
1311 /* rest are options */
1313 extra_options = ap->next;
1320 ip = (struct permitted_ip *) malloc((n + 1) * sizeof(struct permitted_ip));
1325 for (ap = addrs; ap != NULL; ap = ap->next) {
1326 /* "-" means no addresses authorized, "*" means any address allowed */
1327 ptr_word = ap->word;
1328 if (strcmp(ptr_word, "-") == 0)
1330 if (strcmp(ptr_word, "*") == 0) {
1332 ip[n].base = ip[n].mask = 0;
1338 if (*ptr_word == '!') {
1343 mask = ~ (u_int32_t) 0;
1344 ptr_mask = strchr (ptr_word, '/');
1345 if (ptr_mask != NULL) {
1348 bit_count = (int) strtol (ptr_mask+1, (char **) 0, 10);
1349 if (bit_count <= 0 || bit_count > 32) {
1350 warn("invalid address length %v in auth. address list",
1355 mask <<= 32 - bit_count;
1358 hp = gethostbyname(ptr_word);
1359 if (hp != NULL && hp->h_addrtype == AF_INET) {
1360 a = *(u_int32_t *)hp->h_addr;
1362 np = getnetbyname (ptr_word);
1363 if (np != NULL && np->n_addrtype == AF_INET) {
1364 a = htonl (*(u_int32_t *)np->n_net);
1365 if (ptr_mask == NULL) {
1366 /* calculate appropriate mask for net */
1369 mask = IN_CLASSA_NET;
1370 else if (IN_CLASSB(ah))
1371 mask = IN_CLASSB_NET;
1372 else if (IN_CLASSC(ah))
1373 mask = IN_CLASSC_NET;
1376 a = inet_addr (ptr_word);
1380 if (ptr_mask != NULL)
1383 if (a == (u_int32_t)-1L)
1384 warn("unknown host %s in auth. address list", ap->word);
1386 ip[n].mask = htonl(mask);
1387 ip[n].base = a & ip[n].mask;
1389 if (~mask == 0 && suggested_ip == 0)
1394 ip[n].permit = 0; /* make the last entry forbid all addresses */
1395 ip[n].base = 0; /* to terminate the list */
1398 addresses[unit] = ip;
1401 * If the address given for the peer isn't authorized, or if
1402 * the user hasn't given one, AND there is an authorized address
1403 * which is a single host, then use that if we find one.
1405 if (suggested_ip != 0
1406 && (wo->hisaddr == 0 || !auth_ip_addr(unit, wo->hisaddr)))
1407 wo->hisaddr = suggested_ip;
1411 * auth_ip_addr - check whether the peer is authorized to use
1412 * a given IP address. Returns 1 if authorized, 0 otherwise.
1415 auth_ip_addr(unit, addr)
1419 if (addresses[unit] == NULL) {
1421 return 0; /* no addresses authorized */
1422 return allow_any_ip || !have_route_to(addr);
1424 return ip_addr_check(addr, addresses[unit]);
1428 ip_addr_check(addr, addrs)
1430 struct permitted_ip *addrs;
1432 /* don't allow loopback or multicast address */
1433 if (bad_ip_adrs(addr))
1437 if ((addr & addrs->mask) == addrs->base)
1438 return addrs->permit;
1442 * bad_ip_adrs - return 1 if the IP address is one we don't want
1443 * to use, such as an address in the loopback net or a multicast address.
1444 * addr is in network byte order.
1451 return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
1452 || IN_MULTICAST(addr) || IN_BADCLASS(addr);
1456 * some_ip_ok - check a wordlist to see if it authorizes any
1461 struct wordlist *addrs;
1463 for (; addrs != 0; addrs = addrs->next) {
1464 if (strcmp(addrs->word, "-") == 0)
1466 if (addrs->word[0] != '!')
1467 return 1; /* some IP address is allowed */
1473 * check_access - complain if a secret file has too-liberal permissions.
1476 check_access(f, filename)
1482 if (fstat(fileno(f), &sbuf) < 0) {
1483 warn("cannot stat secret file %s: %m", filename);
1484 } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1485 warn("Warning - secret file %s has world and/or group access",
1492 * scan_authfile - Scan an authorization file for a secret suitable
1493 * for authenticating `client' on `server'. The return value is -1
1494 * if no secret is found, otherwise >= 0. The return value has
1495 * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
1496 * NONWILD_SERVER set if the secret didn't have "*" for the server.
1497 * Any following words on the line (i.e. address authorization
1498 * info) are placed in a wordlist and returned in *addrs.
1499 * We assume secret is NULL or points to MAXWORDLEN bytes of space.
1502 scan_authfile(f, client, server, secret, addrs, filename)
1507 struct wordlist **addrs;
1511 int got_flag, best_flag;
1513 struct wordlist *ap, *addr_list, *alist, *alast;
1514 char word[MAXWORDLEN];
1515 char atfile[MAXWORDLEN];
1516 char lsecret[MAXWORDLEN];
1521 if (!getword(f, word, &newline, filename))
1522 return -1; /* file is empty??? */
1527 * Skip until we find a word at the start of a line.
1529 while (!newline && getword(f, word, &newline, filename))
1532 break; /* got to end of file */
1535 * Got a client - check if it's a match or a wildcard.
1538 if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
1543 got_flag = NONWILD_CLIENT;
1546 * Now get a server and check if it matches.
1548 if (!getword(f, word, &newline, filename))
1552 if (!ISWILD(word)) {
1553 if (server != NULL && strcmp(word, server) != 0)
1555 got_flag |= NONWILD_SERVER;
1559 * Got some sort of a match - see if it's better than what
1562 if (got_flag <= best_flag)
1568 if (!getword(f, word, &newline, filename))
1574 * Special syntax: @filename means read secret from file.
1576 if (word[0] == '@') {
1577 strlcpy(atfile, word+1, sizeof(atfile));
1578 if ((sf = fopen(atfile, "r")) == NULL) {
1579 warn("can't open indirect secret file %s", atfile);
1582 check_access(sf, atfile);
1583 if (!getword(sf, word, &xxx, atfile)) {
1584 warn("no secret in indirect secret file %s", atfile);
1591 strlcpy(lsecret, word, sizeof(lsecret));
1594 * Now read address authorization info and make a wordlist.
1596 alist = alast = NULL;
1598 if (!getword(f, word, &newline, filename) || newline)
1600 ap = (struct wordlist *) malloc(sizeof(struct wordlist));
1602 novm("authorized addresses");
1604 ap->word = strdup(word);
1605 if (ap->word == NULL)
1606 novm("authorized address");
1615 * This is the best so far; remember it.
1617 best_flag = got_flag;
1619 free_wordlist(addr_list);
1622 strlcpy(secret, lsecret, MAXWORDLEN);
1630 else if (addr_list != NULL)
1631 free_wordlist(addr_list);
1637 * free_wordlist - release memory allocated for a wordlist.
1641 struct wordlist *wp;
1643 struct wordlist *next;
1645 while (wp != NULL) {
1653 * auth_script_done - called when the auth-up or auth-down script
1657 auth_script_done(arg)
1660 auth_script_pid = 0;
1661 switch (auth_script_state) {
1663 if (auth_state == s_down) {
1664 auth_script_state = s_down;
1665 auth_script(_PATH_AUTHDOWN);
1669 if (auth_state == s_up) {
1670 auth_script_state = s_up;
1671 auth_script(_PATH_AUTHUP);
1678 * auth_script - execute a script with arguments
1679 * interface-name peer-name real-user tty speed
1691 if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
1692 user_name = pw->pw_name;
1694 slprintf(struid, sizeof(struid), "%d", getuid());
1697 slprintf(strspeed, sizeof(strspeed), "%d", baud_rate);
1701 argv[2] = peer_authname;
1702 argv[3] = user_name;
1707 auth_script_pid = run_program(script, argv, 0, auth_script_done, NULL);