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