xref: /netbsd-src/crypto/external/bsd/openssh/dist/auth2-pubkey.c (revision a24efa7dea9f1f56c3bdb15a927d3516792ace1c)
1 /*	$NetBSD: auth2-pubkey.c,v 1.14 2016/03/11 01:55:00 christos Exp $	*/
2 /* $OpenBSD: auth2-pubkey.c,v 1.55 2016/01/27 00:53:12 djm Exp $ */
3 
4 /*
5  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include "includes.h"
29 __RCSID("$NetBSD: auth2-pubkey.c,v 1.14 2016/03/11 01:55:00 christos Exp $");
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/wait.h>
33 
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <paths.h>
37 #include <pwd.h>
38 #include <signal.h>
39 #include <stdio.h>
40 #include <stdarg.h>
41 #include <string.h>
42 #include <time.h>
43 #include <unistd.h>
44 #include <limits.h>
45 
46 #include "xmalloc.h"
47 #include "ssh.h"
48 #include "ssh2.h"
49 #include "packet.h"
50 #include "buffer.h"
51 #include "log.h"
52 #include "misc.h"
53 #include "servconf.h"
54 #include "compat.h"
55 #include "key.h"
56 #include "hostfile.h"
57 #include "auth.h"
58 #include "pathnames.h"
59 #include "uidswap.h"
60 #include "auth-options.h"
61 #include "canohost.h"
62 #ifdef GSSAPI
63 #include "ssh-gss.h"
64 #endif
65 #include "monitor_wrap.h"
66 #include "authfile.h"
67 #include "match.h"
68 #include "digest.h"
69 
70 #ifdef WITH_LDAP_PUBKEY
71 #include "ldapauth.h"
72 #endif
73 
74 #include "ssherr.h"
75 #include "channels.h" /* XXX for session.h */
76 #include "session.h" /* XXX for child_set_env(); refactor? */
77 
78 /* import */
79 extern ServerOptions options;
80 extern u_char *session_id2;
81 extern u_int session_id2_len;
82 
83 static int
84 userauth_pubkey(Authctxt *authctxt)
85 {
86 	Buffer b;
87 	Key *key = NULL;
88 	char *pkalg, *userstyle, *fp = NULL;
89 	u_char *pkblob, *sig;
90 	u_int alen, blen, slen;
91 	int have_sig, pktype;
92 	int authenticated = 0;
93 
94 	if (!authctxt->valid) {
95 		debug2("%s: disabled because of invalid user", __func__);
96 		return 0;
97 	}
98 	have_sig = packet_get_char();
99 	if (datafellows & SSH_BUG_PKAUTH) {
100 		debug2("%s: SSH_BUG_PKAUTH", __func__);
101 		/* no explicit pkalg given */
102 		pkblob = packet_get_string(&blen);
103 		buffer_init(&b);
104 		buffer_append(&b, pkblob, blen);
105 		/* so we have to extract the pkalg from the pkblob */
106 		pkalg = buffer_get_string(&b, &alen);
107 		buffer_free(&b);
108 	} else {
109 		pkalg = packet_get_string(&alen);
110 		pkblob = packet_get_string(&blen);
111 	}
112 	pktype = key_type_from_name(pkalg);
113 	if (pktype == KEY_UNSPEC) {
114 		/* this is perfectly legal */
115 		logit("%s: unsupported public key algorithm: %s",
116 		    __func__, pkalg);
117 		goto done;
118 	}
119 	key = key_from_blob(pkblob, blen);
120 	if (key == NULL) {
121 		error("%s: cannot decode key: %s", __func__, pkalg);
122 		goto done;
123 	}
124 	if (key->type != pktype) {
125 		error("%s: type mismatch for decoded key "
126 		    "(received %d, expected %d)", __func__, key->type, pktype);
127 		goto done;
128 	}
129 	if (key_type_plain(key->type) == KEY_RSA &&
130 	    (datafellows & SSH_BUG_RSASIGMD5) != 0) {
131 		logit("Refusing RSA key because client uses unsafe "
132 		    "signature scheme");
133 		goto done;
134 	}
135 	fp = sshkey_fingerprint(key, options.fingerprint_hash, SSH_FP_DEFAULT);
136 	if (auth2_userkey_already_used(authctxt, key)) {
137 		logit("refusing previously-used %s key", key_type(key));
138 		goto done;
139 	}
140 	if (match_pattern_list(sshkey_ssh_name(key),
141 	    options.pubkey_key_types, 0) != 1) {
142 		logit("%s: key type %s not in PubkeyAcceptedKeyTypes",
143 		    __func__, sshkey_ssh_name(key));
144 		goto done;
145 	}
146 
147 	if (have_sig) {
148 		debug3("%s: have signature for %s %s",
149 		    __func__, sshkey_type(key), fp);
150 		sig = packet_get_string(&slen);
151 		packet_check_eom();
152 		buffer_init(&b);
153 		if (datafellows & SSH_OLD_SESSIONID) {
154 			buffer_append(&b, session_id2, session_id2_len);
155 		} else {
156 			buffer_put_string(&b, session_id2, session_id2_len);
157 		}
158 		/* reconstruct packet */
159 		buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
160 		xasprintf(&userstyle, "%s%s%s", authctxt->user,
161 		    authctxt->style ? ":" : "",
162 		    authctxt->style ? authctxt->style : "");
163 		buffer_put_cstring(&b, userstyle);
164 		free(userstyle);
165 		buffer_put_cstring(&b,
166 		    datafellows & SSH_BUG_PKSERVICE ?
167 		    "ssh-userauth" :
168 		    authctxt->service);
169 		if (datafellows & SSH_BUG_PKAUTH) {
170 			buffer_put_char(&b, have_sig);
171 		} else {
172 			buffer_put_cstring(&b, "publickey");
173 			buffer_put_char(&b, have_sig);
174 			buffer_put_cstring(&b, pkalg);
175 		}
176 		buffer_put_string(&b, pkblob, blen);
177 #ifdef DEBUG_PK
178 		buffer_dump(&b);
179 #endif
180 		pubkey_auth_info(authctxt, key, NULL);
181 
182 		/* test for correct signature */
183 		authenticated = 0;
184 		if (PRIVSEP(user_key_allowed(authctxt->pw, key, 1)) &&
185 		    PRIVSEP(key_verify(key, sig, slen, buffer_ptr(&b),
186 		    buffer_len(&b))) == 1) {
187 			authenticated = 1;
188 			/* Record the successful key to prevent reuse */
189 			auth2_record_userkey(authctxt, key);
190 			key = NULL; /* Don't free below */
191 		}
192 		buffer_free(&b);
193 		free(sig);
194 	} else {
195 		debug("%s: test whether pkalg/pkblob are acceptable for %s %s",
196 		    __func__, sshkey_type(key), fp);
197 		packet_check_eom();
198 
199 		/* XXX fake reply and always send PK_OK ? */
200 		/*
201 		 * XXX this allows testing whether a user is allowed
202 		 * to login: if you happen to have a valid pubkey this
203 		 * message is sent. the message is NEVER sent at all
204 		 * if a user is not allowed to login. is this an
205 		 * issue? -markus
206 		 */
207 		if (PRIVSEP(user_key_allowed(authctxt->pw, key, 0))) {
208 			packet_start(SSH2_MSG_USERAUTH_PK_OK);
209 			packet_put_string(pkalg, alen);
210 			packet_put_string(pkblob, blen);
211 			packet_send();
212 			packet_write_wait();
213 			authctxt->postponed = 1;
214 		}
215 	}
216 	if (authenticated != 1)
217 		auth_clear_options();
218 done:
219 	debug2("%s: authenticated %d pkalg %s", __func__, authenticated, pkalg);
220 	if (key != NULL)
221 		key_free(key);
222 	free(pkalg);
223 	free(pkblob);
224 	free(fp);
225 	return authenticated;
226 }
227 
228 void
229 pubkey_auth_info(Authctxt *authctxt, const Key *key, const char *fmt, ...)
230 {
231 	char *fp, *extra;
232 	va_list ap;
233 	int i;
234 
235 	extra = NULL;
236 	if (fmt != NULL) {
237 		va_start(ap, fmt);
238 		i = vasprintf(&extra, fmt, ap);
239 		va_end(ap);
240 		if (i < 0 || extra == NULL)
241 			fatal("%s: vasprintf failed", __func__);
242 	}
243 
244 	if (key_is_cert(key)) {
245 		fp = sshkey_fingerprint(key->cert->signature_key,
246 		    options.fingerprint_hash, SSH_FP_DEFAULT);
247 		auth_info(authctxt, "%s ID %s (serial %llu) CA %s %s%s%s",
248 		    key_type(key), key->cert->key_id,
249 		    (unsigned long long)key->cert->serial,
250 		    key_type(key->cert->signature_key),
251 		    fp == NULL ? "(null)" : fp,
252 		    extra == NULL ? "" : ", ", extra == NULL ? "" : extra);
253 		free(fp);
254 	} else {
255 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
256 		    SSH_FP_DEFAULT);
257 		auth_info(authctxt, "%s %s%s%s", key_type(key),
258 		    fp == NULL ? "(null)" : fp,
259 		    extra == NULL ? "" : ", ", extra == NULL ? "" : extra);
260 		free(fp);
261 	}
262 	free(extra);
263 }
264 
265 /*
266  * Splits 's' into an argument vector. Handles quoted string and basic
267  * escape characters (\\, \", \'). Caller must free the argument vector
268  * and its members.
269  */
270 static int
271 split_argv(const char *s, int *argcp, char ***argvp)
272 {
273 	int r = SSH_ERR_INTERNAL_ERROR;
274 	int argc = 0, quote, i, j;
275 	char *arg, **argv = xcalloc(1, sizeof(*argv));
276 
277 	*argvp = NULL;
278 	*argcp = 0;
279 
280 	for (i = 0; s[i] != '\0'; i++) {
281 		/* Skip leading whitespace */
282 		if (s[i] == ' ' || s[i] == '\t')
283 			continue;
284 
285 		/* Start of a token */
286 		quote = 0;
287 		if (s[i] == '\\' &&
288 		    (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
289 			i++;
290 		else if (s[i] == '\'' || s[i] == '"')
291 			quote = s[i++];
292 
293 		argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
294 		arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
295 		argv[argc] = NULL;
296 
297 		/* Copy the token in, removing escapes */
298 		for (j = 0; s[i] != '\0'; i++) {
299 			if (s[i] == '\\') {
300 				if (s[i + 1] == '\'' ||
301 				    s[i + 1] == '\"' ||
302 				    s[i + 1] == '\\') {
303 					i++; /* Skip '\' */
304 					arg[j++] = s[i];
305 				} else {
306 					/* Unrecognised escape */
307 					arg[j++] = s[i];
308 				}
309 			} else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
310 				break; /* done */
311 			else if (quote != 0 && s[i] == quote)
312 				break; /* done */
313 			else
314 				arg[j++] = s[i];
315 		}
316 		if (s[i] == '\0') {
317 			if (quote != 0) {
318 				/* Ran out of string looking for close quote */
319 				r = SSH_ERR_INVALID_FORMAT;
320 				goto out;
321 			}
322 			break;
323 		}
324 	}
325 	/* Success */
326 	*argcp = argc;
327 	*argvp = argv;
328 	argc = 0;
329 	argv = NULL;
330 	r = 0;
331  out:
332 	if (argc != 0 && argv != NULL) {
333 		for (i = 0; i < argc; i++)
334 			free(argv[i]);
335 		free(argv);
336 	}
337 	return r;
338 }
339 
340 /*
341  * Reassemble an argument vector into a string, quoting and escaping as
342  * necessary. Caller must free returned string.
343  */
344 static char *
345 assemble_argv(int argc, char **argv)
346 {
347 	int i, j, ws, r;
348 	char c, *ret;
349 	struct sshbuf *buf, *arg;
350 
351 	if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
352 		fatal("%s: sshbuf_new failed", __func__);
353 
354 	for (i = 0; i < argc; i++) {
355 		ws = 0;
356 		sshbuf_reset(arg);
357 		for (j = 0; argv[i][j] != '\0'; j++) {
358 			r = 0;
359 			c = argv[i][j];
360 			switch (c) {
361 			case ' ':
362 			case '\t':
363 				ws = 1;
364 				r = sshbuf_put_u8(arg, c);
365 				break;
366 			case '\\':
367 			case '\'':
368 			case '"':
369 				if ((r = sshbuf_put_u8(arg, '\\')) != 0)
370 					break;
371 				/* FALLTHROUGH */
372 			default:
373 				r = sshbuf_put_u8(arg, c);
374 				break;
375 			}
376 			if (r != 0)
377 				fatal("%s: sshbuf_put_u8: %s",
378 				    __func__, ssh_err(r));
379 		}
380 		if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
381 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
382 		    (r = sshbuf_putb(buf, arg)) != 0 ||
383 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
384 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
385 	}
386 	if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
387 		fatal("%s: malloc failed", __func__);
388 	memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
389 	ret[sshbuf_len(buf)] = '\0';
390 	sshbuf_free(buf);
391 	sshbuf_free(arg);
392 	return ret;
393 }
394 
395 /*
396  * Runs command in a subprocess. Returns pid on success and a FILE* to the
397  * subprocess' stdout or 0 on failure.
398  * NB. "command" is only used for logging.
399  */
400 static pid_t
401 subprocess(const char *tag, struct passwd *pw, const char *command,
402     int ac, char **av, FILE **child)
403 {
404 	FILE *f;
405 	struct stat st;
406 	int devnull, p[2], i;
407 	pid_t pid;
408 	char *cp, errmsg[512];
409 	u_int envsize;
410 	char **child_env;
411 
412 	*child = NULL;
413 
414 	debug3("%s: %s command \"%s\" running as %s", __func__,
415 	    tag, command, pw->pw_name);
416 
417 	/* Verify the path exists and is safe-ish to execute */
418 	if (*av[0] != '/') {
419 		error("%s path is not absolute", tag);
420 		return 0;
421 	}
422 	temporarily_use_uid(pw);
423 	if (stat(av[0], &st) < 0) {
424 		error("Could not stat %s \"%s\": %s", tag,
425 		    av[0], strerror(errno));
426 		restore_uid();
427 		return 0;
428 	}
429 	if (auth_secure_path(av[0], &st, NULL, 0,
430 	    errmsg, sizeof(errmsg)) != 0) {
431 		error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
432 		restore_uid();
433 		return 0;
434 	}
435 
436 	/*
437 	 * Run the command; stderr is left in place, stdout is the
438 	 * authorized_keys output.
439 	 */
440 	if (pipe(p) != 0) {
441 		error("%s: pipe: %s", tag, strerror(errno));
442 		restore_uid();
443 		return 0;
444 	}
445 
446 	/*
447 	 * Don't want to call this in the child, where it can fatal() and
448 	 * run cleanup_exit() code.
449 	 */
450 	restore_uid();
451 
452 	switch ((pid = fork())) {
453 	case -1: /* error */
454 		error("%s: fork: %s", tag, strerror(errno));
455 		close(p[0]);
456 		close(p[1]);
457 		return 0;
458 	case 0: /* child */
459 		/* Prepare a minimal environment for the child. */
460 		envsize = 5;
461 		child_env = xcalloc(sizeof(*child_env), envsize);
462 		child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
463 		child_set_env(&child_env, &envsize, "USER", pw->pw_name);
464 		child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
465 		child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
466 		if ((cp = getenv("LANG")) != NULL)
467 			child_set_env(&child_env, &envsize, "LANG", cp);
468 
469 		for (i = 0; i < NSIG; i++)
470 			signal(i, SIG_DFL);
471 
472 		if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
473 			error("%s: open %s: %s", tag, _PATH_DEVNULL,
474 			    strerror(errno));
475 			_exit(1);
476 		}
477 		/* Keep stderr around a while longer to catch errors */
478 		if (dup2(devnull, STDIN_FILENO) == -1 ||
479 		    dup2(p[1], STDOUT_FILENO) == -1) {
480 			error("%s: dup2: %s", tag, strerror(errno));
481 			_exit(1);
482 		}
483 		if (closefrom(STDERR_FILENO + 1) == -1) {
484 			error("closefrom: %s", strerror(errno));
485 			_exit(1);
486 		}
487 
488 		/* Don't use permanently_set_uid() here to avoid fatal() */
489 		if (setgid(pw->pw_gid) == -1) {
490 			error("setgid %u: %s", (u_int)pw->pw_gid,
491 			    strerror(errno));
492 			_exit(1);
493 		}
494 		if (setuid(pw->pw_uid) == -1) {
495 			error("setuid %u: %s", (u_int)pw->pw_uid,
496 			    strerror(errno));
497 			_exit(1);
498 		}
499 		/* stdin is pointed to /dev/null at this point */
500 		if (dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
501 			error("%s: dup2: %s", tag, strerror(errno));
502 			_exit(1);
503 		}
504 
505 		execve(av[0], av, child_env);
506 		error("%s exec \"%s\": %s", tag, command, strerror(errno));
507 		_exit(127);
508 	default: /* parent */
509 		break;
510 	}
511 
512 	close(p[1]);
513 	if ((f = fdopen(p[0], "r")) == NULL) {
514 		error("%s: fdopen: %s", tag, strerror(errno));
515 		close(p[0]);
516 		/* Don't leave zombie child */
517 		kill(pid, SIGTERM);
518 		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
519 			;
520 		return 0;
521 	}
522 	/* Success */
523 	debug3("%s: %s pid %ld", __func__, tag, (long)pid);
524 	*child = f;
525 	return pid;
526 }
527 
528 /* Returns 0 if pid exited cleanly, non-zero otherwise */
529 static int
530 exited_cleanly(pid_t pid, const char *tag, const char *cmd)
531 {
532 	int status;
533 
534 	while (waitpid(pid, &status, 0) == -1) {
535 		if (errno != EINTR) {
536 			error("%s: waitpid: %s", tag, strerror(errno));
537 			return -1;
538 		}
539 	}
540 	if (WIFSIGNALED(status)) {
541 		error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
542 		return -1;
543 	} else if (WEXITSTATUS(status) != 0) {
544 		error("%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
545 		return -1;
546 	}
547 	return 0;
548 }
549 
550 static int
551 match_principals_option(const char *principal_list, struct sshkey_cert *cert)
552 {
553 	char *result;
554 	u_int i;
555 
556 	/* XXX percent_expand() sequences for authorized_principals? */
557 
558 	for (i = 0; i < cert->nprincipals; i++) {
559 		if ((result = match_list(cert->principals[i],
560 		    principal_list, NULL)) != NULL) {
561 			debug3("matched principal from key options \"%.100s\"",
562 			    result);
563 			free(result);
564 			return 1;
565 		}
566 	}
567 	return 0;
568 }
569 
570 static int
571 process_principals(FILE *f, char *file, struct passwd *pw,
572     struct sshkey_cert *cert)
573 {
574 	char line[SSH_MAX_PUBKEY_BYTES], *cp, *ep, *line_opts;
575 	u_long linenum = 0;
576 	u_int i;
577 
578 	while (read_keyfile_line(f, file, line, sizeof(line), &linenum) != -1) {
579 		/* Skip leading whitespace. */
580 		for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
581 			;
582 		/* Skip blank and comment lines. */
583 		if ((ep = strchr(cp, '#')) != NULL)
584 			*ep = '\0';
585 		if (!*cp || *cp == '\n')
586 			continue;
587 		/* Trim trailing whitespace. */
588 		ep = cp + strlen(cp) - 1;
589 		while (ep > cp && (*ep == '\n' || *ep == ' ' || *ep == '\t'))
590 			*ep-- = '\0';
591 		/*
592 		 * If the line has internal whitespace then assume it has
593 		 * key options.
594 		 */
595 		line_opts = NULL;
596 		if ((ep = strrchr(cp, ' ')) != NULL ||
597 		    (ep = strrchr(cp, '\t')) != NULL) {
598 			for (; *ep == ' ' || *ep == '\t'; ep++)
599 				;
600 			line_opts = cp;
601 			cp = ep;
602 		}
603 		for (i = 0; i < cert->nprincipals; i++) {
604 			if (strcmp(cp, cert->principals[i]) == 0) {
605 				debug3("%s:%lu: matched principal \"%.100s\"",
606 				    file == NULL ? "(command)" : file,
607 				    linenum, cert->principals[i]);
608 				if (auth_parse_options(pw, line_opts,
609 				    file, linenum) != 1)
610 					continue;
611 				return 1;
612 			}
613 		}
614 	}
615 	return 0;
616 }
617 
618 static int
619 match_principals_file(char *file, struct passwd *pw, struct sshkey_cert *cert)
620 {
621 	FILE *f;
622 	int success;
623 
624 	temporarily_use_uid(pw);
625 	debug("trying authorized principals file %s", file);
626 	if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) {
627 		restore_uid();
628 		return 0;
629 	}
630 	success = process_principals(f, file, pw, cert);
631 	fclose(f);
632 	restore_uid();
633 	return success;
634 }
635 
636 /*
637  * Checks whether principal is allowed in output of command.
638  * returns 1 if the principal is allowed or 0 otherwise.
639  */
640 static int
641 match_principals_command(struct passwd *user_pw, struct sshkey_cert *cert)
642 {
643 	FILE *f = NULL;
644 	int ok, found_principal = 0;
645 	struct passwd *pw;
646 	int i, ac = 0, uid_swapped = 0;
647 	pid_t pid;
648 	char *tmp, *username = NULL, *command = NULL, **av = NULL;
649 	void (*osigchld)(int);
650 
651 	if (options.authorized_principals_command == NULL)
652 		return 0;
653 	if (options.authorized_principals_command_user == NULL) {
654 		error("No user for AuthorizedPrincipalsCommand specified, "
655 		    "skipping");
656 		return 0;
657 	}
658 
659 	/*
660 	 * NB. all returns later this function should go via "out" to
661 	 * ensure the original SIGCHLD handler is restored properly.
662 	 */
663 	osigchld = signal(SIGCHLD, SIG_DFL);
664 
665 	/* Prepare and verify the user for the command */
666 	username = percent_expand(options.authorized_principals_command_user,
667 	    "u", user_pw->pw_name, (char *)NULL);
668 	pw = getpwnam(username);
669 	if (pw == NULL) {
670 		error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s",
671 		    username, strerror(errno));
672 		goto out;
673 	}
674 
675 	/* Turn the command into an argument vector */
676 	if (split_argv(options.authorized_principals_command, &ac, &av) != 0) {
677 		error("AuthorizedPrincipalsCommand \"%s\" contains "
678 		    "invalid quotes", command);
679 		goto out;
680 	}
681 	if (ac == 0) {
682 		error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments",
683 		    command);
684 		goto out;
685 	}
686 	for (i = 1; i < ac; i++) {
687 		tmp = percent_expand(av[i],
688 		    "u", user_pw->pw_name,
689 		    "h", user_pw->pw_dir,
690 		    (char *)NULL);
691 		if (tmp == NULL)
692 			fatal("%s: percent_expand failed", __func__);
693 		free(av[i]);
694 		av[i] = tmp;
695 	}
696 	/* Prepare a printable command for logs, etc. */
697 	command = assemble_argv(ac, av);
698 
699 	if ((pid = subprocess("AuthorizedPrincipalsCommand", pw, command,
700 	    ac, av, &f)) == 0)
701 		goto out;
702 
703 	uid_swapped = 1;
704 	temporarily_use_uid(pw);
705 
706 	ok = process_principals(f, NULL, pw, cert);
707 
708 	if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command) != 0)
709 		goto out;
710 
711 	/* Read completed successfully */
712 	found_principal = ok;
713  out:
714 	if (f != NULL)
715 		fclose(f);
716 	signal(SIGCHLD, osigchld);
717 	for (i = 0; i < ac; i++)
718 		free(av[i]);
719 	free(av);
720 	if (uid_swapped)
721 		restore_uid();
722 	free(command);
723 	free(username);
724 	return found_principal;
725 }
726 /*
727  * Checks whether key is allowed in authorized_keys-format file,
728  * returns 1 if the key is allowed or 0 otherwise.
729  */
730 static int
731 check_authkeys_file(FILE *f, char *file, Key* key, struct passwd *pw)
732 {
733 	char line[SSH_MAX_PUBKEY_BYTES];
734 	const char *reason;
735 	int found_key = 0;
736 	u_long linenum = 0;
737 	Key *found;
738 	char *fp;
739 #ifdef WITH_LDAP_PUBKEY
740 	ldap_key_t * k;
741 	unsigned int i = 0;
742 #endif
743 
744 #ifdef WITH_LDAP_PUBKEY
745 	found_key = 0;
746 	/* allocate a new key type */
747 	found = key_new(key->type);
748 
749 	/* first check if the options is enabled, then try.. */
750 	if (options.lpk.on) {
751 	    debug("[LDAP] trying LDAP first uid=%s",pw->pw_name);
752 	    if (ldap_ismember(&options.lpk, pw->pw_name) > 0) {
753 		if ((k = ldap_getuserkey(&options.lpk, pw->pw_name)) != NULL) {
754 		    /* Skip leading whitespace, empty and comment lines. */
755 		    for (i = 0 ; i < k->num ; i++) {
756 			/* dont forget if multiple keys to reset options */
757 			char *cp, *xoptions = NULL;
758 
759 			for (cp = (char *)k->keys[i]->bv_val; *cp == ' ' || *cp == '\t'; cp++)
760 			    ;
761 			if (!*cp || *cp == '\n' || *cp == '#')
762 			    continue;
763 
764 			if (key_read(found, &cp) != 1) {
765 			    /* no key?  check if there are options for this key */
766 			    int quoted = 0;
767 			    debug2("[LDAP] user_key_allowed: check options: '%s'", cp);
768 			    xoptions = cp;
769 			    for (; *cp && (quoted || (*cp != ' ' && *cp != '\t')); cp++) {
770 				if (*cp == '\\' && cp[1] == '"')
771 				    cp++;	/* Skip both */
772 				else if (*cp == '"')
773 				    quoted = !quoted;
774 			    }
775 			    /* Skip remaining whitespace. */
776 			    for (; *cp == ' ' || *cp == '\t'; cp++)
777 				;
778 			    if (key_read(found, &cp) != 1) {
779 				debug2("[LDAP] user_key_allowed: advance: '%s'", cp);
780 				/* still no key?  advance to next line*/
781 				continue;
782 			    }
783 			}
784 
785 			if (key_equal(found, key) &&
786 				auth_parse_options(pw, xoptions, file, linenum) == 1) {
787 			    found_key = 1;
788 			    debug("[LDAP] matching key found");
789 			    fp = sshkey_fingerprint(found, SSH_FP_HASH_DEFAULT, SSH_FP_HEX);
790 			    verbose("[LDAP] Found matching %s key: %s", key_type(found), fp);
791 
792 			    /* restoring memory */
793 			    ldap_keys_free(k);
794 			    free(fp);
795 			    restore_uid();
796 			    key_free(found);
797 			    return found_key;
798 			    break;
799 			}
800 		    }/* end of LDAP for() */
801 		} else {
802 		    logit("[LDAP] no keys found for '%s'!", pw->pw_name);
803 		}
804 	    } else {
805 		logit("[LDAP] '%s' is not in '%s'", pw->pw_name, options.lpk.sgroup);
806 	    }
807 	}
808 #endif
809 	debug("trying public key file %s", file);
810 	f = auth_openkeyfile(file, pw, options.strict_modes);
811 
812 	if (!f) {
813 		restore_uid();
814 		return 0;
815 	}
816 
817 	found_key = 0;
818 
819 	found = NULL;
820 	while (read_keyfile_line(f, file, line, sizeof(line), &linenum) != -1) {
821 		char *cp, *key_options = NULL;
822 		if (found != NULL)
823 			key_free(found);
824 		found = key_new(key_is_cert(key) ? KEY_UNSPEC : key->type);
825 		auth_clear_options();
826 
827 		/* Skip leading whitespace, empty and comment lines. */
828 		for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
829 			;
830 		if (!*cp || *cp == '\n' || *cp == '#')
831 			continue;
832 
833 		if (key_read(found, &cp) != 1) {
834 			/* no key?  check if there are options for this key */
835 			int quoted = 0;
836 			debug2("user_key_allowed: check options: '%s'", cp);
837 			key_options = cp;
838 			for (; *cp && (quoted || (*cp != ' ' && *cp != '\t')); cp++) {
839 				if (*cp == '\\' && cp[1] == '"')
840 					cp++;	/* Skip both */
841 				else if (*cp == '"')
842 					quoted = !quoted;
843 			}
844 			/* Skip remaining whitespace. */
845 			for (; *cp == ' ' || *cp == '\t'; cp++)
846 				;
847 			if (key_read(found, &cp) != 1) {
848 				debug2("user_key_allowed: advance: '%s'", cp);
849 				/* still no key?  advance to next line*/
850 				continue;
851 			}
852 		}
853 		if (key_is_cert(key)) {
854 			if (!key_equal(found, key->cert->signature_key))
855 				continue;
856 			if (auth_parse_options(pw, key_options, file,
857 			    linenum) != 1)
858 				continue;
859 			if (!key_is_cert_authority)
860 				continue;
861 			if ((fp = sshkey_fingerprint(found,
862 			    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
863 				continue;
864 			debug("matching CA found: file %s, line %lu, %s %s",
865 			    file, linenum, key_type(found), fp);
866 			/*
867 			 * If the user has specified a list of principals as
868 			 * a key option, then prefer that list to matching
869 			 * their username in the certificate principals list.
870 			 */
871 			if (authorized_principals != NULL &&
872 			    !match_principals_option(authorized_principals,
873 			    key->cert)) {
874 				reason = "Certificate does not contain an "
875 				    "authorized principal";
876  fail_reason:
877 				free(fp);
878 				error("%s", reason);
879 				auth_debug_add("%s", reason);
880 				continue;
881 			}
882 			if (key_cert_check_authority(key, 0, 0,
883 			    authorized_principals == NULL ? pw->pw_name : NULL,
884 			    &reason) != 0)
885 				goto fail_reason;
886 			if (auth_cert_options(key, pw) != 0) {
887 				free(fp);
888 				continue;
889 			}
890 			verbose("Accepted certificate ID \"%s\" (serial %llu) "
891 			    "signed by %s CA %s via %s", key->cert->key_id,
892 			    (unsigned long long)key->cert->serial,
893 			    key_type(found), fp, file);
894 			free(fp);
895 			found_key = 1;
896 			break;
897 		} else if (key_equal(found, key)) {
898 			if (auth_parse_options(pw, key_options, file,
899 			    linenum) != 1)
900 				continue;
901 			if (key_is_cert_authority)
902 				continue;
903 			if ((fp = sshkey_fingerprint(found,
904 			    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
905 				continue;
906 			debug("matching key found: file %s, line %lu %s %s",
907 			    file, linenum, key_type(found), fp);
908 			free(fp);
909 			found_key = 1;
910 			break;
911 		}
912 	}
913 	if (found != NULL)
914 		key_free(found);
915 	if (!found_key)
916 		debug2("key not found");
917 	return found_key;
918 }
919 
920 /* Authenticate a certificate key against TrustedUserCAKeys */
921 static int
922 user_cert_trusted_ca(struct passwd *pw, Key *key)
923 {
924 	char *ca_fp, *principals_file = NULL;
925 	const char *reason;
926 	int ret = 0, found_principal = 0, use_authorized_principals;
927 
928 	if (!key_is_cert(key) || options.trusted_user_ca_keys == NULL)
929 		return 0;
930 
931 	if ((ca_fp = sshkey_fingerprint(key->cert->signature_key,
932 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
933 		return 0;
934 
935 	if (sshkey_in_file(key->cert->signature_key,
936 	    options.trusted_user_ca_keys, 1, 0) != 0) {
937 		debug2("%s: CA %s %s is not listed in %s", __func__,
938 		    key_type(key->cert->signature_key), ca_fp,
939 		    options.trusted_user_ca_keys);
940 		goto out;
941 	}
942 	/*
943 	 * If AuthorizedPrincipals is in use, then compare the certificate
944 	 * principals against the names in that file rather than matching
945 	 * against the username.
946 	 */
947 	if ((principals_file = authorized_principals_file(pw)) != NULL) {
948 		if (match_principals_file(principals_file, pw, key->cert))
949 			found_principal = 1;
950 	}
951 	/* Try querying command if specified */
952 	if (!found_principal && match_principals_command(pw, key->cert))
953 		found_principal = 1;
954 	/* If principals file or command is specified, then require a match */
955 	use_authorized_principals = principals_file != NULL ||
956             options.authorized_principals_command != NULL;
957 	if (!found_principal && use_authorized_principals) {
958 		reason = "Certificate does not contain an authorized principal";
959  fail_reason:
960 		error("%s", reason);
961 		auth_debug_add("%s", reason);
962 		goto out;
963 	}
964 	if (key_cert_check_authority(key, 0, 1,
965 	    use_authorized_principals ? NULL : pw->pw_name, &reason) != 0)
966 		goto fail_reason;
967 	if (auth_cert_options(key, pw) != 0)
968 		goto out;
969 
970 	verbose("Accepted certificate ID \"%s\" (serial %llu) signed by "
971 	    "%s CA %s via %s", key->cert->key_id,
972 	    (unsigned long long)key->cert->serial,
973 	    key_type(key->cert->signature_key), ca_fp,
974 	    options.trusted_user_ca_keys);
975 	ret = 1;
976 
977  out:
978 	free(principals_file);
979 	free(ca_fp);
980 	return ret;
981 }
982 
983 /*
984  * Checks whether key is allowed in file.
985  * returns 1 if the key is allowed or 0 otherwise.
986  */
987 static int
988 user_key_allowed2(struct passwd *pw, Key *key, char *file)
989 {
990 	FILE *f;
991 	int found_key = 0;
992 
993 	/* Temporarily use the user's uid. */
994 	temporarily_use_uid(pw);
995 
996 	debug("trying public key file %s", file);
997 	if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) {
998 		found_key = check_authkeys_file(f, file, key, pw);
999 		fclose(f);
1000 	}
1001 
1002 	restore_uid();
1003 	return found_key;
1004 }
1005 
1006 /*
1007  * Checks whether key is allowed in output of command.
1008  * returns 1 if the key is allowed or 0 otherwise.
1009  */
1010 static int
1011 user_key_command_allowed2(struct passwd *user_pw, Key *key)
1012 {
1013 	FILE *f = NULL;
1014 	int r, ok, found_key = 0;
1015 	struct passwd *pw;
1016 	int i, uid_swapped = 0, ac = 0;
1017 	pid_t pid;
1018 	char *username = NULL, *key_fp = NULL, *keytext = NULL;
1019 	char *tmp, *command = NULL, **av = NULL;
1020 	void (*osigchld)(int);
1021 
1022 	if (options.authorized_keys_command == NULL)
1023 		return 0;
1024 	if (options.authorized_keys_command_user == NULL) {
1025 		error("No user for AuthorizedKeysCommand specified, skipping");
1026 		return 0;
1027 	}
1028 
1029 	/*
1030 	 * NB. all returns later this function should go via "out" to
1031 	 * ensure the original SIGCHLD handler is restored properly.
1032 	 */
1033 	osigchld = signal(SIGCHLD, SIG_DFL);
1034 
1035 	/* Prepare and verify the user for the command */
1036 	username = percent_expand(options.authorized_keys_command_user,
1037 	    "u", user_pw->pw_name, (char *)NULL);
1038 	pw = getpwnam(username);
1039 	if (pw == NULL) {
1040 		error("AuthorizedKeysCommandUser \"%s\" not found: %s",
1041 		    username, strerror(errno));
1042 		goto out;
1043 	}
1044 
1045 	/* Prepare AuthorizedKeysCommand */
1046 	if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash,
1047 	    SSH_FP_DEFAULT)) == NULL) {
1048 		error("%s: sshkey_fingerprint failed", __func__);
1049 		goto out;
1050 	}
1051 	if ((r = sshkey_to_base64(key, &keytext)) != 0) {
1052 		error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r));
1053 		goto out;
1054 	}
1055 
1056 	/* Turn the command into an argument vector */
1057 	if (split_argv(options.authorized_keys_command, &ac, &av) != 0) {
1058 		error("AuthorizedKeysCommand \"%s\" contains invalid quotes",
1059 		    command);
1060 		goto out;
1061 	}
1062 	if (ac == 0) {
1063 		error("AuthorizedKeysCommand \"%s\" yielded no arguments",
1064 		    command);
1065 		goto out;
1066 	}
1067 	for (i = 1; i < ac; i++) {
1068 		tmp = percent_expand(av[i],
1069 		    "u", user_pw->pw_name,
1070 		    "h", user_pw->pw_dir,
1071 		    "t", sshkey_ssh_name(key),
1072 		    "f", key_fp,
1073 		    "k", keytext,
1074 		    (char *)NULL);
1075 		if (tmp == NULL)
1076 			fatal("%s: percent_expand failed", __func__);
1077 		free(av[i]);
1078 		av[i] = tmp;
1079 	}
1080 	/* Prepare a printable command for logs, etc. */
1081 	command = assemble_argv(ac, av);
1082 
1083 	/*
1084 	 * If AuthorizedKeysCommand was run without arguments
1085 	 * then fall back to the old behaviour of passing the
1086 	 * target username as a single argument.
1087 	 */
1088 	if (ac == 1) {
1089 		av = xreallocarray(av, ac + 2, sizeof(*av));
1090 		av[1] = xstrdup(user_pw->pw_name);
1091 		av[2] = NULL;
1092 		/* Fix up command too, since it is used in log messages */
1093 		free(command);
1094 		xasprintf(&command, "%s %s", av[0], av[1]);
1095 	}
1096 
1097 	if ((pid = subprocess("AuthorizedKeysCommand", pw, command,
1098 	    ac, av, &f)) == 0)
1099 		goto out;
1100 
1101 	uid_swapped = 1;
1102 	temporarily_use_uid(pw);
1103 
1104 	ok = check_authkeys_file(f, options.authorized_keys_command, key, pw);
1105 
1106 	if (exited_cleanly(pid, "AuthorizedKeysCommand", command) != 0)
1107 		goto out;
1108 
1109 	/* Read completed successfully */
1110 	found_key = ok;
1111  out:
1112 	if (f != NULL)
1113 		fclose(f);
1114 	signal(SIGCHLD, osigchld);
1115 	for (i = 0; i < ac; i++)
1116 		free(av[i]);
1117 	free(av);
1118 	if (uid_swapped)
1119 		restore_uid();
1120 	free(command);
1121 	free(username);
1122 	free(key_fp);
1123 	free(keytext);
1124 	return found_key;
1125 }
1126 
1127 /*
1128  * Check whether key authenticates and authorises the user.
1129  */
1130 int
1131 user_key_allowed(struct passwd *pw, Key *key, int auth_attempt)
1132 {
1133 	u_int success, i;
1134 	char *file;
1135 
1136 	if (auth_key_is_revoked(key))
1137 		return 0;
1138 	if (key_is_cert(key) && auth_key_is_revoked(key->cert->signature_key))
1139 		return 0;
1140 
1141 	success = user_cert_trusted_ca(pw, key);
1142 	if (success)
1143 		return success;
1144 
1145 	success = user_key_command_allowed2(pw, key);
1146 	if (success > 0)
1147 		return success;
1148 
1149 	for (i = 0; !success && i < options.num_authkeys_files; i++) {
1150 
1151 		if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
1152 			continue;
1153 		file = expand_authorized_keys(
1154 		    options.authorized_keys_files[i], pw);
1155 
1156 		success = user_key_allowed2(pw, key, file);
1157 		free(file);
1158 	}
1159 
1160 	return success;
1161 }
1162 
1163 /* Records a public key in the list of previously-successful keys */
1164 void
1165 auth2_record_userkey(Authctxt *authctxt, struct sshkey *key)
1166 {
1167 	struct sshkey **tmp;
1168 
1169 	if (authctxt->nprev_userkeys >= INT_MAX ||
1170 	    (tmp = reallocarray(authctxt->prev_userkeys,
1171 	    authctxt->nprev_userkeys + 1, sizeof(*tmp))) == NULL)
1172 		fatal("%s: reallocarray failed", __func__);
1173 	authctxt->prev_userkeys = tmp;
1174 	authctxt->prev_userkeys[authctxt->nprev_userkeys] = key;
1175 	authctxt->nprev_userkeys++;
1176 }
1177 
1178 /* Checks whether a key has already been used successfully for authentication */
1179 int
1180 auth2_userkey_already_used(Authctxt *authctxt, struct sshkey *key)
1181 {
1182 	u_int i;
1183 
1184 	for (i = 0; i < authctxt->nprev_userkeys; i++) {
1185 		if (sshkey_equal_public(key, authctxt->prev_userkeys[i])) {
1186 			return 1;
1187 		}
1188 	}
1189 	return 0;
1190 }
1191 
1192 Authmethod method_pubkey = {
1193 	"publickey",
1194 	userauth_pubkey,
1195 	&options.pubkey_authentication
1196 };
1197