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