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.
35 #define RCSID "$Id: auth.c,v 1.71 2001/11/09 10:33:42 paulus Exp $"
44 #include <sys/types.h>
46 #include <sys/socket.h>
49 #if defined(_PATH_LASTLOG) && defined(_linux_)
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
58 #include <security/pam_appl.h>
64 #define PW_PPP PW_LOGIN
77 #include "pathnames.h"
79 static const char rcsid[] = RCSID;
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 /* Wordlist giving addresses which the peer may use
100 without authenticating itself. */
101 static struct wordlist *noauth_addrs;
103 /* Extra options to apply, from the secrets file entry for the peer. */
104 static struct wordlist *extra_options;
106 /* Number of network protocols which we have opened. */
107 static int num_np_open;
109 /* Number of network protocols which have come up. */
110 static int num_np_up;
112 /* Set if we got the contents of passwd[] from the pap-secrets file. */
113 static int passwd_from_file;
115 /* Set if we require authentication only because we have a default route. */
116 static bool default_auth;
118 /* Hook to enable a plugin to control the idle time limit */
119 int (*idle_time_hook) __P((struct ppp_idle *)) = NULL;
121 /* Hook for a plugin to say whether we can possibly authenticate any peer */
122 int (*pap_check_hook) __P((void)) = NULL;
124 /* Hook for a plugin to check the PAP user and password */
125 int (*pap_auth_hook) __P((char *user, char *passwd, char **msgp,
126 struct wordlist **paddrs,
127 struct wordlist **popts)) = NULL;
129 /* Hook for a plugin to know about the PAP user logout */
130 void (*pap_logout_hook) __P((void)) = NULL;
132 /* Hook for a plugin to get the PAP password for authenticating us */
133 int (*pap_passwd_hook) __P((char *user, char *passwd)) = NULL;
135 /* Hook for a plugin to say whether it is OK if the peer
136 refuses to authenticate. */
137 int (*null_auth_hook) __P((struct wordlist **paddrs,
138 struct wordlist **popts)) = NULL;
140 /* A notifier for when the peer has authenticated itself,
141 and we are proceeding to the network phase. */
142 struct notifier *auth_up_notifier = NULL;
144 /* A notifier for when the link goes down. */
145 struct notifier *link_down_notifier = NULL;
148 * This is used to ensure that we don't start an auth-up/down
149 * script while one is already running.
156 static enum script_state auth_state = s_down;
157 static enum script_state auth_script_state = s_down;
158 static pid_t auth_script_pid = 0;
160 static int used_login; /* peer authenticated against login database */
165 bool uselogin = 0; /* Use /etc/passwd for checking PAP */
166 bool cryptpap = 0; /* Passwords in pap-secrets are encrypted */
167 bool refuse_pap = 0; /* Don't wanna auth. ourselves with PAP */
168 bool refuse_chap = 0; /* Don't wanna auth. ourselves with CHAP */
169 bool usehostname = 0; /* Use hostname for our_name */
170 bool auth_required = 0; /* Always require authentication from peer */
171 bool allow_any_ip = 0; /* Allow peer to use any IP address */
172 bool explicit_remote = 0; /* User specified explicit remote name */
173 char remote_name[MAXNAMELEN]; /* Peer's name for authentication */
175 static char *uafname; /* name of most recent +ua file */
177 /* Bits in auth_pending[] */
178 #define PAP_WITHPEER 1
180 #define CHAP_WITHPEER 4
183 extern char *crypt __P((const char *, const char *));
185 /* Prototypes for procedures local to this file. */
187 static void network_phase __P((int));
188 static void check_idle __P((void *));
189 static void connect_time_expired __P((void *));
190 static int plogin __P((char *, char *, char **));
191 static void plogout __P((void));
192 static int null_login __P((int));
193 static int get_pap_passwd __P((char *));
194 static int have_pap_secret __P((int *));
195 static int have_chap_secret __P((char *, char *, int, int *));
196 static int ip_addr_check __P((u_int32_t, struct permitted_ip *));
197 static int scan_authfile __P((FILE *, char *, char *, char *,
198 struct wordlist **, struct wordlist **,
200 static void free_wordlist __P((struct wordlist *));
201 static void auth_script __P((char *));
202 static void auth_script_done __P((void *));
203 static void set_allowed_addrs __P((int, struct wordlist *, struct wordlist *));
204 static int some_ip_ok __P((struct wordlist *));
205 static int setupapfile __P((char **));
206 static int privgroup __P((char **));
207 static int set_noauth_addr __P((char **));
208 static void check_access __P((FILE *, char *));
209 static int wordlist_count __P((struct wordlist *));
212 * Authentication-related options.
214 option_t auth_options[] = {
215 { "auth", o_bool, &auth_required,
216 "Require authentication from peer", OPT_PRIO | 1 },
217 { "noauth", o_bool, &auth_required,
218 "Don't require peer to authenticate", OPT_PRIOSUB | OPT_PRIV,
220 { "require-pap", o_bool, &lcp_wantoptions[0].neg_upap,
221 "Require PAP authentication from peer",
222 OPT_PRIOSUB | 1, &auth_required },
223 { "+pap", o_bool, &lcp_wantoptions[0].neg_upap,
224 "Require PAP authentication from peer",
225 OPT_ALIAS | OPT_PRIOSUB | 1, &auth_required },
226 { "require-chap", o_bool, &lcp_wantoptions[0].neg_chap,
227 "Require CHAP authentication from peer",
228 OPT_PRIOSUB | 1, &auth_required },
229 { "+chap", o_bool, &lcp_wantoptions[0].neg_chap,
230 "Require CHAP authentication from peer",
231 OPT_ALIAS | OPT_PRIOSUB | 1, &auth_required },
233 { "refuse-pap", o_bool, &refuse_pap,
234 "Don't agree to auth to peer with PAP", 1 },
235 { "-pap", o_bool, &refuse_pap,
236 "Don't allow PAP authentication with peer", OPT_ALIAS | 1 },
238 { "refuse-chap", o_bool, &refuse_chap,
239 "Don't agree to auth to peer with CHAP", 1 },
240 { "-chap", o_bool, &refuse_chap,
241 "Don't allow CHAP authentication with peer", OPT_ALIAS | 1 },
243 { "name", o_string, our_name,
244 "Set local name for authentication",
245 OPT_PRIO | OPT_PRIV | OPT_STATIC, NULL, MAXNAMELEN },
247 { "+ua", o_special, (void *)setupapfile,
248 "Get PAP user and password from file",
249 OPT_PRIO | OPT_A2STRVAL, &uafname },
251 { "user", o_string, user,
252 "Set name for auth with peer", OPT_PRIO | OPT_STATIC, NULL, MAXNAMELEN },
254 { "password", o_string, passwd,
255 "Password for authenticating us to the peer",
256 OPT_PRIO | OPT_STATIC | OPT_HIDE, NULL, MAXSECRETLEN },
258 { "usehostname", o_bool, &usehostname,
259 "Must use hostname for authentication", 1 },
261 { "remotename", o_string, remote_name,
262 "Set remote name for authentication", OPT_PRIO | OPT_STATIC,
263 &explicit_remote, MAXNAMELEN },
265 { "login", o_bool, &uselogin,
266 "Use system password database for PAP", 1 },
268 { "papcrypt", o_bool, &cryptpap,
269 "PAP passwords are encrypted", 1 },
271 { "privgroup", o_special, (void *)privgroup,
272 "Allow group members to use privileged options", OPT_PRIV | OPT_A2LIST },
274 { "allow-ip", o_special, (void *)set_noauth_addr,
275 "Set IP address(es) which can be used without authentication",
276 OPT_PRIV | OPT_A2LIST },
282 * setupapfile - specifies UPAP info for authenticating with peer.
290 char u[MAXNAMELEN], p[MAXSECRETLEN];
293 lcp_allowoptions[0].neg_upap = 1;
295 /* open user info file */
296 fname = strdup(*argv);
298 novm("+ua file name");
300 ufile = fopen(fname, "r");
303 option_error("unable to open user login data file %s", fname);
306 check_access(ufile, fname);
310 if (fgets(u, MAXNAMELEN - 1, ufile) == NULL
311 || fgets(p, MAXSECRETLEN - 1, ufile) == NULL){
312 option_error("unable to read user login data file %s", fname);
317 /* get rid of newlines */
319 if (l > 0 && u[l-1] == '\n')
322 if (l > 0 && p[l-1] == '\n')
325 if (override_value("user", option_priority, fname))
326 strlcpy(user, u, sizeof(user));
327 if (override_value("passwd", option_priority, fname))
328 strlcpy(passwd, p, sizeof(passwd));
335 * privgroup - allow members of the group to have privileged access.
346 option_error("group %s is unknown", *argv);
349 for (i = 0; i < ngroups; ++i) {
350 if (groups[i] == g->gr_gid) {
360 * set_noauth_addr - set address(es) that can be used without authentication.
361 * Equivalent to specifying an entry like `"" * "" addr' in pap-secrets.
364 set_noauth_addr(argv)
368 int l = strlen(addr) + 1;
371 wp = (struct wordlist *) malloc(sizeof(struct wordlist) + l);
373 novm("allow-ip argument");
374 wp->word = (char *) (wp + 1);
375 wp->next = noauth_addrs;
376 BCOPY(addr, wp->word, l);
383 * An Open on LCP has requested a change from Dead to Establish phase.
384 * Do what's necessary to bring the physical layer up.
393 * LCP has terminated the link; go to the Dead phase and take the
394 * physical layer down.
397 link_terminated(unit)
400 if (phase == PHASE_DEAD)
402 if (pap_logout_hook) {
408 new_phase(PHASE_DEAD);
409 notice("Connection terminated.");
413 * LCP has gone down; it will either die or try to re-establish.
420 struct protent *protp;
422 notify(link_down_notifier, 0);
424 if (auth_script_state == s_up && auth_script_pid == 0) {
425 update_link_stats(unit);
426 auth_script_state = s_down;
427 auth_script(_PATH_AUTHDOWN);
429 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
430 if (!protp->enabled_flag)
432 if (protp->protocol != PPP_LCP && protp->lowerdown != NULL)
433 (*protp->lowerdown)(unit);
434 if (protp->protocol < 0xC000 && protp->close != NULL)
435 (*protp->close)(unit, "LCP down");
439 if (phase != PHASE_DEAD)
440 new_phase(PHASE_ESTABLISH);
444 * The link is established.
445 * Proceed to the Dead, Authenticate or Network phase as appropriate.
448 link_established(unit)
452 lcp_options *wo = &lcp_wantoptions[unit];
453 lcp_options *go = &lcp_gotoptions[unit];
454 lcp_options *ho = &lcp_hisoptions[unit];
456 struct protent *protp;
459 * Tell higher-level protocols that LCP is up.
461 for (i = 0; (protp = protocols[i]) != NULL; ++i)
462 if (protp->protocol != PPP_LCP && protp->enabled_flag
463 && protp->lowerup != NULL)
464 (*protp->lowerup)(unit);
466 if (auth_required && !(go->neg_chap || go->neg_upap)) {
468 * We wanted the peer to authenticate itself, and it refused:
469 * if we have some address(es) it can use without auth, fine,
470 * otherwise treat it as though it authenticated with PAP using
471 * a username * of "" and a password of "". If that's not OK,
474 if (noauth_addrs != NULL) {
475 set_allowed_addrs(unit, NULL, NULL);
476 } else if (!wo->neg_upap || uselogin || !null_login(unit)) {
477 warn("peer refused to authenticate: terminating link");
478 lcp_close(unit, "peer refused to authenticate");
479 status = EXIT_PEER_AUTH_FAILED;
484 new_phase(PHASE_AUTHENTICATE);
488 ChapAuthPeer(unit, our_name, go->chap_mdtype);
490 } else if (go->neg_upap) {
495 ChapAuthWithPeer(unit, user, ho->chap_mdtype);
496 auth |= CHAP_WITHPEER;
497 } else if (ho->neg_upap) {
498 if (passwd[0] == 0) {
499 passwd_from_file = 1;
500 if (!get_pap_passwd(passwd))
501 error("No secret found for PAP login");
503 upap_authwithpeer(unit, user, passwd);
504 auth |= PAP_WITHPEER;
506 auth_pending[unit] = auth;
513 * Proceed to the network phase.
519 lcp_options *go = &lcp_gotoptions[unit];
522 * If the peer had to authenticate, run the auth-up script now.
524 if (go->neg_chap || go->neg_upap) {
525 notify(auth_up_notifier, 0);
527 if (auth_script_state == s_down && auth_script_pid == 0) {
528 auth_script_state = s_up;
529 auth_script(_PATH_AUTHUP);
535 * If we negotiated callback, do it now.
538 new_phase(PHASE_CALLBACK);
539 (*cbcp_protent.open)(unit);
545 * Process extra options from the secrets file
548 options_from_list(extra_options, 1);
549 free_wordlist(extra_options);
559 struct protent *protp;
561 new_phase(PHASE_NETWORK);
563 #ifdef HAVE_MULTILINK
565 if (mp_join_bundle()) {
566 if (updetach && !nodetach)
571 #endif /* HAVE_MULTILINK */
575 set_filters(&pass_filter, &active_filter);
577 for (i = 0; (protp = protocols[i]) != NULL; ++i)
578 if (protp->protocol < 0xC000 && protp->enabled_flag
579 && protp->open != NULL) {
581 if (protp->protocol != PPP_CCP)
585 if (num_np_open == 0)
587 lcp_close(0, "No network protocols running");
591 * The peer has failed to authenticate himself using `protocol'.
594 auth_peer_fail(unit, protocol)
598 * Authentication failure: take the link down
600 lcp_close(unit, "Authentication failed");
601 status = EXIT_PEER_AUTH_FAILED;
605 * The peer has been successfully authenticated using `protocol'.
608 auth_peer_success(unit, protocol, name, namelen)
623 warn("auth_peer_success: unknown protocol %x", protocol);
628 * Save the authenticated name of the peer for later.
630 if (namelen > sizeof(peer_authname) - 1)
631 namelen = sizeof(peer_authname) - 1;
632 BCOPY(name, peer_authname, namelen);
633 peer_authname[namelen] = 0;
634 script_setenv("PEERNAME", peer_authname, 0);
637 * If there is no more authentication still to be done,
638 * proceed to the network (or callback) phase.
640 if ((auth_pending[unit] &= ~bit) == 0)
645 * We have failed to authenticate ourselves to the peer using `protocol'.
648 auth_withpeer_fail(unit, protocol)
651 if (passwd_from_file)
652 BZERO(passwd, MAXSECRETLEN);
654 * We've failed to authenticate ourselves to our peer.
655 * Some servers keep sending CHAP challenges, but there
656 * is no point in persisting without any way to get updated
657 * authentication secrets.
659 lcp_close(unit, "Failed to authenticate ourselves to peer");
660 status = EXIT_AUTH_TOPEER_FAILED;
664 * We have successfully authenticated ourselves with the peer using `protocol'.
667 auth_withpeer_success(unit, protocol)
677 if (passwd_from_file)
678 BZERO(passwd, MAXSECRETLEN);
682 warn("auth_withpeer_success: unknown protocol %x", protocol);
687 * If there is no more authentication still being done,
688 * proceed to the network (or callback) phase.
690 if ((auth_pending[unit] &= ~bit) == 0)
696 * np_up - a network protocol has come up.
704 if (num_np_up == 0) {
706 * At this point we consider that the link has come up successfully.
710 new_phase(PHASE_RUNNING);
712 if (idle_time_hook != 0)
713 tlim = (*idle_time_hook)(NULL);
715 tlim = idle_time_limit;
717 TIMEOUT(check_idle, NULL, tlim);
720 * Set a timeout to close the connection once the maximum
721 * connect time has expired.
724 TIMEOUT(connect_time_expired, 0, maxconnect);
727 * Detach now, if the updetach option was given.
729 if (updetach && !nodetach)
736 * np_down - a network protocol has gone down.
742 if (--num_np_up == 0) {
743 UNTIMEOUT(check_idle, NULL);
744 UNTIMEOUT(connect_time_expired, NULL);
745 new_phase(PHASE_NETWORK);
750 * np_finished - a network protocol has finished using the link.
753 np_finished(unit, proto)
756 if (--num_np_open <= 0) {
757 /* no further use for the link: shut up shop. */
758 lcp_close(0, "No network protocols running");
763 * check_idle - check whether the link has been idle for long
764 * enough that we can shut it down.
770 struct ppp_idle idle;
774 if (!get_idle_time(0, &idle))
776 if (idle_time_hook != 0) {
777 tlim = idle_time_hook(&idle);
779 itime = MIN(idle.xmit_idle, idle.recv_idle);
780 tlim = idle_time_limit - itime;
783 /* link is idle: shut it down. */
784 notice("Terminating connection due to lack of activity.");
785 lcp_close(0, "Link inactive");
787 status = EXIT_IDLE_TIMEOUT;
789 TIMEOUT(check_idle, NULL, tlim);
794 * connect_time_expired - log a message and close the connection.
797 connect_time_expired(arg)
800 info("Connect time expired");
801 lcp_close(0, "Connect time expired"); /* Close connection */
802 status = EXIT_CONNECT_TIME;
806 * auth_check_options - called to check authentication options.
811 lcp_options *wo = &lcp_wantoptions[0];
815 /* Default our_name to hostname, and user to our_name */
816 if (our_name[0] == 0 || usehostname)
817 strlcpy(our_name, hostname, sizeof(our_name));
819 strlcpy(user, our_name, sizeof(user));
822 * If we have a default route, require the peer to authenticate
823 * unless the noauth option was given or the real user is root.
825 if (!auth_required && !allow_any_ip && have_route_to(0) && !privileged) {
830 /* If authentication is required, ask peer for CHAP or PAP. */
833 if (!wo->neg_chap && !wo->neg_upap) {
843 * Check whether we have appropriate secrets to use
844 * to authenticate the peer.
847 can_auth = wo->neg_upap && (uselogin || have_pap_secret(&lacks_ip));
848 if (!can_auth && wo->neg_chap) {
849 can_auth = have_chap_secret((explicit_remote? remote_name: NULL),
850 our_name, 1, &lacks_ip);
853 if (auth_required && !can_auth && noauth_addrs == NULL) {
856 "By default the remote system is required to authenticate itself");
858 "(because this system has a default route to the internet)");
859 } else if (explicit_remote)
861 "The remote system (%s) is required to authenticate itself",
865 "The remote system is required to authenticate itself");
867 "but I couldn't find any suitable secret (password) for it to use to do so.");
870 "(None of the available passwords would let it use an IP address.)");
877 * auth_reset - called when LCP is starting negotiations to recheck
878 * authentication options, i.e. whether we have appropriate secrets
879 * to use for authenticating ourselves and/or the peer.
885 lcp_options *go = &lcp_gotoptions[unit];
886 lcp_options *ao = &lcp_allowoptions[0];
888 ao->neg_upap = !refuse_pap && (passwd[0] != 0 || get_pap_passwd(NULL));
889 ao->neg_chap = !refuse_chap
891 || have_chap_secret(user, (explicit_remote? remote_name: NULL),
894 if (go->neg_upap && !uselogin && !have_pap_secret(NULL))
897 if (!have_chap_secret((explicit_remote? remote_name: NULL),
905 * check_passwd - Check the user name and passwd against the PAP secrets
906 * file. If requested, also check against the system password database,
907 * and login the user if OK.
910 * UPAP_AUTHNAK: Authentication failed.
911 * UPAP_AUTHACK: Authentication succeeded.
912 * In either case, msg points to an appropriate message.
915 check_passwd(unit, auser, userlen, apasswd, passwdlen, msg)
926 struct wordlist *addrs = NULL, *opts = NULL;
927 char passwd[256], user[256];
928 char secret[MAXWORDLEN];
929 static int attempts = 0;
932 * Make copies of apasswd and auser, then null-terminate them.
933 * If there are unprintable characters in the password, make
936 slprintf(passwd, sizeof(passwd), "%.*v", passwdlen, apasswd);
937 slprintf(user, sizeof(user), "%.*v", userlen, auser);
941 * Check if a plugin wants to handle this.
944 ret = (*pap_auth_hook)(user, passwd, msg, &addrs, &opts);
947 set_allowed_addrs(unit, addrs, opts);
948 BZERO(passwd, sizeof(passwd));
950 free_wordlist(addrs);
951 return ret? UPAP_AUTHACK: UPAP_AUTHNAK;
956 * Open the file of pap secrets and scan for a suitable secret
957 * for authenticating this user.
959 filename = _PATH_UPAPFILE;
962 f = fopen(filename, "r");
964 error("Can't open PAP password file %s: %m", filename);
967 check_access(f, filename);
968 if (scan_authfile(f, user, our_name, secret, &addrs, &opts, filename) < 0) {
969 warn("no PAP secret found for %s", user);
972 * If the secret is "@login", it means to check
973 * the password against the login database.
975 int login_secret = strcmp(secret, "@login") == 0;
977 if (uselogin || login_secret) {
978 /* login option or secret is @login */
979 ret = plogin(user, passwd, msg);
980 if (ret == UPAP_AUTHNAK)
981 warn("PAP login failure for %s", user);
985 if (secret[0] != 0 && !login_secret) {
986 /* password given in pap-secrets - must match */
987 if ((cryptpap || strcmp(passwd, secret) != 0)
988 && strcmp(crypt(passwd, secret), secret) != 0) {
990 warn("PAP authentication failure for %s", user);
997 if (ret == UPAP_AUTHNAK) {
999 *msg = "Login incorrect";
1001 * XXX can we ever get here more than once??
1002 * Frustrate passwd stealer programs.
1003 * Allow 10 tries, but start backing off after 3 (stolen from login).
1004 * On 10'th, drop the connection.
1006 if (attempts++ >= 10) {
1007 warn("%d LOGIN FAILURES ON %s, %s", attempts, devnam, user);
1008 lcp_close(unit, "login failed");
1011 sleep((u_int) (attempts - 3) * 5);
1013 free_wordlist(opts);
1016 attempts = 0; /* Reset count */
1019 set_allowed_addrs(unit, addrs, opts);
1023 free_wordlist(addrs);
1024 BZERO(passwd, sizeof(passwd));
1025 BZERO(secret, sizeof(secret));
1031 * This function is needed for PAM.
1035 /* Static variables used to communicate between the conversation function
1036 * and the server_login function
1038 static char *PAM_username;
1039 static char *PAM_password;
1040 static int PAM_error = 0;
1041 static pam_handle_t *pamh = NULL;
1043 /* PAM conversation function
1044 * Here we assume (for now, at least) that echo on means login name, and
1045 * echo off means password.
1048 static int PAM_conv (int num_msg, const struct pam_message **msg,
1049 struct pam_response **resp, void *appdata_ptr)
1052 struct pam_response *reply = NULL;
1054 #define COPY_STRING(s) (s) ? strdup(s) : NULL
1056 reply = malloc(sizeof(struct pam_response) * num_msg);
1057 if (!reply) return PAM_CONV_ERR;
1059 for (replies = 0; replies < num_msg; replies++) {
1060 switch (msg[replies]->msg_style) {
1061 case PAM_PROMPT_ECHO_ON:
1062 reply[replies].resp_retcode = PAM_SUCCESS;
1063 reply[replies].resp = COPY_STRING(PAM_username);
1064 /* PAM frees resp */
1066 case PAM_PROMPT_ECHO_OFF:
1067 reply[replies].resp_retcode = PAM_SUCCESS;
1068 reply[replies].resp = COPY_STRING(PAM_password);
1069 /* PAM frees resp */
1074 /* ignore it, but pam still wants a NULL response... */
1075 reply[replies].resp_retcode = PAM_SUCCESS;
1076 reply[replies].resp = NULL;
1079 /* Must be an error of some sort... */
1082 return PAM_CONV_ERR;
1089 static struct pam_conv PAM_conversation = {
1093 #endif /* USE_PAM */
1096 * plogin - Check the user name and password against the system
1097 * password database, and login the user if OK.
1100 * UPAP_AUTHNAK: Login failed.
1101 * UPAP_AUTHACK: Login succeeded.
1102 * In either case, msg points to an appropriate message.
1106 plogin(user, passwd, msg)
1116 pam_error = pam_start ("ppp", user, &PAM_conversation, &pamh);
1117 if (pam_error != PAM_SUCCESS) {
1118 *msg = (char *) pam_strerror (pamh, pam_error);
1120 return UPAP_AUTHNAK;
1123 * Define the fields for the credential validation
1126 PAM_username = user;
1127 PAM_password = passwd;
1129 pam_set_item (pamh, PAM_TTY, devnam); /* this might be useful to some modules */
1134 pam_error = pam_authenticate (pamh, PAM_SILENT);
1135 if (pam_error == PAM_SUCCESS && !PAM_error) {
1136 pam_error = pam_acct_mgmt (pamh, PAM_SILENT);
1137 if (pam_error == PAM_SUCCESS)
1138 pam_open_session (pamh, PAM_SILENT);
1141 *msg = (char *) pam_strerror (pamh, pam_error);
1146 reopen_log(); /* apparently the PAM stuff does closelog() */
1147 PAM_username = NULL;
1148 PAM_password = NULL;
1149 if (pam_error != PAM_SUCCESS)
1150 return UPAP_AUTHNAK;
1151 #else /* #ifdef USE_PAM */
1154 * Use the non-PAM methods directly
1159 struct spwd *getspnam();
1161 struct passwd *pw = getpwnam(user);
1165 return (UPAP_AUTHNAK);
1168 spwd = getspnam(user);
1171 /* check the age of the password entry */
1172 long now = time(NULL) / 86400L;
1174 if ((spwd->sp_expire > 0 && now >= spwd->sp_expire)
1175 || ((spwd->sp_max >= 0 && spwd->sp_max < 10000)
1176 && spwd->sp_lstchg >= 0
1177 && now >= spwd->sp_lstchg + spwd->sp_max)) {
1178 warn("Password for %s has expired", user);
1179 return (UPAP_AUTHNAK);
1181 pw->pw_passwd = spwd->sp_pwdp;
1186 * If no passwd, don't let them login.
1188 if (pw->pw_passwd == NULL || strlen(pw->pw_passwd) < 2
1189 || strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd) != 0)
1190 return (UPAP_AUTHNAK);
1192 #endif /* #ifdef USE_PAM */
1195 * Write a wtmp entry for this user.
1199 if (strncmp(tty, "/dev/", 5) == 0)
1201 logwtmp(tty, user, remote_name); /* Add wtmp login entry */
1203 #if defined(_PATH_LASTLOG) && !defined(USE_PAM)
1204 if (pw != (struct passwd *)NULL) {
1208 if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
1209 (void)lseek(fd, (off_t)(pw->pw_uid * sizeof(ll)), SEEK_SET);
1210 memset((void *)&ll, 0, sizeof(ll));
1211 (void)time(&ll.ll_time);
1212 (void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
1213 (void)write(fd, (char *)&ll, sizeof(ll));
1217 #endif /* _PATH_LASTLOG and not USE_PAM */
1219 info("user %s logged in", user);
1222 return (UPAP_AUTHACK);
1226 * plogout - Logout the user.
1235 pam_error = pam_close_session (pamh, PAM_SILENT);
1236 pam_end (pamh, pam_error);
1239 /* Apparently the pam stuff does closelog(). */
1241 #else /* ! USE_PAM */
1245 if (strncmp(tty, "/dev/", 5) == 0)
1247 logwtmp(tty, "", ""); /* Wipe out utmp logout entry */
1248 #endif /* ! USE_PAM */
1254 * null_login - Check if a username of "" and a password of "" are
1255 * acceptable, and iff so, set the list of acceptable IP addresses
1265 struct wordlist *addrs, *opts;
1266 char secret[MAXWORDLEN];
1269 * Check if a plugin wants to handle this.
1273 ret = (*null_auth_hook)(&addrs, &opts);
1276 * Open the file of pap secrets and scan for a suitable secret.
1279 filename = _PATH_UPAPFILE;
1281 f = fopen(filename, "r");
1284 check_access(f, filename);
1286 i = scan_authfile(f, "", our_name, secret, &addrs, &opts, filename);
1287 ret = i >= 0 && secret[0] == 0;
1288 BZERO(secret, sizeof(secret));
1293 set_allowed_addrs(unit, addrs, opts);
1295 free_wordlist(opts);
1297 free_wordlist(addrs);
1304 * get_pap_passwd - get a password for authenticating ourselves with
1305 * our peer using PAP. Returns 1 on success, 0 if no suitable password
1307 * Assumes passwd points to MAXSECRETLEN bytes of space (if non-null).
1310 get_pap_passwd(passwd)
1316 char secret[MAXWORDLEN];
1319 * Check whether a plugin wants to supply this.
1321 if (pap_passwd_hook) {
1322 ret = (*pap_passwd_hook)(user, passwd);
1327 filename = _PATH_UPAPFILE;
1328 f = fopen(filename, "r");
1331 check_access(f, filename);
1332 ret = scan_authfile(f, user,
1333 (remote_name[0]? remote_name: NULL),
1334 secret, NULL, NULL, filename);
1339 strlcpy(passwd, secret, MAXSECRETLEN);
1340 BZERO(secret, sizeof(secret));
1346 * have_pap_secret - check whether we have a PAP file with any
1347 * secrets that we could possibly use for authenticating the peer.
1350 have_pap_secret(lacks_ipp)
1356 struct wordlist *addrs;
1358 /* let the plugin decide, if there is one */
1359 if (pap_check_hook) {
1360 ret = (*pap_check_hook)();
1365 filename = _PATH_UPAPFILE;
1366 f = fopen(filename, "r");
1370 ret = scan_authfile(f, (explicit_remote? remote_name: NULL), our_name,
1371 NULL, &addrs, NULL, filename);
1373 if (ret >= 0 && !some_ip_ok(addrs)) {
1379 free_wordlist(addrs);
1386 * have_chap_secret - check whether we have a CHAP file with a
1387 * secret that we could possibly use for authenticating `client'
1388 * on `server'. Either can be the null string, meaning we don't
1389 * know the identity yet.
1392 have_chap_secret(client, server, need_ip, lacks_ipp)
1401 struct wordlist *addrs;
1403 filename = _PATH_CHAPFILE;
1404 f = fopen(filename, "r");
1408 if (client != NULL && client[0] == 0)
1410 else if (server != NULL && server[0] == 0)
1413 ret = scan_authfile(f, client, server, NULL, &addrs, NULL, filename);
1415 if (ret >= 0 && need_ip && !some_ip_ok(addrs)) {
1421 free_wordlist(addrs);
1428 * get_secret - open the CHAP secret file and return the secret
1429 * for authenticating the given client on the given server.
1430 * (We could be either client or server).
1433 get_secret(unit, client, server, secret, secret_len, am_server)
1444 struct wordlist *addrs, *opts;
1445 char secbuf[MAXWORDLEN];
1447 if (!am_server && passwd[0] != 0) {
1448 strlcpy(secbuf, passwd, sizeof(secbuf));
1450 filename = _PATH_CHAPFILE;
1454 f = fopen(filename, "r");
1456 error("Can't open chap secret file %s: %m", filename);
1459 check_access(f, filename);
1461 ret = scan_authfile(f, client, server, secbuf, &addrs, &opts, filename);
1467 set_allowed_addrs(unit, addrs, opts);
1469 free_wordlist(opts);
1471 free_wordlist(addrs);
1474 len = strlen(secbuf);
1475 if (len > MAXSECRETLEN) {
1476 error("Secret for %s on %s is too long", client, server);
1479 BCOPY(secbuf, secret, len);
1480 BZERO(secbuf, sizeof(secbuf));
1487 * set_allowed_addrs() - set the list of allowed addresses.
1488 * Also looks for `--' indicating options to apply for this peer
1489 * and leaves the following words in extra_options.
1492 set_allowed_addrs(unit, addrs, opts)
1494 struct wordlist *addrs;
1495 struct wordlist *opts;
1498 struct wordlist *ap, **plink;
1499 struct permitted_ip *ip;
1500 char *ptr_word, *ptr_mask;
1503 u_int32_t a, mask, ah, offset;
1504 struct ipcp_options *wo = &ipcp_wantoptions[unit];
1505 u_int32_t suggested_ip = 0;
1507 if (addresses[unit] != NULL)
1508 free(addresses[unit]);
1509 addresses[unit] = NULL;
1510 if (extra_options != NULL)
1511 free_wordlist(extra_options);
1512 extra_options = opts;
1515 * Count the number of IP addresses given.
1517 n = wordlist_count(addrs) + wordlist_count(noauth_addrs);
1520 ip = (struct permitted_ip *) malloc((n + 1) * sizeof(struct permitted_ip));
1524 /* temporarily append the noauth_addrs list to addrs */
1525 for (plink = &addrs; *plink != NULL; plink = &(*plink)->next)
1527 *plink = noauth_addrs;
1530 for (ap = addrs; ap != NULL; ap = ap->next) {
1531 /* "-" means no addresses authorized, "*" means any address allowed */
1532 ptr_word = ap->word;
1533 if (strcmp(ptr_word, "-") == 0)
1535 if (strcmp(ptr_word, "*") == 0) {
1537 ip[n].base = ip[n].mask = 0;
1543 if (*ptr_word == '!') {
1548 mask = ~ (u_int32_t) 0;
1550 ptr_mask = strchr (ptr_word, '/');
1551 if (ptr_mask != NULL) {
1555 bit_count = (int) strtol (ptr_mask+1, &endp, 10);
1556 if (bit_count <= 0 || bit_count > 32) {
1557 warn("invalid address length %v in auth. address list",
1561 bit_count = 32 - bit_count; /* # bits in host part */
1563 offset = ifunit + 1;
1567 warn("invalid address length syntax: %v", ptr_mask+1);
1574 hp = gethostbyname(ptr_word);
1575 if (hp != NULL && hp->h_addrtype == AF_INET) {
1576 a = *(u_int32_t *)hp->h_addr;
1578 np = getnetbyname (ptr_word);
1579 if (np != NULL && np->n_addrtype == AF_INET) {
1580 a = htonl (*(u_int32_t *)np->n_net);
1581 if (ptr_mask == NULL) {
1582 /* calculate appropriate mask for net */
1585 mask = IN_CLASSA_NET;
1586 else if (IN_CLASSB(ah))
1587 mask = IN_CLASSB_NET;
1588 else if (IN_CLASSC(ah))
1589 mask = IN_CLASSC_NET;
1592 a = inet_addr (ptr_word);
1596 if (ptr_mask != NULL)
1599 if (a == (u_int32_t)-1L) {
1600 warn("unknown host %s in auth. address list", ap->word);
1604 if (offset >= ~mask) {
1605 warn("interface unit %d too large for subnet %v",
1609 a = htonl((ntohl(a) & mask) + offset);
1610 mask = ~(u_int32_t)0;
1612 ip[n].mask = htonl(mask);
1613 ip[n].base = a & ip[n].mask;
1615 if (~mask == 0 && suggested_ip == 0)
1620 ip[n].permit = 0; /* make the last entry forbid all addresses */
1621 ip[n].base = 0; /* to terminate the list */
1624 addresses[unit] = ip;
1627 * If the address given for the peer isn't authorized, or if
1628 * the user hasn't given one, AND there is an authorized address
1629 * which is a single host, then use that if we find one.
1631 if (suggested_ip != 0
1632 && (wo->hisaddr == 0 || !auth_ip_addr(unit, wo->hisaddr))) {
1633 wo->hisaddr = suggested_ip;
1635 * Do we insist on this address? No, if there are other
1636 * addresses authorized than the suggested one.
1639 wo->accept_remote = 1;
1644 * auth_ip_addr - check whether the peer is authorized to use
1645 * a given IP address. Returns 1 if authorized, 0 otherwise.
1648 auth_ip_addr(unit, addr)
1654 /* don't allow loopback or multicast address */
1655 if (bad_ip_adrs(addr))
1658 if (addresses[unit] != NULL) {
1659 ok = ip_addr_check(addr, addresses[unit]);
1664 return 0; /* no addresses authorized */
1665 return allow_any_ip || privileged || !have_route_to(addr);
1669 ip_addr_check(addr, addrs)
1671 struct permitted_ip *addrs;
1674 if ((addr & addrs->mask) == addrs->base)
1675 return addrs->permit;
1679 * bad_ip_adrs - return 1 if the IP address is one we don't want
1680 * to use, such as an address in the loopback net or a multicast address.
1681 * addr is in network byte order.
1688 return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
1689 || IN_MULTICAST(addr) || IN_BADCLASS(addr);
1693 * some_ip_ok - check a wordlist to see if it authorizes any
1698 struct wordlist *addrs;
1700 for (; addrs != 0; addrs = addrs->next) {
1701 if (addrs->word[0] == '-')
1703 if (addrs->word[0] != '!')
1704 return 1; /* some IP address is allowed */
1710 * check_access - complain if a secret file has too-liberal permissions.
1713 check_access(f, filename)
1719 if (fstat(fileno(f), &sbuf) < 0) {
1720 warn("cannot stat secret file %s: %m", filename);
1721 } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1722 warn("Warning - secret file %s has world and/or group access",
1729 * scan_authfile - Scan an authorization file for a secret suitable
1730 * for authenticating `client' on `server'. The return value is -1
1731 * if no secret is found, otherwise >= 0. The return value has
1732 * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
1733 * NONWILD_SERVER set if the secret didn't have "*" for the server.
1734 * Any following words on the line up to a "--" (i.e. address authorization
1735 * info) are placed in a wordlist and returned in *addrs. Any
1736 * following words (extra options) are placed in a wordlist and
1737 * returned in *opts.
1738 * We assume secret is NULL or points to MAXWORDLEN bytes of space.
1741 scan_authfile(f, client, server, secret, addrs, opts, filename)
1746 struct wordlist **addrs;
1747 struct wordlist **opts;
1751 int got_flag, best_flag;
1753 struct wordlist *ap, *addr_list, *alist, **app;
1754 char word[MAXWORDLEN];
1755 char atfile[MAXWORDLEN];
1756 char lsecret[MAXWORDLEN];
1763 if (!getword(f, word, &newline, filename))
1764 return -1; /* file is empty??? */
1769 * Skip until we find a word at the start of a line.
1771 while (!newline && getword(f, word, &newline, filename))
1774 break; /* got to end of file */
1777 * Got a client - check if it's a match or a wildcard.
1780 if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
1785 got_flag = NONWILD_CLIENT;
1788 * Now get a server and check if it matches.
1790 if (!getword(f, word, &newline, filename))
1794 if (!ISWILD(word)) {
1795 if (server != NULL && strcmp(word, server) != 0)
1797 got_flag |= NONWILD_SERVER;
1801 * Got some sort of a match - see if it's better than what
1804 if (got_flag <= best_flag)
1810 if (!getword(f, word, &newline, filename))
1815 if (secret != NULL) {
1817 * Special syntax: @/pathname means read secret from file.
1819 if (word[0] == '@' && word[1] == '/') {
1820 strlcpy(atfile, word+1, sizeof(atfile));
1821 if ((sf = fopen(atfile, "r")) == NULL) {
1822 warn("can't open indirect secret file %s", atfile);
1825 check_access(sf, atfile);
1826 if (!getword(sf, word, &xxx, atfile)) {
1827 warn("no secret in indirect secret file %s", atfile);
1833 strlcpy(lsecret, word, sizeof(lsecret));
1837 * Now read address authorization info and make a wordlist.
1841 if (!getword(f, word, &newline, filename) || newline)
1843 ap = (struct wordlist *)
1844 malloc(sizeof(struct wordlist) + strlen(word) + 1);
1846 novm("authorized addresses");
1847 ap->word = (char *) (ap + 1);
1848 strcpy(ap->word, word);
1855 * This is the best so far; remember it.
1857 best_flag = got_flag;
1859 free_wordlist(addr_list);
1862 strlcpy(secret, lsecret, MAXWORDLEN);
1868 /* scan for a -- word indicating the start of options */
1869 for (app = &addr_list; (ap = *app) != NULL; app = &ap->next)
1870 if (strcmp(ap->word, "--") == 0)
1872 /* ap = start of options */
1874 ap = ap->next; /* first option */
1875 free(*app); /* free the "--" word */
1876 *app = NULL; /* terminate addr list */
1880 else if (ap != NULL)
1884 else if (addr_list != NULL)
1885 free_wordlist(addr_list);
1891 * wordlist_count - return the number of items in a wordlist
1895 struct wordlist *wp;
1899 for (n = 0; wp != NULL; wp = wp->next)
1905 * free_wordlist - release memory allocated for a wordlist.
1909 struct wordlist *wp;
1911 struct wordlist *next;
1913 while (wp != NULL) {
1921 * auth_script_done - called when the auth-up or auth-down script
1925 auth_script_done(arg)
1928 auth_script_pid = 0;
1929 switch (auth_script_state) {
1931 if (auth_state == s_down) {
1932 auth_script_state = s_down;
1933 auth_script(_PATH_AUTHDOWN);
1937 if (auth_state == s_up) {
1938 auth_script_state = s_up;
1939 auth_script(_PATH_AUTHUP);
1946 * auth_script - execute a script with arguments
1947 * interface-name peer-name real-user tty speed
1959 if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
1960 user_name = pw->pw_name;
1962 slprintf(struid, sizeof(struid), "%d", getuid());
1965 slprintf(strspeed, sizeof(strspeed), "%d", baud_rate);
1969 argv[2] = peer_authname;
1970 argv[3] = user_name;
1975 auth_script_pid = run_program(script, argv, 0, auth_script_done, NULL);