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