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