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