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