Home | History | Annotate | Line # | Download | only in pam_ssh
pam_ssh.c revision 1.7
      1 /*	$NetBSD: pam_ssh.c,v 1.7 2005/03/14 05:45:48 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2003 Networks Associates Technology, Inc.
      5  * All rights reserved.
      6  *
      7  * This software was developed for the FreeBSD Project by ThinkSec AS and
      8  * NAI Labs, the Security Research Division of Network Associates, Inc.
      9  * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
     10  * DARPA CHATS research program.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. The name of the author may not be used to endorse or promote
     21  *    products derived from this software without specific prior written
     22  *    permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  */
     36 
     37 #include <sys/cdefs.h>
     38 #ifdef __FreeBSD__
     39 __FBSDID("$FreeBSD: src/lib/libpam/modules/pam_ssh/pam_ssh.c,v 1.40 2004/02/10 10:13:21 des Exp $");
     40 #else
     41 __RCSID("$NetBSD: pam_ssh.c,v 1.7 2005/03/14 05:45:48 christos Exp $");
     42 #endif
     43 
     44 #include <sys/param.h>
     45 #include <sys/wait.h>
     46 
     47 #include <errno.h>
     48 #include <fcntl.h>
     49 #include <paths.h>
     50 #include <pwd.h>
     51 #include <signal.h>
     52 #include <stdio.h>
     53 #include <string.h>
     54 #include <unistd.h>
     55 
     56 #define PAM_SM_AUTH
     57 #define PAM_SM_SESSION
     58 
     59 #include <security/pam_appl.h>
     60 #include <security/pam_modules.h>
     61 #include <security/openpam.h>
     62 
     63 #include <openssl/evp.h>
     64 
     65 #include "key.h"
     66 #include "auth.h"
     67 #include "authfd.h"
     68 #include "authfile.h"
     69 
     70 extern char **environ;
     71 
     72 struct pam_ssh_key {
     73 	Key	*key;
     74 	char	*comment;
     75 };
     76 
     77 static const char *pam_ssh_prompt = "SSH passphrase: ";
     78 static const char *pam_ssh_have_keys = "pam_ssh_have_keys";
     79 
     80 static const char *pam_ssh_keyfiles[] = {
     81 	".ssh/identity",	/* SSH1 RSA key */
     82 	".ssh/id_rsa",		/* SSH2 RSA key */
     83 	".ssh/id_dsa",		/* SSH2 DSA key */
     84 	NULL
     85 };
     86 
     87 static const char *pam_ssh_agent = "/usr/bin/ssh-agent";
     88 static const char *pam_ssh_agent_argv[] = { "ssh_agent", "-s", NULL };
     89 static const char *pam_ssh_agent_envp[] = { NULL };
     90 
     91 /*
     92  * Attempts to load a private key from the specified file in the specified
     93  * directory, using the specified passphrase.  If successful, returns a
     94  * struct pam_ssh_key containing the key and its comment.
     95  */
     96 static struct pam_ssh_key *
     97 pam_ssh_load_key(struct passwd *pwd, const char *kfn, const char *passphrase)
     98 {
     99 	struct pam_ssh_key *psk;
    100 	char fn[PATH_MAX];
    101 	char *comment;
    102 	Key *key;
    103 
    104 	if (snprintf(fn, sizeof(fn), "%s/%s", pwd->pw_dir, kfn) >
    105 	    (int)sizeof(fn))
    106 		return (NULL);
    107 	comment = NULL;
    108 	key = key_load_private(fn, passphrase, &comment);
    109 	if (key == NULL) {
    110 		openpam_log(PAM_LOG_DEBUG, "failed to load key from %s\n", fn);
    111 		return (NULL);
    112 	}
    113 	if (!user_key_allowed(pwd, key)) {
    114 		openpam_log(PAM_LOG_DEBUG, "key from %s not authorized\n", fn);
    115 		goto out;
    116 	}
    117 
    118 	openpam_log(PAM_LOG_DEBUG, "loaded '%s' from %s\n", comment, fn);
    119 	if ((psk = malloc(sizeof(*psk))) == NULL) {
    120 out:
    121 		key_free(key);
    122 		free(comment);
    123 		return (NULL);
    124 	}
    125 	psk->key = key;
    126 	psk->comment = comment;
    127 	return (psk);
    128 }
    129 
    130 /*
    131  * Wipes a private key and frees the associated resources.
    132  */
    133 static void
    134 pam_ssh_free_key(pam_handle_t *pamh __unused,
    135     void *data, int pam_err __unused)
    136 {
    137 	struct pam_ssh_key *psk;
    138 
    139 	psk = data;
    140 	key_free(psk->key);
    141 	free(psk->comment);
    142 	free(psk);
    143 }
    144 
    145 PAM_EXTERN int
    146 pam_sm_authenticate(pam_handle_t *pamh, int flags __unused,
    147     int argc __unused, const char *argv[] __unused)
    148 {
    149 	const char **kfn, *passphrase, *user;
    150 	struct passwd *pwd;
    151 	struct pam_ssh_key *psk;
    152 	int nkeys, pam_err, pass;
    153 
    154 	/* PEM is not loaded by default */
    155 	OpenSSL_add_all_algorithms();
    156 
    157 	/* get user name and home directory */
    158 	pam_err = pam_get_user(pamh, &user, NULL);
    159 	if (pam_err != PAM_SUCCESS)
    160 		return (pam_err);
    161 	pwd = getpwnam(user);
    162 	if (pwd == NULL)
    163 		return (PAM_USER_UNKNOWN);
    164 	if (pwd->pw_dir == NULL)
    165 		return (PAM_AUTH_ERR);
    166 
    167 	/* switch to user credentials */
    168 	pam_err = openpam_borrow_cred(pamh, pwd);
    169 	if (pam_err != PAM_SUCCESS)
    170 		return (pam_err);
    171 
    172 #ifdef notyet
    173 	for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
    174 		char path[MAXPATHLEN];
    175 		(void)snprintf(path, sizeof(path), "%s/%s", pwd->pw_dir, *kfn);
    176 		if (access(path, R_OK) == 0)
    177 			break;
    178 	}
    179 
    180 	if (*kfn == NULL) {
    181 		openpam_restore_cred(pamh);
    182 		return (PAM_AUTH_ERR);
    183 	}
    184 #endif
    185 
    186 	pass = (pam_get_item(pamh, PAM_AUTHTOK,
    187 	    (const void **)__UNCONST(&passphrase)) == PAM_SUCCESS);
    188  load_keys:
    189 	/* get passphrase */
    190 	pam_err = pam_get_authtok(pamh, PAM_AUTHTOK,
    191 	    &passphrase, pam_ssh_prompt);
    192 	if (pam_err != PAM_SUCCESS) {
    193 		openpam_restore_cred(pamh);
    194 		return (pam_err);
    195 	}
    196 
    197 	/* try to load keys from all keyfiles we know of */
    198 	nkeys = 0;
    199 	for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
    200 		psk = pam_ssh_load_key(pwd, *kfn, passphrase);
    201 		if (psk != NULL) {
    202 			pam_set_data(pamh, *kfn, psk, pam_ssh_free_key);
    203 			++nkeys;
    204 		}
    205 	}
    206 
    207 	/*
    208 	 * If we tried an old token and didn't get anything, and
    209 	 * try_first_pass was specified, try again after prompting the
    210 	 * user for a new passphrase.
    211 	 */
    212 	if (nkeys == 0 && pass == 1 &&
    213 	    openpam_get_option(pamh, "try_first_pass") != NULL) {
    214 		pam_set_item(pamh, PAM_AUTHTOK, NULL);
    215 		pass = 0;
    216 		goto load_keys;
    217 	}
    218 
    219 	/* switch back to arbitrator credentials before returning */
    220 	openpam_restore_cred(pamh);
    221 
    222 	/* no keys? */
    223 	if (nkeys == 0)
    224 		return (PAM_AUTH_ERR);
    225 
    226 	pam_set_data(pamh, pam_ssh_have_keys, NULL, NULL);
    227 	return (PAM_SUCCESS);
    228 }
    229 
    230 PAM_EXTERN int
    231 pam_sm_setcred(pam_handle_t *pamh __unused, int flags __unused,
    232     int argc __unused, const char *argv[] __unused)
    233 {
    234 
    235 	return (PAM_SUCCESS);
    236 }
    237 
    238 /*
    239  * Parses a line from ssh-agent's output.
    240  */
    241 static void
    242 pam_ssh_process_agent_output(pam_handle_t *pamh, FILE *f)
    243 {
    244 	char *line, *p, *key, *val;
    245 	size_t len;
    246 
    247 	while ((line = fgetln(f, &len)) != NULL) {
    248 		if (len < 4 || strncmp(line, "SSH_", 4) != 0)
    249 			continue;
    250 
    251 		/* find equal sign at end of key */
    252 		for (p = key = line; p < line + len; ++p)
    253 			if (*p == '=')
    254 				break;
    255 		if (p == line + len || *p != '=')
    256 			continue;
    257 		*p = '\0';
    258 
    259 		/* find semicolon at end of value */
    260 		for (val = ++p; p < line + len; ++p)
    261 			if (*p == ';')
    262 				break;
    263 		if (p == line + len || *p != ';')
    264 			continue;
    265 		*p = '\0';
    266 
    267 		/* store key-value pair in environment */
    268 		openpam_log(PAM_LOG_DEBUG, "got %s: %s", key, val);
    269 		pam_setenv(pamh, key, val, 1);
    270 	}
    271 }
    272 
    273 /*
    274  * Starts an ssh agent and stores the environment variables derived from
    275  * its output.
    276  */
    277 static int
    278 pam_ssh_start_agent(pam_handle_t *pamh, struct passwd *pwd)
    279 {
    280 	int agent_pipe[2];
    281 	pid_t pid;
    282 	FILE *f;
    283 
    284 	/* get a pipe which we will use to read the agent's output */
    285 	if (pipe(agent_pipe) == -1)
    286 		return (PAM_SYSTEM_ERR);
    287 
    288 	/* start the agent */
    289 	openpam_log(PAM_LOG_DEBUG, "starting an ssh agent");
    290 	pid = fork();
    291 	if (pid == (pid_t)-1) {
    292 		/* failed */
    293 		close(agent_pipe[0]);
    294 		close(agent_pipe[1]);
    295 		return (PAM_SYSTEM_ERR);
    296 	}
    297 	if (pid == 0) {
    298 #ifndef F_CLOSEM
    299 		int fd;
    300 #endif
    301 		/* child: drop privs, close fds and start agent */
    302 		if (setgid(pwd->pw_gid) == -1) {
    303 			openpam_log(PAM_LOG_DEBUG, "%s: Cannot setgid %d (%m)",
    304 			    __FUNCTION__, (int)pwd->pw_gid);
    305 			goto done;
    306 		}
    307 		if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
    308 			openpam_log(PAM_LOG_DEBUG,
    309 			    "%s: Cannot initgroups for %s (%m)",
    310 			    __FUNCTION__, pwd->pw_name);
    311 			goto done;
    312 		}
    313 		if (setuid(pwd->pw_uid) == -1) {
    314 			openpam_log(PAM_LOG_DEBUG, "%s: Cannot setuid %d (%m)",
    315 			    __FUNCTION__, (int)pwd->pw_uid);
    316 			goto done;
    317 		}
    318 		(void)close(STDIN_FILENO);
    319 		(void)open(_PATH_DEVNULL, O_RDONLY);
    320 		(void)dup2(agent_pipe[1], STDOUT_FILENO);
    321 		(void)dup2(agent_pipe[1], STDERR_FILENO);
    322 #ifdef F_CLOSEM
    323 		(void)fcntl(3, F_CLOSEM, 0);
    324 #else
    325 		for (fd = 3; fd < getdtablesize(); ++fd)
    326 			(void)close(fd);
    327 #endif
    328 		(void)execve(pam_ssh_agent,
    329 		    (char **)__UNCONST(pam_ssh_agent_argv),
    330 		    (char **)__UNCONST(pam_ssh_agent_envp));
    331 done:
    332 		_exit(127);
    333 	}
    334 
    335 	/* parent */
    336 	close(agent_pipe[1]);
    337 	if ((f = fdopen(agent_pipe[0], "r")) == NULL)
    338 		return (PAM_SYSTEM_ERR);
    339 	pam_ssh_process_agent_output(pamh, f);
    340 	fclose(f);
    341 
    342 	return (PAM_SUCCESS);
    343 }
    344 
    345 /*
    346  * Adds previously stored keys to a running agent.
    347  */
    348 static int
    349 pam_ssh_add_keys_to_agent(pam_handle_t *pamh)
    350 {
    351 	AuthenticationConnection *ac;
    352 	struct pam_ssh_key *psk;
    353 	const char **kfn;
    354 	char **envlist, **env;
    355 	int pam_err;
    356 
    357 	/* switch to PAM environment */
    358 	envlist = environ;
    359 	if ((environ = pam_getenvlist(pamh)) == NULL) {
    360 		openpam_log(PAM_LOG_DEBUG, "%s: cannot get envlist",
    361 		    __FUNCTION__);
    362 		environ = envlist;
    363 		return (PAM_SYSTEM_ERR);
    364 	}
    365 
    366 	/* get a connection to the agent */
    367 	if ((ac = ssh_get_authentication_connection()) == NULL) {
    368 		openpam_log(PAM_LOG_DEBUG,
    369 		    "%s: cannot get authentication connection",
    370 		    __FUNCTION__);
    371 		pam_err = PAM_SYSTEM_ERR;
    372 		goto end;
    373 	}
    374 
    375 	/* look for keys to add to it */
    376 	for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
    377 		pam_err = pam_get_data(pamh, *kfn, (void **)__UNCONST(&psk));
    378 		if (pam_err == PAM_SUCCESS && psk != NULL) {
    379 			if (ssh_add_identity(ac, psk->key, psk->comment))
    380 				openpam_log(PAM_LOG_DEBUG,
    381 				    "added %s to ssh agent", psk->comment);
    382 			else
    383 				openpam_log(PAM_LOG_DEBUG, "failed "
    384 				    "to add %s to ssh agent", psk->comment);
    385 			/* we won't need the key again, so wipe it */
    386 			pam_set_data(pamh, *kfn, NULL, NULL);
    387 		}
    388 	}
    389 	pam_err = PAM_SUCCESS;
    390  end:
    391 	/* disconnect from agent */
    392 	if (ac != NULL)
    393 		ssh_close_authentication_connection(ac);
    394 
    395 	/* switch back to original environment */
    396 	for (env = environ; *env != NULL; ++env)
    397 		free(*env);
    398 	free(environ);
    399 	environ = envlist;
    400 
    401 	return (pam_err);
    402 }
    403 
    404 PAM_EXTERN int
    405 pam_sm_open_session(pam_handle_t *pamh, int flags __unused,
    406     int argc __unused, const char *argv[] __unused)
    407 {
    408 	struct passwd *pwd;
    409 	const char *user;
    410 	void *data;
    411 	int pam_err = PAM_SUCCESS;
    412 
    413 	/* no keys, no work */
    414 	if (pam_get_data(pamh, pam_ssh_have_keys, &data) != PAM_SUCCESS &&
    415 	    openpam_get_option(pamh, "want_agent") == NULL)
    416 		return (PAM_SUCCESS);
    417 
    418 	/* switch to user credentials */
    419 	pam_err = pam_get_user(pamh, &user, NULL);
    420 	if (pam_err != PAM_SUCCESS)
    421 		return (pam_err);
    422 	pwd = getpwnam(user);
    423 	if (pwd == NULL)
    424 		return (PAM_USER_UNKNOWN);
    425 
    426 	/* start the agent */
    427 	pam_err = pam_ssh_start_agent(pamh, pwd);
    428 	if (pam_err != PAM_SUCCESS)
    429 		return pam_err;
    430 
    431 	pam_err = openpam_borrow_cred(pamh, pwd);
    432 	if (pam_err != PAM_SUCCESS)
    433 		return pam_err;
    434 
    435 	/* we have an agent, see if we can add any keys to it */
    436 	pam_err = pam_ssh_add_keys_to_agent(pamh);
    437 	if (pam_err != PAM_SUCCESS) {
    438 		/* XXX ignore failures */
    439 		openpam_log(PAM_LOG_DEBUG, "failed adding keys to ssh agent");
    440 		pam_err = PAM_SUCCESS;
    441 	}
    442 
    443 	openpam_restore_cred(pamh);
    444 	return pam_err;
    445 }
    446 
    447 PAM_EXTERN int
    448 pam_sm_close_session(pam_handle_t *pamh, int flags __unused,
    449     int argc __unused, const char *argv[] __unused)
    450 {
    451 	const char *ssh_agent_pid;
    452 	char *end;
    453 	int status;
    454 	pid_t pid;
    455 
    456 	if ((ssh_agent_pid = pam_getenv(pamh, "SSH_AGENT_PID")) == NULL) {
    457 		openpam_log(PAM_LOG_DEBUG, "no ssh agent");
    458 		return (PAM_SUCCESS);
    459 	}
    460 	pid = (pid_t)strtol(ssh_agent_pid, &end, 10);
    461 	if (*ssh_agent_pid == '\0' || *end != '\0') {
    462 		openpam_log(PAM_LOG_DEBUG, "invalid ssh agent pid");
    463 		return (PAM_SESSION_ERR);
    464 	}
    465 	openpam_log(PAM_LOG_DEBUG, "killing ssh agent %d", (int)pid);
    466 	if (kill(pid, SIGTERM) == -1 ||
    467 	    (waitpid(pid, &status, 0) == -1 && errno != ECHILD))
    468 		return (PAM_SYSTEM_ERR);
    469 	return (PAM_SUCCESS);
    470 }
    471 
    472 PAM_MODULE_ENTRY("pam_ssh");
    473