xref: /freebsd/lib/libpam/modules/pam_ssh/pam_ssh.c (revision 0b3105a37d7adcadcb720112fed4dc4e8040be99)
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     int nullok)
98 {
99 	struct pam_ssh_key *psk;
100 	char fn[PATH_MAX];
101 	char *comment;
102 	Key *key;
103 
104 	if (snprintf(fn, sizeof(fn), "%s/%s", dir, kfn) > (int)sizeof(fn))
105 		return (NULL);
106 	comment = NULL;
107 	/*
108 	 * If the key is unencrypted, OpenSSL ignores the passphrase, so
109 	 * it will seem like the user typed in the right one.  This allows
110 	 * a user to circumvent nullok by providing a dummy passphrase.
111 	 * Verify that the key really *is* encrypted by trying to load it
112 	 * with an empty passphrase, and if the key is not encrypted,
113 	 * accept only an empty passphrase.
114 	 */
115 	key = key_load_private(fn, "", &comment);
116 	if (key != NULL && !(*passphrase == '\0' && nullok)) {
117 		key_free(key);
118 		return (NULL);
119 	}
120 	if (key == NULL)
121 		key = key_load_private(fn, passphrase, &comment);
122 	if (key == NULL) {
123 		openpam_log(PAM_LOG_DEBUG, "failed to load key from %s", fn);
124 		return (NULL);
125 	}
126 
127 	openpam_log(PAM_LOG_DEBUG, "loaded '%s' from %s", comment, fn);
128 	if ((psk = malloc(sizeof(*psk))) == NULL) {
129 		key_free(key);
130 		free(comment);
131 		return (NULL);
132 	}
133 	psk->key = key;
134 	psk->comment = comment;
135 	return (psk);
136 }
137 
138 /*
139  * Wipes a private key and frees the associated resources.
140  */
141 static void
142 pam_ssh_free_key(pam_handle_t *pamh __unused,
143     void *data, int pam_err __unused)
144 {
145 	struct pam_ssh_key *psk;
146 
147 	psk = data;
148 	key_free(psk->key);
149 	free(psk->comment);
150 	free(psk);
151 }
152 
153 PAM_EXTERN int
154 pam_sm_authenticate(pam_handle_t *pamh, int flags __unused,
155     int argc __unused, const char *argv[] __unused)
156 {
157 	const char **kfn, *passphrase, *user;
158 	const void *item;
159 	struct passwd *pwd;
160 	struct pam_ssh_key *psk;
161 	int nkeys, nullok, pam_err, pass;
162 
163 	nullok = (openpam_get_option(pamh, "nullok") != NULL);
164 
165 	/* PEM is not loaded by default */
166 	OpenSSL_add_all_algorithms();
167 
168 	/* get user name and home directory */
169 	pam_err = pam_get_user(pamh, &user, NULL);
170 	if (pam_err != PAM_SUCCESS)
171 		return (pam_err);
172 	pwd = getpwnam(user);
173 	if (pwd == NULL)
174 		return (PAM_USER_UNKNOWN);
175 	if (pwd->pw_dir == NULL)
176 		return (PAM_AUTH_ERR);
177 
178 	nkeys = 0;
179 	pass = (pam_get_item(pamh, PAM_AUTHTOK, &item) == PAM_SUCCESS &&
180 	    item != NULL);
181  load_keys:
182 	/* get passphrase */
183 	pam_err = pam_get_authtok(pamh, PAM_AUTHTOK,
184 	    &passphrase, pam_ssh_prompt);
185 	if (pam_err != PAM_SUCCESS)
186 		return (pam_err);
187 
188 	/* switch to user credentials */
189 	pam_err = openpam_borrow_cred(pamh, pwd);
190 	if (pam_err != PAM_SUCCESS)
191 		return (pam_err);
192 
193 	/* try to load keys from all keyfiles we know of */
194 	for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
195 		psk = pam_ssh_load_key(pwd->pw_dir, *kfn, passphrase, nullok);
196 		if (psk != NULL) {
197 			pam_set_data(pamh, *kfn, psk, pam_ssh_free_key);
198 			++nkeys;
199 		}
200 	}
201 
202 	/* switch back to arbitrator credentials */
203 	openpam_restore_cred(pamh);
204 
205 	/*
206 	 * If we tried an old token and didn't get anything, and
207 	 * try_first_pass was specified, try again after prompting the
208 	 * user for a new passphrase.
209 	 */
210 	if (nkeys == 0 && pass == 1 &&
211 	    openpam_get_option(pamh, "try_first_pass") != NULL) {
212 		pam_set_item(pamh, PAM_AUTHTOK, NULL);
213 		pass = 0;
214 		goto load_keys;
215 	}
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)
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 		int fd;
294 
295 		/* child: drop privs, close fds and start agent */
296 		setgid(getegid());
297 		setuid(geteuid());
298 		close(STDIN_FILENO);
299 		open(_PATH_DEVNULL, O_RDONLY);
300 		dup2(agent_pipe[1], STDOUT_FILENO);
301 		dup2(agent_pipe[1], STDERR_FILENO);
302 		for (fd = 3; fd < getdtablesize(); ++fd)
303 			close(fd);
304 		execve(pam_ssh_agent, pam_ssh_agent_argv, pam_ssh_agent_envp);
305 		_exit(127);
306 	}
307 
308 	/* parent */
309 	close(agent_pipe[1]);
310 	if ((f = fdopen(agent_pipe[0], "r")) == NULL)
311 		return (PAM_SYSTEM_ERR);
312 	pam_ssh_process_agent_output(pamh, f);
313 	fclose(f);
314 
315 	return (PAM_SUCCESS);
316 }
317 
318 /*
319  * Adds previously stored keys to a running agent.
320  */
321 static int
322 pam_ssh_add_keys_to_agent(pam_handle_t *pamh)
323 {
324 	const struct pam_ssh_key *psk;
325 	const char **kfn;
326 	const void *item;
327 	char **envlist, **env;
328 	int fd, pam_err;
329 
330 	/* switch to PAM environment */
331 	envlist = environ;
332 	if ((environ = pam_getenvlist(pamh)) == NULL) {
333 		environ = envlist;
334 		return (PAM_SYSTEM_ERR);
335 	}
336 
337 	/* get a connection to the agent */
338 	if (ssh_get_authentication_socket(&fd) != 0) {
339 		openpam_log(PAM_LOG_DEBUG, "failed to connect to the agent");
340 		pam_err = PAM_SYSTEM_ERR;
341 		goto end;
342 	}
343 
344 	/* look for keys to add to it */
345 	for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
346 		pam_err = pam_get_data(pamh, *kfn, &item);
347 		if (pam_err == PAM_SUCCESS && item != NULL) {
348 			psk = item;
349 			if (ssh_add_identity(fd, psk->key, psk->comment) == 0)
350 				openpam_log(PAM_LOG_DEBUG,
351 				    "added %s to ssh agent", psk->comment);
352 			else
353 				openpam_log(PAM_LOG_DEBUG, "failed "
354 				    "to add %s to ssh agent", psk->comment);
355 			/* we won't need the key again, so wipe it */
356 			pam_set_data(pamh, *kfn, NULL, NULL);
357 		}
358 	}
359 	pam_err = PAM_SUCCESS;
360 
361 	/* disconnect from agent */
362 	ssh_close_authentication_socket(fd);
363 
364  end:
365 	/* switch back to original environment */
366 	for (env = environ; *env != NULL; ++env)
367 		free(*env);
368 	free(environ);
369 	environ = envlist;
370 
371 	return (pam_err);
372 }
373 
374 PAM_EXTERN int
375 pam_sm_open_session(pam_handle_t *pamh, int flags __unused,
376     int argc __unused, const char *argv[] __unused)
377 {
378 	struct passwd *pwd;
379 	const char *user;
380 	const void *data;
381 	int pam_err;
382 
383 	/* no keys, no work */
384 	if (pam_get_data(pamh, pam_ssh_have_keys, &data) != PAM_SUCCESS &&
385 	    openpam_get_option(pamh, "want_agent") == NULL)
386 		return (PAM_SUCCESS);
387 
388 	/* switch to user credentials */
389 	pam_err = pam_get_user(pamh, &user, NULL);
390 	if (pam_err != PAM_SUCCESS)
391 		return (pam_err);
392 	pwd = getpwnam(user);
393 	if (pwd == NULL)
394 		return (PAM_USER_UNKNOWN);
395 	pam_err = openpam_borrow_cred(pamh, pwd);
396 	if (pam_err != PAM_SUCCESS)
397 		return (pam_err);
398 
399 	/* start the agent */
400 	pam_err = pam_ssh_start_agent(pamh);
401 	if (pam_err != PAM_SUCCESS) {
402 		openpam_restore_cred(pamh);
403 		return (pam_err);
404 	}
405 
406 	/* we have an agent, see if we can add any keys to it */
407 	pam_err = pam_ssh_add_keys_to_agent(pamh);
408 	if (pam_err != PAM_SUCCESS) {
409 		/* XXX ignore failures */
410 	}
411 
412 	openpam_restore_cred(pamh);
413 	return (PAM_SUCCESS);
414 }
415 
416 PAM_EXTERN int
417 pam_sm_close_session(pam_handle_t *pamh, int flags __unused,
418     int argc __unused, const char *argv[] __unused)
419 {
420 	const char *ssh_agent_pid;
421 	char *end;
422 	int status;
423 	pid_t pid;
424 
425 	if ((ssh_agent_pid = pam_getenv(pamh, "SSH_AGENT_PID")) == NULL) {
426 		openpam_log(PAM_LOG_DEBUG, "no ssh agent");
427 		return (PAM_SUCCESS);
428 	}
429 	pid = (pid_t)strtol(ssh_agent_pid, &end, 10);
430 	if (*ssh_agent_pid == '\0' || *end != '\0') {
431 		openpam_log(PAM_LOG_DEBUG, "invalid ssh agent pid");
432 		return (PAM_SESSION_ERR);
433 	}
434 	openpam_log(PAM_LOG_DEBUG, "killing ssh agent %d", (int)pid);
435 	if (kill(pid, SIGTERM) == -1 ||
436 	    (waitpid(pid, &status, 0) == -1 && errno != ECHILD))
437 		return (PAM_SYSTEM_ERR);
438 	return (PAM_SUCCESS);
439 }
440 
441 PAM_MODULE_ENTRY("pam_ssh");
442