xref: /openbsd-src/usr.bin/ssh/auth2-pubkey.c (revision 25c4e8bd056e974b28f4a0ffd39d76c190a56013)
1 /* $OpenBSD: auth2-pubkey.c,v 1.116 2022/06/15 16:08:25 djm Exp $ */
2 /*
3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2010 Damien Miller.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 
28 #include <sys/types.h>
29 
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <paths.h>
33 #include <pwd.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdarg.h>
37 #include <string.h>
38 #include <time.h>
39 #include <unistd.h>
40 #include <limits.h>
41 
42 #include "xmalloc.h"
43 #include "ssh.h"
44 #include "ssh2.h"
45 #include "packet.h"
46 #include "kex.h"
47 #include "sshbuf.h"
48 #include "log.h"
49 #include "misc.h"
50 #include "servconf.h"
51 #include "compat.h"
52 #include "sshkey.h"
53 #include "hostfile.h"
54 #include "auth.h"
55 #include "pathnames.h"
56 #include "uidswap.h"
57 #include "auth-options.h"
58 #include "canohost.h"
59 #ifdef GSSAPI
60 #include "ssh-gss.h"
61 #endif
62 #include "monitor_wrap.h"
63 #include "authfile.h"
64 #include "match.h"
65 #include "ssherr.h"
66 #include "channels.h" /* XXX for session.h */
67 #include "session.h" /* XXX for child_set_env(); refactor? */
68 #include "sk-api.h"
69 
70 /* import */
71 extern ServerOptions options;
72 
73 static char *
74 format_key(const struct sshkey *key)
75 {
76 	char *ret, *fp = sshkey_fingerprint(key,
77 	    options.fingerprint_hash, SSH_FP_DEFAULT);
78 
79 	xasprintf(&ret, "%s %s", sshkey_type(key), fp);
80 	free(fp);
81 	return ret;
82 }
83 
84 static int
85 userauth_pubkey(struct ssh *ssh, const char *method)
86 {
87 	Authctxt *authctxt = ssh->authctxt;
88 	struct passwd *pw = authctxt->pw;
89 	struct sshbuf *b = NULL;
90 	struct sshkey *key = NULL, *hostkey = NULL;
91 	char *pkalg = NULL, *userstyle = NULL, *key_s = NULL, *ca_s = NULL;
92 	u_char *pkblob = NULL, *sig = NULL, have_sig;
93 	size_t blen, slen;
94 	int hostbound, r, pktype;
95 	int req_presence = 0, req_verify = 0, authenticated = 0;
96 	struct sshauthopt *authopts = NULL;
97 	struct sshkey_sig_details *sig_details = NULL;
98 
99 	hostbound = strcmp(method, "publickey-hostbound-v00@openssh.com") == 0;
100 
101 	if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 ||
102 	    (r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
103 	    (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0)
104 		fatal_fr(r, "parse %s packet", method);
105 
106 	/* hostbound auth includes the hostkey offered at initial KEX */
107 	if (hostbound) {
108 		if ((r = sshpkt_getb_froms(ssh, &b)) != 0 ||
109 		    (r = sshkey_fromb(b, &hostkey)) != 0)
110 			fatal_fr(r, "parse %s hostkey", method);
111 		if (ssh->kex->initial_hostkey == NULL)
112 			fatal_f("internal error: initial hostkey not recorded");
113 		if (!sshkey_equal(hostkey, ssh->kex->initial_hostkey))
114 			fatal_f("%s packet contained wrong host key", method);
115 		sshbuf_free(b);
116 		b = NULL;
117 	}
118 
119 	if (log_level_get() >= SYSLOG_LEVEL_DEBUG2) {
120 		char *keystring;
121 		struct sshbuf *pkbuf;
122 
123 		if ((pkbuf = sshbuf_from(pkblob, blen)) == NULL)
124 			fatal_f("sshbuf_from failed");
125 		if ((keystring = sshbuf_dtob64_string(pkbuf, 0)) == NULL)
126 			fatal_f("sshbuf_dtob64 failed");
127 		debug2_f("%s user %s %s public key %s %s",
128 		    authctxt->valid ? "valid" : "invalid", authctxt->user,
129 		    have_sig ? "attempting" : "querying", pkalg, keystring);
130 		sshbuf_free(pkbuf);
131 		free(keystring);
132 	}
133 
134 	pktype = sshkey_type_from_name(pkalg);
135 	if (pktype == KEY_UNSPEC) {
136 		/* this is perfectly legal */
137 		verbose_f("unsupported public key algorithm: %s", pkalg);
138 		goto done;
139 	}
140 	if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
141 		error_fr(r, "parse key");
142 		goto done;
143 	}
144 	if (key == NULL) {
145 		error_f("cannot decode key: %s", pkalg);
146 		goto done;
147 	}
148 	if (key->type != pktype) {
149 		error_f("type mismatch for decoded key "
150 		    "(received %d, expected %d)", key->type, pktype);
151 		goto done;
152 	}
153 	if (sshkey_type_plain(key->type) == KEY_RSA &&
154 	    (ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
155 		logit("Refusing RSA key because client uses unsafe "
156 		    "signature scheme");
157 		goto done;
158 	}
159 	if (auth2_key_already_used(authctxt, key)) {
160 		logit("refusing previously-used %s key", sshkey_type(key));
161 		goto done;
162 	}
163 	if (match_pattern_list(pkalg, options.pubkey_accepted_algos, 0) != 1) {
164 		logit_f("signature algorithm %s not in "
165 		    "PubkeyAcceptedAlgorithms", pkalg);
166 		goto done;
167 	}
168 	if ((r = sshkey_check_cert_sigtype(key,
169 	    options.ca_sign_algorithms)) != 0) {
170 		logit_fr(r, "certificate signature algorithm %s",
171 		    (key->cert == NULL || key->cert->signature_type == NULL) ?
172 		    "(null)" : key->cert->signature_type);
173 		goto done;
174 	}
175 	key_s = format_key(key);
176 	if (sshkey_is_cert(key))
177 		ca_s = format_key(key->cert->signature_key);
178 
179 	if (have_sig) {
180 		debug3_f("%s have %s signature for %s%s%s",
181 		    method, pkalg, key_s,
182 		    ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
183 		if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 ||
184 		    (r = sshpkt_get_end(ssh)) != 0)
185 			fatal_fr(r, "parse signature packet");
186 		if ((b = sshbuf_new()) == NULL)
187 			fatal_f("sshbuf_new failed");
188 		if (ssh->compat & SSH_OLD_SESSIONID) {
189 			if ((r = sshbuf_putb(b, ssh->kex->session_id)) != 0)
190 				fatal_fr(r, "put old session id");
191 		} else {
192 			if ((r = sshbuf_put_stringb(b,
193 			    ssh->kex->session_id)) != 0)
194 				fatal_fr(r, "put session id");
195 		}
196 		if (!authctxt->valid || authctxt->user == NULL) {
197 			debug2_f("disabled because of invalid user");
198 			goto done;
199 		}
200 		/* reconstruct packet */
201 		xasprintf(&userstyle, "%s%s%s", authctxt->user,
202 		    authctxt->style ? ":" : "",
203 		    authctxt->style ? authctxt->style : "");
204 		if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
205 		    (r = sshbuf_put_cstring(b, userstyle)) != 0 ||
206 		    (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
207 		    (r = sshbuf_put_cstring(b, method)) != 0 ||
208 		    (r = sshbuf_put_u8(b, have_sig)) != 0 ||
209 		    (r = sshbuf_put_cstring(b, pkalg)) != 0 ||
210 		    (r = sshbuf_put_string(b, pkblob, blen)) != 0)
211 			fatal_fr(r, "reconstruct %s packet", method);
212 		if (hostbound &&
213 		    (r = sshkey_puts(ssh->kex->initial_hostkey, b)) != 0)
214 			fatal_fr(r, "reconstruct %s packet", method);
215 #ifdef DEBUG_PK
216 		sshbuf_dump(b, stderr);
217 #endif
218 		/* test for correct signature */
219 		authenticated = 0;
220 		if (PRIVSEP(user_key_allowed(ssh, pw, key, 1, &authopts)) &&
221 		    PRIVSEP(sshkey_verify(key, sig, slen,
222 		    sshbuf_ptr(b), sshbuf_len(b),
223 		    (ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL,
224 		    ssh->compat, &sig_details)) == 0) {
225 			authenticated = 1;
226 		}
227 		if (authenticated == 1 && sig_details != NULL) {
228 			auth2_record_info(authctxt, "signature count = %u",
229 			    sig_details->sk_counter);
230 			debug_f("sk_counter = %u, sk_flags = 0x%02x",
231 			    sig_details->sk_counter, sig_details->sk_flags);
232 			req_presence = (options.pubkey_auth_options &
233 			    PUBKEYAUTH_TOUCH_REQUIRED) ||
234 			    !authopts->no_require_user_presence;
235 			if (req_presence && (sig_details->sk_flags &
236 			    SSH_SK_USER_PRESENCE_REQD) == 0) {
237 				error("public key %s signature for %s%s from "
238 				    "%.128s port %d rejected: user presence "
239 				    "(authenticator touch) requirement "
240 				    "not met ", key_s,
241 				    authctxt->valid ? "" : "invalid user ",
242 				    authctxt->user, ssh_remote_ipaddr(ssh),
243 				    ssh_remote_port(ssh));
244 				authenticated = 0;
245 				goto done;
246 			}
247 			req_verify = (options.pubkey_auth_options &
248 			    PUBKEYAUTH_VERIFY_REQUIRED) ||
249 			    authopts->require_verify;
250 			if (req_verify && (sig_details->sk_flags &
251 			    SSH_SK_USER_VERIFICATION_REQD) == 0) {
252 				error("public key %s signature for %s%s from "
253 				    "%.128s port %d rejected: user "
254 				    "verification requirement not met ", key_s,
255 				    authctxt->valid ? "" : "invalid user ",
256 				    authctxt->user, ssh_remote_ipaddr(ssh),
257 				    ssh_remote_port(ssh));
258 				authenticated = 0;
259 				goto done;
260 			}
261 		}
262 		auth2_record_key(authctxt, authenticated, key);
263 	} else {
264 		debug_f("%s test pkalg %s pkblob %s%s%s", method, pkalg, key_s,
265 		    ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
266 
267 		if ((r = sshpkt_get_end(ssh)) != 0)
268 			fatal_fr(r, "parse packet");
269 
270 		if (!authctxt->valid || authctxt->user == NULL) {
271 			debug2_f("disabled because of invalid user");
272 			goto done;
273 		}
274 		/* XXX fake reply and always send PK_OK ? */
275 		/*
276 		 * XXX this allows testing whether a user is allowed
277 		 * to login: if you happen to have a valid pubkey this
278 		 * message is sent. the message is NEVER sent at all
279 		 * if a user is not allowed to login. is this an
280 		 * issue? -markus
281 		 */
282 		if (PRIVSEP(user_key_allowed(ssh, pw, key, 0, NULL))) {
283 			if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK))
284 			    != 0 ||
285 			    (r = sshpkt_put_cstring(ssh, pkalg)) != 0 ||
286 			    (r = sshpkt_put_string(ssh, pkblob, blen)) != 0 ||
287 			    (r = sshpkt_send(ssh)) != 0 ||
288 			    (r = ssh_packet_write_wait(ssh)) != 0)
289 				fatal_fr(r, "send packet");
290 			authctxt->postponed = 1;
291 		}
292 	}
293 done:
294 	if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) {
295 		debug_f("key options inconsistent with existing");
296 		authenticated = 0;
297 	}
298 	debug2_f("authenticated %d pkalg %s", authenticated, pkalg);
299 
300 	sshbuf_free(b);
301 	sshauthopt_free(authopts);
302 	sshkey_free(key);
303 	sshkey_free(hostkey);
304 	free(userstyle);
305 	free(pkalg);
306 	free(pkblob);
307 	free(key_s);
308 	free(ca_s);
309 	free(sig);
310 	sshkey_sig_details_free(sig_details);
311 	return authenticated;
312 }
313 
314 static int
315 match_principals_file(struct passwd *pw, char *file,
316     struct sshkey_cert *cert, struct sshauthopt **authoptsp)
317 {
318 	FILE *f;
319 	int success;
320 
321 	if (authoptsp != NULL)
322 		*authoptsp = NULL;
323 
324 	temporarily_use_uid(pw);
325 	debug("trying authorized principals file %s", file);
326 	if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) {
327 		restore_uid();
328 		return 0;
329 	}
330 	success = auth_process_principals(f, file, cert, authoptsp);
331 	fclose(f);
332 	restore_uid();
333 	return success;
334 }
335 
336 /*
337  * Checks whether principal is allowed in output of command.
338  * returns 1 if the principal is allowed or 0 otherwise.
339  */
340 static int
341 match_principals_command(struct passwd *user_pw,
342     const struct sshkey *key, struct sshauthopt **authoptsp)
343 {
344 	struct passwd *runas_pw = NULL;
345 	const struct sshkey_cert *cert = key->cert;
346 	FILE *f = NULL;
347 	int r, ok, found_principal = 0;
348 	int i, ac = 0, uid_swapped = 0;
349 	pid_t pid;
350 	char *tmp, *username = NULL, *command = NULL, **av = NULL;
351 	char *ca_fp = NULL, *key_fp = NULL, *catext = NULL, *keytext = NULL;
352 	char serial_s[32], uidstr[32];
353 	void (*osigchld)(int);
354 
355 	if (authoptsp != NULL)
356 		*authoptsp = NULL;
357 	if (options.authorized_principals_command == NULL)
358 		return 0;
359 	if (options.authorized_principals_command_user == NULL) {
360 		error("No user for AuthorizedPrincipalsCommand specified, "
361 		    "skipping");
362 		return 0;
363 	}
364 
365 	/*
366 	 * NB. all returns later this function should go via "out" to
367 	 * ensure the original SIGCHLD handler is restored properly.
368 	 */
369 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
370 
371 	/* Prepare and verify the user for the command */
372 	username = percent_expand(options.authorized_principals_command_user,
373 	    "u", user_pw->pw_name, (char *)NULL);
374 	runas_pw = getpwnam(username);
375 	if (runas_pw == NULL) {
376 		error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s",
377 		    username, strerror(errno));
378 		goto out;
379 	}
380 
381 	/* Turn the command into an argument vector */
382 	if (argv_split(options.authorized_principals_command,
383 	    &ac, &av, 0) != 0) {
384 		error("AuthorizedPrincipalsCommand \"%s\" contains "
385 		    "invalid quotes", options.authorized_principals_command);
386 		goto out;
387 	}
388 	if (ac == 0) {
389 		error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments",
390 		    options.authorized_principals_command);
391 		goto out;
392 	}
393 	if ((ca_fp = sshkey_fingerprint(cert->signature_key,
394 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
395 		error_f("sshkey_fingerprint failed");
396 		goto out;
397 	}
398 	if ((key_fp = sshkey_fingerprint(key,
399 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
400 		error_f("sshkey_fingerprint failed");
401 		goto out;
402 	}
403 	if ((r = sshkey_to_base64(cert->signature_key, &catext)) != 0) {
404 		error_fr(r, "sshkey_to_base64 failed");
405 		goto out;
406 	}
407 	if ((r = sshkey_to_base64(key, &keytext)) != 0) {
408 		error_fr(r, "sshkey_to_base64 failed");
409 		goto out;
410 	}
411 	snprintf(serial_s, sizeof(serial_s), "%llu",
412 	    (unsigned long long)cert->serial);
413 	snprintf(uidstr, sizeof(uidstr), "%llu",
414 	    (unsigned long long)user_pw->pw_uid);
415 	for (i = 1; i < ac; i++) {
416 		tmp = percent_expand(av[i],
417 		    "U", uidstr,
418 		    "u", user_pw->pw_name,
419 		    "h", user_pw->pw_dir,
420 		    "t", sshkey_ssh_name(key),
421 		    "T", sshkey_ssh_name(cert->signature_key),
422 		    "f", key_fp,
423 		    "F", ca_fp,
424 		    "k", keytext,
425 		    "K", catext,
426 		    "i", cert->key_id,
427 		    "s", serial_s,
428 		    (char *)NULL);
429 		if (tmp == NULL)
430 			fatal_f("percent_expand failed");
431 		free(av[i]);
432 		av[i] = tmp;
433 	}
434 	/* Prepare a printable command for logs, etc. */
435 	command = argv_assemble(ac, av);
436 
437 	if ((pid = subprocess("AuthorizedPrincipalsCommand", command,
438 	    ac, av, &f,
439 	    SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
440 	    runas_pw, temporarily_use_uid, restore_uid)) == 0)
441 		goto out;
442 
443 	uid_swapped = 1;
444 	temporarily_use_uid(runas_pw);
445 
446 	ok = auth_process_principals(f, "(command)", cert, authoptsp);
447 
448 	fclose(f);
449 	f = NULL;
450 
451 	if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command, 0) != 0)
452 		goto out;
453 
454 	/* Read completed successfully */
455 	found_principal = ok;
456  out:
457 	if (f != NULL)
458 		fclose(f);
459 	ssh_signal(SIGCHLD, osigchld);
460 	for (i = 0; i < ac; i++)
461 		free(av[i]);
462 	free(av);
463 	if (uid_swapped)
464 		restore_uid();
465 	free(command);
466 	free(username);
467 	free(ca_fp);
468 	free(key_fp);
469 	free(catext);
470 	free(keytext);
471 	return found_principal;
472 }
473 
474 /* Authenticate a certificate key against TrustedUserCAKeys */
475 static int
476 user_cert_trusted_ca(struct passwd *pw, struct sshkey *key,
477     const char *remote_ip, const char *remote_host,
478     struct sshauthopt **authoptsp)
479 {
480 	char *ca_fp, *principals_file = NULL;
481 	const char *reason;
482 	struct sshauthopt *principals_opts = NULL, *cert_opts = NULL;
483 	struct sshauthopt *final_opts = NULL;
484 	int r, ret = 0, found_principal = 0, use_authorized_principals;
485 
486 	if (authoptsp != NULL)
487 		*authoptsp = NULL;
488 
489 	if (!sshkey_is_cert(key) || options.trusted_user_ca_keys == NULL)
490 		return 0;
491 
492 	if ((ca_fp = sshkey_fingerprint(key->cert->signature_key,
493 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
494 		return 0;
495 
496 	if ((r = sshkey_in_file(key->cert->signature_key,
497 	    options.trusted_user_ca_keys, 1, 0)) != 0) {
498 		debug2_fr(r, "CA %s %s is not listed in %s",
499 		    sshkey_type(key->cert->signature_key), ca_fp,
500 		    options.trusted_user_ca_keys);
501 		goto out;
502 	}
503 	/*
504 	 * If AuthorizedPrincipals is in use, then compare the certificate
505 	 * principals against the names in that file rather than matching
506 	 * against the username.
507 	 */
508 	if ((principals_file = authorized_principals_file(pw)) != NULL) {
509 		if (match_principals_file(pw, principals_file,
510 		    key->cert, &principals_opts))
511 			found_principal = 1;
512 	}
513 	/* Try querying command if specified */
514 	if (!found_principal && match_principals_command(pw, key,
515 	    &principals_opts))
516 		found_principal = 1;
517 	/* If principals file or command is specified, then require a match */
518 	use_authorized_principals = principals_file != NULL ||
519 	    options.authorized_principals_command != NULL;
520 	if (!found_principal && use_authorized_principals) {
521 		reason = "Certificate does not contain an authorized principal";
522 		goto fail_reason;
523 	}
524 	if (use_authorized_principals && principals_opts == NULL)
525 		fatal_f("internal error: missing principals_opts");
526 	if (sshkey_cert_check_authority_now(key, 0, 1, 0,
527 	    use_authorized_principals ? NULL : pw->pw_name, &reason) != 0)
528 		goto fail_reason;
529 
530 	/* Check authority from options in key and from principals file/cmd */
531 	if ((cert_opts = sshauthopt_from_cert(key)) == NULL) {
532 		reason = "Invalid certificate options";
533 		goto fail_reason;
534 	}
535 	if (auth_authorise_keyopts(pw, cert_opts, 0,
536 	    remote_ip, remote_host, "cert") != 0) {
537 		reason = "Refused by certificate options";
538 		goto fail_reason;
539 	}
540 	if (principals_opts == NULL) {
541 		final_opts = cert_opts;
542 		cert_opts = NULL;
543 	} else {
544 		if (auth_authorise_keyopts(pw, principals_opts, 0,
545 		    remote_ip, remote_host, "principals") != 0) {
546 			reason = "Refused by certificate principals options";
547 			goto fail_reason;
548 		}
549 		if ((final_opts = sshauthopt_merge(principals_opts,
550 		    cert_opts, &reason)) == NULL) {
551  fail_reason:
552 			error("%s", reason);
553 			auth_debug_add("%s", reason);
554 			goto out;
555 		}
556 	}
557 
558 	/* Success */
559 	verbose("Accepted certificate ID \"%s\" (serial %llu) signed by "
560 	    "%s CA %s via %s", key->cert->key_id,
561 	    (unsigned long long)key->cert->serial,
562 	    sshkey_type(key->cert->signature_key), ca_fp,
563 	    options.trusted_user_ca_keys);
564 	if (authoptsp != NULL) {
565 		*authoptsp = final_opts;
566 		final_opts = NULL;
567 	}
568 	ret = 1;
569  out:
570 	sshauthopt_free(principals_opts);
571 	sshauthopt_free(cert_opts);
572 	sshauthopt_free(final_opts);
573 	free(principals_file);
574 	free(ca_fp);
575 	return ret;
576 }
577 
578 /*
579  * Checks whether key is allowed in file.
580  * returns 1 if the key is allowed or 0 otherwise.
581  */
582 static int
583 user_key_allowed2(struct passwd *pw, struct sshkey *key,
584     char *file, const char *remote_ip, const char *remote_host,
585     struct sshauthopt **authoptsp)
586 {
587 	FILE *f;
588 	int found_key = 0;
589 
590 	if (authoptsp != NULL)
591 		*authoptsp = NULL;
592 
593 	/* Temporarily use the user's uid. */
594 	temporarily_use_uid(pw);
595 
596 	debug("trying public key file %s", file);
597 	if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) {
598 		found_key = auth_check_authkeys_file(pw, f, file,
599 		    key, remote_ip, remote_host, authoptsp);
600 		fclose(f);
601 	}
602 
603 	restore_uid();
604 	return found_key;
605 }
606 
607 /*
608  * Checks whether key is allowed in output of command.
609  * returns 1 if the key is allowed or 0 otherwise.
610  */
611 static int
612 user_key_command_allowed2(struct passwd *user_pw, struct sshkey *key,
613     const char *remote_ip, const char *remote_host,
614     struct sshauthopt **authoptsp)
615 {
616 	struct passwd *runas_pw = NULL;
617 	FILE *f = NULL;
618 	int r, ok, found_key = 0;
619 	int i, uid_swapped = 0, ac = 0;
620 	pid_t pid;
621 	char *username = NULL, *key_fp = NULL, *keytext = NULL;
622 	char uidstr[32], *tmp, *command = NULL, **av = NULL;
623 	void (*osigchld)(int);
624 
625 	if (authoptsp != NULL)
626 		*authoptsp = NULL;
627 	if (options.authorized_keys_command == NULL)
628 		return 0;
629 	if (options.authorized_keys_command_user == NULL) {
630 		error("No user for AuthorizedKeysCommand specified, skipping");
631 		return 0;
632 	}
633 
634 	/*
635 	 * NB. all returns later this function should go via "out" to
636 	 * ensure the original SIGCHLD handler is restored properly.
637 	 */
638 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
639 
640 	/* Prepare and verify the user for the command */
641 	username = percent_expand(options.authorized_keys_command_user,
642 	    "u", user_pw->pw_name, (char *)NULL);
643 	runas_pw = getpwnam(username);
644 	if (runas_pw == NULL) {
645 		error("AuthorizedKeysCommandUser \"%s\" not found: %s",
646 		    username, strerror(errno));
647 		goto out;
648 	}
649 
650 	/* Prepare AuthorizedKeysCommand */
651 	if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash,
652 	    SSH_FP_DEFAULT)) == NULL) {
653 		error_f("sshkey_fingerprint failed");
654 		goto out;
655 	}
656 	if ((r = sshkey_to_base64(key, &keytext)) != 0) {
657 		error_fr(r, "sshkey_to_base64 failed");
658 		goto out;
659 	}
660 
661 	/* Turn the command into an argument vector */
662 	if (argv_split(options.authorized_keys_command, &ac, &av, 0) != 0) {
663 		error("AuthorizedKeysCommand \"%s\" contains invalid quotes",
664 		    options.authorized_keys_command);
665 		goto out;
666 	}
667 	if (ac == 0) {
668 		error("AuthorizedKeysCommand \"%s\" yielded no arguments",
669 		    options.authorized_keys_command);
670 		goto out;
671 	}
672 	snprintf(uidstr, sizeof(uidstr), "%llu",
673 	    (unsigned long long)user_pw->pw_uid);
674 	for (i = 1; i < ac; i++) {
675 		tmp = percent_expand(av[i],
676 		    "U", uidstr,
677 		    "u", user_pw->pw_name,
678 		    "h", user_pw->pw_dir,
679 		    "t", sshkey_ssh_name(key),
680 		    "f", key_fp,
681 		    "k", keytext,
682 		    (char *)NULL);
683 		if (tmp == NULL)
684 			fatal_f("percent_expand failed");
685 		free(av[i]);
686 		av[i] = tmp;
687 	}
688 	/* Prepare a printable command for logs, etc. */
689 	command = argv_assemble(ac, av);
690 
691 	/*
692 	 * If AuthorizedKeysCommand was run without arguments
693 	 * then fall back to the old behaviour of passing the
694 	 * target username as a single argument.
695 	 */
696 	if (ac == 1) {
697 		av = xreallocarray(av, ac + 2, sizeof(*av));
698 		av[1] = xstrdup(user_pw->pw_name);
699 		av[2] = NULL;
700 		/* Fix up command too, since it is used in log messages */
701 		free(command);
702 		xasprintf(&command, "%s %s", av[0], av[1]);
703 	}
704 
705 	if ((pid = subprocess("AuthorizedKeysCommand", command,
706 	    ac, av, &f,
707 	    SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
708 	    runas_pw, temporarily_use_uid, restore_uid)) == 0)
709 		goto out;
710 
711 	uid_swapped = 1;
712 	temporarily_use_uid(runas_pw);
713 
714 	ok = auth_check_authkeys_file(user_pw, f,
715 	    options.authorized_keys_command, key, remote_ip,
716 	    remote_host, authoptsp);
717 
718 	fclose(f);
719 	f = NULL;
720 
721 	if (exited_cleanly(pid, "AuthorizedKeysCommand", command, 0) != 0)
722 		goto out;
723 
724 	/* Read completed successfully */
725 	found_key = ok;
726  out:
727 	if (f != NULL)
728 		fclose(f);
729 	ssh_signal(SIGCHLD, osigchld);
730 	for (i = 0; i < ac; i++)
731 		free(av[i]);
732 	free(av);
733 	if (uid_swapped)
734 		restore_uid();
735 	free(command);
736 	free(username);
737 	free(key_fp);
738 	free(keytext);
739 	return found_key;
740 }
741 
742 /*
743  * Check whether key authenticates and authorises the user.
744  */
745 int
746 user_key_allowed(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
747     int auth_attempt, struct sshauthopt **authoptsp)
748 {
749 	u_int success = 0, i;
750 	char *file;
751 	struct sshauthopt *opts = NULL;
752 	const char *remote_ip = ssh_remote_ipaddr(ssh);
753 	const char *remote_host = auth_get_canonical_hostname(ssh,
754 	    options.use_dns);
755 
756 	if (authoptsp != NULL)
757 		*authoptsp = NULL;
758 
759 	if (auth_key_is_revoked(key))
760 		return 0;
761 	if (sshkey_is_cert(key) &&
762 	    auth_key_is_revoked(key->cert->signature_key))
763 		return 0;
764 
765 	for (i = 0; !success && i < options.num_authkeys_files; i++) {
766 		if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
767 			continue;
768 		file = expand_authorized_keys(
769 		    options.authorized_keys_files[i], pw);
770 		success = user_key_allowed2(pw, key, file,
771 		    remote_ip, remote_host, &opts);
772 		free(file);
773 		if (!success) {
774 			sshauthopt_free(opts);
775 			opts = NULL;
776 		}
777 	}
778 	if (success)
779 		goto out;
780 
781 	if ((success = user_cert_trusted_ca(pw, key, remote_ip, remote_host,
782 	    &opts)) != 0)
783 		goto out;
784 	sshauthopt_free(opts);
785 	opts = NULL;
786 
787 	if ((success = user_key_command_allowed2(pw, key, remote_ip,
788 	    remote_host, &opts)) != 0)
789 		goto out;
790 	sshauthopt_free(opts);
791 	opts = NULL;
792 
793  out:
794 	if (success && authoptsp != NULL) {
795 		*authoptsp = opts;
796 		opts = NULL;
797 	}
798 	sshauthopt_free(opts);
799 	return success;
800 }
801 
802 Authmethod method_pubkey = {
803 	"publickey",
804 	"publickey-hostbound-v00@openssh.com",
805 	userauth_pubkey,
806 	&options.pubkey_authentication
807 };
808