Home | History | Annotate | Line # | Download | only in pam_ssh
pam_ssh.c revision 1.12
      1 /*	$NetBSD: pam_ssh.c,v 1.12 2006/03/19 06:52:26 jnemeth 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.12 2006/03/19 06:52:26 jnemeth 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 "authfd.h"
     67 #include "authfile.h"
     68 
     69 extern char **environ;
     70 
     71 struct pam_ssh_key {
     72 	Key	*key;
     73 	char	*comment;
     74 };
     75 
     76 static const char *pam_ssh_prompt = "SSH passphrase: ";
     77 static const char *pam_ssh_have_keys = "pam_ssh_have_keys";
     78 
     79 static const char *pam_ssh_keyfiles[] = {
     80 	".ssh/identity",	/* SSH1 RSA key */
     81 	".ssh/id_rsa",		/* SSH2 RSA key */
     82 	".ssh/id_dsa",		/* SSH2 DSA key */
     83 	NULL
     84 };
     85 
     86 static const char *pam_ssh_agent = "/usr/bin/ssh-agent";
     87 static const char *pam_ssh_agent_argv[] = { "ssh_agent", "-s", NULL };
     88 static const char *pam_ssh_agent_envp[] = { NULL };
     89 
     90 /*
     91  * Attempts to load a private key from the specified file in the specified
     92  * directory, using the specified passphrase.  If successful, returns a
     93  * struct pam_ssh_key containing the key and its comment.
     94  */
     95 static struct pam_ssh_key *
     96 pam_ssh_load_key(struct passwd *pwd, const char *kfn, const char *passphrase)
     97 {
     98 	struct pam_ssh_key *psk;
     99 	char fn[PATH_MAX];
    100 	char *comment;
    101 	Key *key;
    102 
    103 	if (snprintf(fn, sizeof(fn), "%s/%s", pwd->pw_dir, kfn) >
    104 	    (int)sizeof(fn))
    105 		return (NULL);
    106 	comment = NULL;
    107 	key = key_load_private(fn, passphrase, &comment);
    108 	if (key == NULL) {
    109 		openpam_log(PAM_LOG_DEBUG, "failed to load key from %s\n", fn);
    110 		if (comment != NULL)
    111 			free(comment);
    112 		return (NULL);
    113 	}
    114 
    115 	openpam_log(PAM_LOG_DEBUG, "loaded '%s' from %s\n", comment, fn);
    116 	if ((psk = malloc(sizeof(*psk))) == NULL) {
    117 		key_free(key);
    118 		free(comment);
    119 		return (NULL);
    120 	}
    121 	psk->key = key;
    122 	psk->comment = comment;
    123 	return (psk);
    124 }
    125 
    126 /*
    127  * Wipes a private key and frees the associated resources.
    128  */
    129 static void
    130 pam_ssh_free_key(pam_handle_t *pamh __unused,
    131     void *data, int pam_err __unused)
    132 {
    133 	struct pam_ssh_key *psk;
    134 
    135 	psk = data;
    136 	key_free(psk->key);
    137 	free(psk->comment);
    138 	free(psk);
    139 }
    140 
    141 PAM_EXTERN int
    142 pam_sm_authenticate(pam_handle_t *pamh, int flags __unused,
    143     int argc __unused, const char *argv[] __unused)
    144 {
    145 	const char **kfn, *passphrase, *user;
    146 	struct passwd *pwd, pwres;
    147 	struct pam_ssh_key *psk;
    148 	int nkeys, pam_err, pass;
    149 	char pwbuf[1024];
    150 
    151 	/* PEM is not loaded by default */
    152 	OpenSSL_add_all_algorithms();
    153 
    154 	/* get user name and home directory */
    155 	pam_err = pam_get_user(pamh, &user, NULL);
    156 	if (pam_err != PAM_SUCCESS)
    157 		return (pam_err);
    158 	if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
    159 	    pwd == NULL)
    160 		return (PAM_USER_UNKNOWN);
    161 	if (pwd->pw_dir == NULL)
    162 		return (PAM_AUTH_ERR);
    163 
    164 	/* switch to user credentials */
    165 	pam_err = openpam_borrow_cred(pamh, pwd);
    166 	if (pam_err != PAM_SUCCESS)
    167 		return (pam_err);
    168 
    169 #ifdef notyet
    170 	for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
    171 		char path[MAXPATHLEN];
    172 		(void)snprintf(path, sizeof(path), "%s/%s", pwd->pw_dir, *kfn);
    173 		if (access(path, R_OK) == 0)
    174 			break;
    175 	}
    176 
    177 	if (*kfn == NULL) {
    178 		openpam_restore_cred(pamh);
    179 		return (PAM_AUTH_ERR);
    180 	}
    181 #endif
    182 
    183 	pass = (pam_get_item(pamh, PAM_AUTHTOK,
    184 	    (const void **)__UNCONST(&passphrase)) == PAM_SUCCESS);
    185  load_keys:
    186 	/* get passphrase */
    187 	pam_err = pam_get_authtok(pamh, PAM_AUTHTOK,
    188 	    &passphrase, pam_ssh_prompt);
    189 	if (pam_err != PAM_SUCCESS) {
    190 		openpam_restore_cred(pamh);
    191 		return (pam_err);
    192 	}
    193 
    194 	/* try to load keys from all keyfiles we know of */
    195 	nkeys = 0;
    196 	for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
    197 		psk = pam_ssh_load_key(pwd, *kfn, passphrase);
    198 		if (psk != NULL) {
    199 			pam_set_data(pamh, *kfn, psk, pam_ssh_free_key);
    200 			++nkeys;
    201 		}
    202 	}
    203 
    204 	/*
    205 	 * If we tried an old token and didn't get anything, and
    206 	 * try_first_pass was specified, try again after prompting the
    207 	 * user for a new passphrase.
    208 	 */
    209 	if (nkeys == 0 && pass == 1 &&
    210 	    openpam_get_option(pamh, "try_first_pass") != NULL) {
    211 		pam_set_item(pamh, PAM_AUTHTOK, NULL);
    212 		pass = 0;
    213 		goto load_keys;
    214 	}
    215 
    216 	/* switch back to arbitrator credentials before returning */
    217 	openpam_restore_cred(pamh);
    218 
    219 	/* no keys? */
    220 	if (nkeys == 0)
    221 		return (PAM_AUTH_ERR);
    222 
    223 	pam_set_data(pamh, pam_ssh_have_keys, NULL, NULL);
    224 	return (PAM_SUCCESS);
    225 }
    226 
    227 PAM_EXTERN int
    228 pam_sm_setcred(pam_handle_t *pamh __unused, int flags __unused,
    229     int argc __unused, const char *argv[] __unused)
    230 {
    231 
    232 	return (PAM_SUCCESS);
    233 }
    234 
    235 /*
    236  * Parses a line from ssh-agent's output.
    237  */
    238 static void
    239 pam_ssh_process_agent_output(pam_handle_t *pamh, FILE *f)
    240 {
    241 	char *line, *p, *key, *val;
    242 	size_t len;
    243 
    244 	while ((line = fgetln(f, &len)) != NULL) {
    245 		if (len < 4 || strncmp(line, "SSH_", 4) != 0)
    246 			continue;
    247 
    248 		/* find equal sign at end of key */
    249 		for (p = key = line; p < line + len; ++p)
    250 			if (*p == '=')
    251 				break;
    252 		if (p == line + len || *p != '=')
    253 			continue;
    254 		*p = '\0';
    255 
    256 		/* find semicolon at end of value */
    257 		for (val = ++p; p < line + len; ++p)
    258 			if (*p == ';')
    259 				break;
    260 		if (p == line + len || *p != ';')
    261 			continue;
    262 		*p = '\0';
    263 
    264 		/* store key-value pair in environment */
    265 		openpam_log(PAM_LOG_DEBUG, "got %s: %s", key, val);
    266 		pam_setenv(pamh, key, val, 1);
    267 	}
    268 }
    269 
    270 /*
    271  * Starts an ssh agent and stores the environment variables derived from
    272  * its output.
    273  */
    274 static int
    275 pam_ssh_start_agent(pam_handle_t *pamh, struct passwd *pwd)
    276 {
    277 	int agent_pipe[2];
    278 	pid_t pid;
    279 	FILE *f;
    280 
    281 	/* get a pipe which we will use to read the agent's output */
    282 	if (pipe(agent_pipe) == -1)
    283 		return (PAM_SYSTEM_ERR);
    284 
    285 	/* start the agent */
    286 	openpam_log(PAM_LOG_DEBUG, "starting an ssh agent");
    287 	pid = fork();
    288 	if (pid == (pid_t)-1) {
    289 		/* failed */
    290 		close(agent_pipe[0]);
    291 		close(agent_pipe[1]);
    292 		return (PAM_SYSTEM_ERR);
    293 	}
    294 	if (pid == 0) {
    295 #ifndef F_CLOSEM
    296 		int fd;
    297 #endif
    298 		/* child: drop privs, close fds and start agent */
    299 		if (setgid(pwd->pw_gid) == -1) {
    300 			openpam_log(PAM_LOG_DEBUG, "%s: Cannot setgid %d (%m)",
    301 			    __FUNCTION__, (int)pwd->pw_gid);
    302 			goto done;
    303 		}
    304 		if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
    305 			openpam_log(PAM_LOG_DEBUG,
    306 			    "%s: Cannot initgroups for %s (%m)",
    307 			    __FUNCTION__, pwd->pw_name);
    308 			goto done;
    309 		}
    310 		if (setuid(pwd->pw_uid) == -1) {
    311 			openpam_log(PAM_LOG_DEBUG, "%s: Cannot setuid %d (%m)",
    312 			    __FUNCTION__, (int)pwd->pw_uid);
    313 			goto done;
    314 		}
    315 		(void)close(STDIN_FILENO);
    316 		(void)open(_PATH_DEVNULL, O_RDONLY);
    317 		(void)dup2(agent_pipe[1], STDOUT_FILENO);
    318 		(void)dup2(agent_pipe[1], STDERR_FILENO);
    319 #ifdef F_CLOSEM
    320 		(void)fcntl(3, F_CLOSEM, 0);
    321 #else
    322 		for (fd = 3; fd < getdtablesize(); ++fd)
    323 			(void)close(fd);
    324 #endif
    325 		(void)execve(pam_ssh_agent,
    326 		    (char **)__UNCONST(pam_ssh_agent_argv),
    327 		    (char **)__UNCONST(pam_ssh_agent_envp));
    328 done:
    329 		_exit(127);
    330 	}
    331 
    332 	/* parent */
    333 	close(agent_pipe[1]);
    334 	if ((f = fdopen(agent_pipe[0], "r")) == NULL)
    335 		return (PAM_SYSTEM_ERR);
    336 	pam_ssh_process_agent_output(pamh, f);
    337 	fclose(f);
    338 
    339 	return (PAM_SUCCESS);
    340 }
    341 
    342 /*
    343  * Adds previously stored keys to a running agent.
    344  */
    345 static int
    346 pam_ssh_add_keys_to_agent(pam_handle_t *pamh)
    347 {
    348 	AuthenticationConnection *ac;
    349 	struct pam_ssh_key *psk;
    350 	const char **kfn;
    351 	char **envlist, **env;
    352 	int pam_err;
    353 
    354 	/* switch to PAM environment */
    355 	envlist = environ;
    356 	if ((environ = pam_getenvlist(pamh)) == NULL) {
    357 		openpam_log(PAM_LOG_DEBUG, "%s: cannot get envlist",
    358 		    __FUNCTION__);
    359 		environ = envlist;
    360 		return (PAM_SYSTEM_ERR);
    361 	}
    362 
    363 	/* get a connection to the agent */
    364 	if ((ac = ssh_get_authentication_connection()) == NULL) {
    365 		openpam_log(PAM_LOG_DEBUG,
    366 		    "%s: cannot get authentication connection",
    367 		    __FUNCTION__);
    368 		pam_err = PAM_SYSTEM_ERR;
    369 		goto end;
    370 	}
    371 
    372 	/* look for keys to add to it */
    373 	for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
    374 		pam_err = pam_get_data(pamh, *kfn, (void **)__UNCONST(&psk));
    375 		if (pam_err == PAM_SUCCESS && psk != NULL) {
    376 			if (ssh_add_identity(ac, psk->key, psk->comment))
    377 				openpam_log(PAM_LOG_DEBUG,
    378 				    "added %s to ssh agent", psk->comment);
    379 			else
    380 				openpam_log(PAM_LOG_DEBUG, "failed "
    381 				    "to add %s to ssh agent", psk->comment);
    382 			/* we won't need the key again, so wipe it */
    383 			pam_set_data(pamh, *kfn, NULL, NULL);
    384 		}
    385 	}
    386 	pam_err = PAM_SUCCESS;
    387  end:
    388 	/* disconnect from agent */
    389 	if (ac != NULL)
    390 		ssh_close_authentication_connection(ac);
    391 
    392 	/* switch back to original environment */
    393 	for (env = environ; *env != NULL; ++env)
    394 		free(*env);
    395 	free(environ);
    396 	environ = envlist;
    397 
    398 	return (pam_err);
    399 }
    400 
    401 PAM_EXTERN int
    402 pam_sm_open_session(pam_handle_t *pamh, int flags __unused,
    403     int argc __unused, const char *argv[] __unused)
    404 {
    405 	struct passwd *pwd, pwres;
    406 	const char *user;
    407 	void *data;
    408 	int pam_err = PAM_SUCCESS;
    409 	char pwbuf[1024];
    410 
    411 	/* no keys, no work */
    412 	if (pam_get_data(pamh, pam_ssh_have_keys, &data) != PAM_SUCCESS &&
    413 	    openpam_get_option(pamh, "want_agent") == NULL)
    414 		return (PAM_SUCCESS);
    415 
    416 	/* switch to user credentials */
    417 	pam_err = pam_get_user(pamh, &user, NULL);
    418 	if (pam_err != PAM_SUCCESS)
    419 		return (pam_err);
    420 	if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
    421 	    pwd == NULL)
    422 		return (PAM_USER_UNKNOWN);
    423 
    424 	/* start the agent */
    425 	pam_err = pam_ssh_start_agent(pamh, pwd);
    426 	if (pam_err != PAM_SUCCESS)
    427 		return pam_err;
    428 
    429 	pam_err = openpam_borrow_cred(pamh, pwd);
    430 	if (pam_err != PAM_SUCCESS)
    431 		return pam_err;
    432 
    433 	/* we have an agent, see if we can add any keys to it */
    434 	pam_err = pam_ssh_add_keys_to_agent(pamh);
    435 	if (pam_err != PAM_SUCCESS) {
    436 		/* XXX ignore failures */
    437 		openpam_log(PAM_LOG_DEBUG, "failed adding keys to ssh agent");
    438 		pam_err = PAM_SUCCESS;
    439 	}
    440 
    441 	openpam_restore_cred(pamh);
    442 	return pam_err;
    443 }
    444 
    445 PAM_EXTERN int
    446 pam_sm_close_session(pam_handle_t *pamh, int flags __unused,
    447     int argc __unused, const char *argv[] __unused)
    448 {
    449 	const char *ssh_agent_pid;
    450 	char *end;
    451 	int status;
    452 	pid_t pid;
    453 
    454 	if ((ssh_agent_pid = pam_getenv(pamh, "SSH_AGENT_PID")) == NULL) {
    455 		openpam_log(PAM_LOG_DEBUG, "no ssh agent");
    456 		return (PAM_SUCCESS);
    457 	}
    458 	pid = (pid_t)strtol(ssh_agent_pid, &end, 10);
    459 	if (*ssh_agent_pid == '\0' || *end != '\0') {
    460 		openpam_log(PAM_LOG_DEBUG, "invalid ssh agent pid");
    461 		return (PAM_SESSION_ERR);
    462 	}
    463 	openpam_log(PAM_LOG_DEBUG, "killing ssh agent %d", (int)pid);
    464 	if (kill(pid, SIGTERM) == -1 ||
    465 	    (waitpid(pid, &status, 0) == -1 && errno != ECHILD))
    466 		return (PAM_SYSTEM_ERR);
    467 	return (PAM_SUCCESS);
    468 }
    469 
    470 PAM_MODULE_ENTRY("pam_ssh");
    471