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