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