xref: /openbsd-src/usr.bin/ssh/auth2-pubkey.c (revision 68dd5bb1859285b71cb62a10bf107b8ad54064d9)
1 /* $OpenBSD: auth2-pubkey.c,v 1.119 2023/07/27 22:25:17 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 (auth2_key_already_used(authctxt, key)) {
154 		logit("refusing previously-used %s key", sshkey_type(key));
155 		goto done;
156 	}
157 	if (match_pattern_list(pkalg, options.pubkey_accepted_algos, 0) != 1) {
158 		logit_f("signature algorithm %s not in "
159 		    "PubkeyAcceptedAlgorithms", pkalg);
160 		goto done;
161 	}
162 	if ((r = sshkey_check_cert_sigtype(key,
163 	    options.ca_sign_algorithms)) != 0) {
164 		logit_fr(r, "certificate signature algorithm %s",
165 		    (key->cert == NULL || key->cert->signature_type == NULL) ?
166 		    "(null)" : key->cert->signature_type);
167 		goto done;
168 	}
169 	if ((r = sshkey_check_rsa_length(key,
170 	    options.required_rsa_size)) != 0) {
171 		logit_r(r, "refusing %s key", sshkey_type(key));
172 		goto done;
173 	}
174 	key_s = format_key(key);
175 	if (sshkey_is_cert(key))
176 		ca_s = format_key(key->cert->signature_key);
177 
178 	if (have_sig) {
179 		debug3_f("%s have %s signature for %s%s%s",
180 		    method, pkalg, key_s,
181 		    ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
182 		if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 ||
183 		    (r = sshpkt_get_end(ssh)) != 0)
184 			fatal_fr(r, "parse signature packet");
185 		if ((b = sshbuf_new()) == NULL)
186 			fatal_f("sshbuf_new failed");
187 		if (ssh->compat & SSH_OLD_SESSIONID) {
188 			if ((r = sshbuf_putb(b, ssh->kex->session_id)) != 0)
189 				fatal_fr(r, "put old session id");
190 		} else {
191 			if ((r = sshbuf_put_stringb(b,
192 			    ssh->kex->session_id)) != 0)
193 				fatal_fr(r, "put session id");
194 		}
195 		if (!authctxt->valid || authctxt->user == NULL) {
196 			debug2_f("disabled because of invalid user");
197 			goto done;
198 		}
199 		/* reconstruct packet */
200 		xasprintf(&userstyle, "%s%s%s", authctxt->user,
201 		    authctxt->style ? ":" : "",
202 		    authctxt->style ? authctxt->style : "");
203 		if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
204 		    (r = sshbuf_put_cstring(b, userstyle)) != 0 ||
205 		    (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
206 		    (r = sshbuf_put_cstring(b, method)) != 0 ||
207 		    (r = sshbuf_put_u8(b, have_sig)) != 0 ||
208 		    (r = sshbuf_put_cstring(b, pkalg)) != 0 ||
209 		    (r = sshbuf_put_string(b, pkblob, blen)) != 0)
210 			fatal_fr(r, "reconstruct %s packet", method);
211 		if (hostbound &&
212 		    (r = sshkey_puts(ssh->kex->initial_hostkey, b)) != 0)
213 			fatal_fr(r, "reconstruct %s packet", method);
214 #ifdef DEBUG_PK
215 		sshbuf_dump(b, stderr);
216 #endif
217 		/* test for correct signature */
218 		authenticated = 0;
219 		if (PRIVSEP(user_key_allowed(ssh, pw, key, 1, &authopts)) &&
220 		    PRIVSEP(sshkey_verify(key, sig, slen,
221 		    sshbuf_ptr(b), sshbuf_len(b),
222 		    (ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL,
223 		    ssh->compat, &sig_details)) == 0) {
224 			authenticated = 1;
225 		}
226 		if (authenticated == 1 && sig_details != NULL) {
227 			auth2_record_info(authctxt, "signature count = %u",
228 			    sig_details->sk_counter);
229 			debug_f("sk_counter = %u, sk_flags = 0x%02x",
230 			    sig_details->sk_counter, sig_details->sk_flags);
231 			req_presence = (options.pubkey_auth_options &
232 			    PUBKEYAUTH_TOUCH_REQUIRED) ||
233 			    !authopts->no_require_user_presence;
234 			if (req_presence && (sig_details->sk_flags &
235 			    SSH_SK_USER_PRESENCE_REQD) == 0) {
236 				error("public key %s signature for %s%s from "
237 				    "%.128s port %d rejected: user presence "
238 				    "(authenticator touch) requirement "
239 				    "not met ", key_s,
240 				    authctxt->valid ? "" : "invalid user ",
241 				    authctxt->user, ssh_remote_ipaddr(ssh),
242 				    ssh_remote_port(ssh));
243 				authenticated = 0;
244 				goto done;
245 			}
246 			req_verify = (options.pubkey_auth_options &
247 			    PUBKEYAUTH_VERIFY_REQUIRED) ||
248 			    authopts->require_verify;
249 			if (req_verify && (sig_details->sk_flags &
250 			    SSH_SK_USER_VERIFICATION_REQD) == 0) {
251 				error("public key %s signature for %s%s from "
252 				    "%.128s port %d rejected: user "
253 				    "verification requirement not met ", key_s,
254 				    authctxt->valid ? "" : "invalid user ",
255 				    authctxt->user, ssh_remote_ipaddr(ssh),
256 				    ssh_remote_port(ssh));
257 				authenticated = 0;
258 				goto done;
259 			}
260 		}
261 		auth2_record_key(authctxt, authenticated, key);
262 	} else {
263 		debug_f("%s test pkalg %s pkblob %s%s%s", method, pkalg, key_s,
264 		    ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
265 
266 		if ((r = sshpkt_get_end(ssh)) != 0)
267 			fatal_fr(r, "parse packet");
268 
269 		if (!authctxt->valid || authctxt->user == NULL) {
270 			debug2_f("disabled because of invalid user");
271 			goto done;
272 		}
273 		/* XXX fake reply and always send PK_OK ? */
274 		/*
275 		 * XXX this allows testing whether a user is allowed
276 		 * to login: if you happen to have a valid pubkey this
277 		 * message is sent. the message is NEVER sent at all
278 		 * if a user is not allowed to login. is this an
279 		 * issue? -markus
280 		 */
281 		if (PRIVSEP(user_key_allowed(ssh, pw, key, 0, NULL))) {
282 			if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK))
283 			    != 0 ||
284 			    (r = sshpkt_put_cstring(ssh, pkalg)) != 0 ||
285 			    (r = sshpkt_put_string(ssh, pkblob, blen)) != 0 ||
286 			    (r = sshpkt_send(ssh)) != 0 ||
287 			    (r = ssh_packet_write_wait(ssh)) != 0)
288 				fatal_fr(r, "send packet");
289 			authctxt->postponed = 1;
290 		}
291 	}
292 done:
293 	if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) {
294 		debug_f("key options inconsistent with existing");
295 		authenticated = 0;
296 	}
297 	debug2_f("authenticated %d pkalg %s", authenticated, pkalg);
298 
299 	sshbuf_free(b);
300 	sshauthopt_free(authopts);
301 	sshkey_free(key);
302 	sshkey_free(hostkey);
303 	free(userstyle);
304 	free(pkalg);
305 	free(pkblob);
306 	free(key_s);
307 	free(ca_s);
308 	free(sig);
309 	sshkey_sig_details_free(sig_details);
310 	return authenticated;
311 }
312 
313 static int
314 match_principals_file(struct passwd *pw, char *file,
315     struct sshkey_cert *cert, struct sshauthopt **authoptsp)
316 {
317 	FILE *f;
318 	int success;
319 
320 	if (authoptsp != NULL)
321 		*authoptsp = NULL;
322 
323 	temporarily_use_uid(pw);
324 	debug("trying authorized principals file %s", file);
325 	if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) {
326 		restore_uid();
327 		return 0;
328 	}
329 	success = auth_process_principals(f, file, cert, authoptsp);
330 	fclose(f);
331 	restore_uid();
332 	return success;
333 }
334 
335 /*
336  * Checks whether principal is allowed in output of command.
337  * returns 1 if the principal is allowed or 0 otherwise.
338  */
339 static int
340 match_principals_command(struct passwd *user_pw, const struct sshkey *key,
341     const char *conn_id, const char *rdomain, struct sshauthopt **authoptsp)
342 {
343 	struct passwd *runas_pw = NULL;
344 	const struct sshkey_cert *cert = key->cert;
345 	FILE *f = NULL;
346 	int r, ok, found_principal = 0;
347 	int i, ac = 0, uid_swapped = 0;
348 	pid_t pid;
349 	char *tmp, *username = NULL, *command = NULL, **av = NULL;
350 	char *ca_fp = NULL, *key_fp = NULL, *catext = NULL, *keytext = NULL;
351 	char serial_s[32], uidstr[32];
352 	void (*osigchld)(int);
353 
354 	if (authoptsp != NULL)
355 		*authoptsp = NULL;
356 	if (options.authorized_principals_command == NULL)
357 		return 0;
358 	if (options.authorized_principals_command_user == NULL) {
359 		error("No user for AuthorizedPrincipalsCommand specified, "
360 		    "skipping");
361 		return 0;
362 	}
363 
364 	/*
365 	 * NB. all returns later this function should go via "out" to
366 	 * ensure the original SIGCHLD handler is restored properly.
367 	 */
368 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
369 
370 	/* Prepare and verify the user for the command */
371 	username = percent_expand(options.authorized_principals_command_user,
372 	    "u", user_pw->pw_name, (char *)NULL);
373 	runas_pw = getpwnam(username);
374 	if (runas_pw == NULL) {
375 		error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s",
376 		    username, strerror(errno));
377 		goto out;
378 	}
379 
380 	/* Turn the command into an argument vector */
381 	if (argv_split(options.authorized_principals_command,
382 	    &ac, &av, 0) != 0) {
383 		error("AuthorizedPrincipalsCommand \"%s\" contains "
384 		    "invalid quotes", options.authorized_principals_command);
385 		goto out;
386 	}
387 	if (ac == 0) {
388 		error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments",
389 		    options.authorized_principals_command);
390 		goto out;
391 	}
392 	if ((ca_fp = sshkey_fingerprint(cert->signature_key,
393 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
394 		error_f("sshkey_fingerprint failed");
395 		goto out;
396 	}
397 	if ((key_fp = sshkey_fingerprint(key,
398 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
399 		error_f("sshkey_fingerprint failed");
400 		goto out;
401 	}
402 	if ((r = sshkey_to_base64(cert->signature_key, &catext)) != 0) {
403 		error_fr(r, "sshkey_to_base64 failed");
404 		goto out;
405 	}
406 	if ((r = sshkey_to_base64(key, &keytext)) != 0) {
407 		error_fr(r, "sshkey_to_base64 failed");
408 		goto out;
409 	}
410 	snprintf(serial_s, sizeof(serial_s), "%llu",
411 	    (unsigned long long)cert->serial);
412 	snprintf(uidstr, sizeof(uidstr), "%llu",
413 	    (unsigned long long)user_pw->pw_uid);
414 	for (i = 1; i < ac; i++) {
415 		tmp = percent_expand(av[i],
416 		    "C", conn_id,
417 		    "D", rdomain,
418 		    "U", uidstr,
419 		    "u", user_pw->pw_name,
420 		    "h", user_pw->pw_dir,
421 		    "t", sshkey_ssh_name(key),
422 		    "T", sshkey_ssh_name(cert->signature_key),
423 		    "f", key_fp,
424 		    "F", ca_fp,
425 		    "k", keytext,
426 		    "K", catext,
427 		    "i", cert->key_id,
428 		    "s", serial_s,
429 		    (char *)NULL);
430 		if (tmp == NULL)
431 			fatal_f("percent_expand failed");
432 		free(av[i]);
433 		av[i] = tmp;
434 	}
435 	/* Prepare a printable command for logs, etc. */
436 	command = argv_assemble(ac, av);
437 
438 	if ((pid = subprocess("AuthorizedPrincipalsCommand", command,
439 	    ac, av, &f,
440 	    SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
441 	    runas_pw, temporarily_use_uid, restore_uid)) == 0)
442 		goto out;
443 
444 	uid_swapped = 1;
445 	temporarily_use_uid(runas_pw);
446 
447 	ok = auth_process_principals(f, "(command)", cert, authoptsp);
448 
449 	fclose(f);
450 	f = NULL;
451 
452 	if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command, 0) != 0)
453 		goto out;
454 
455 	/* Read completed successfully */
456 	found_principal = ok;
457  out:
458 	if (f != NULL)
459 		fclose(f);
460 	ssh_signal(SIGCHLD, osigchld);
461 	for (i = 0; i < ac; i++)
462 		free(av[i]);
463 	free(av);
464 	if (uid_swapped)
465 		restore_uid();
466 	free(command);
467 	free(username);
468 	free(ca_fp);
469 	free(key_fp);
470 	free(catext);
471 	free(keytext);
472 	return found_principal;
473 }
474 
475 /* Authenticate a certificate key against TrustedUserCAKeys */
476 static int
477 user_cert_trusted_ca(struct passwd *pw, struct sshkey *key,
478     const char *remote_ip, const char *remote_host,
479     const char *conn_id, const char *rdomain, struct sshauthopt **authoptsp)
480 {
481 	char *ca_fp, *principals_file = NULL;
482 	const char *reason;
483 	struct sshauthopt *principals_opts = NULL, *cert_opts = NULL;
484 	struct sshauthopt *final_opts = NULL;
485 	int r, ret = 0, found_principal = 0, use_authorized_principals;
486 
487 	if (authoptsp != NULL)
488 		*authoptsp = NULL;
489 
490 	if (!sshkey_is_cert(key) || options.trusted_user_ca_keys == NULL)
491 		return 0;
492 
493 	if ((ca_fp = sshkey_fingerprint(key->cert->signature_key,
494 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
495 		return 0;
496 
497 	if ((r = sshkey_in_file(key->cert->signature_key,
498 	    options.trusted_user_ca_keys, 1, 0)) != 0) {
499 		debug2_fr(r, "CA %s %s is not listed in %s",
500 		    sshkey_type(key->cert->signature_key), ca_fp,
501 		    options.trusted_user_ca_keys);
502 		goto out;
503 	}
504 	/*
505 	 * If AuthorizedPrincipals is in use, then compare the certificate
506 	 * principals against the names in that file rather than matching
507 	 * against the username.
508 	 */
509 	if ((principals_file = authorized_principals_file(pw)) != NULL) {
510 		if (match_principals_file(pw, principals_file,
511 		    key->cert, &principals_opts))
512 			found_principal = 1;
513 	}
514 	/* Try querying command if specified */
515 	if (!found_principal && match_principals_command(pw, key,
516 	    conn_id, rdomain, &principals_opts))
517 		found_principal = 1;
518 	/* If principals file or command is specified, then require a match */
519 	use_authorized_principals = principals_file != NULL ||
520 	    options.authorized_principals_command != NULL;
521 	if (!found_principal && use_authorized_principals) {
522 		reason = "Certificate does not contain an authorized principal";
523 		goto fail_reason;
524 	}
525 	if (use_authorized_principals && principals_opts == NULL)
526 		fatal_f("internal error: missing principals_opts");
527 	if (sshkey_cert_check_authority_now(key, 0, 1, 0,
528 	    use_authorized_principals ? NULL : pw->pw_name, &reason) != 0)
529 		goto fail_reason;
530 
531 	/* Check authority from options in key and from principals file/cmd */
532 	if ((cert_opts = sshauthopt_from_cert(key)) == NULL) {
533 		reason = "Invalid certificate options";
534 		goto fail_reason;
535 	}
536 	if (auth_authorise_keyopts(pw, cert_opts, 0,
537 	    remote_ip, remote_host, "cert") != 0) {
538 		reason = "Refused by certificate options";
539 		goto fail_reason;
540 	}
541 	if (principals_opts == NULL) {
542 		final_opts = cert_opts;
543 		cert_opts = NULL;
544 	} else {
545 		if (auth_authorise_keyopts(pw, principals_opts, 0,
546 		    remote_ip, remote_host, "principals") != 0) {
547 			reason = "Refused by certificate principals options";
548 			goto fail_reason;
549 		}
550 		if ((final_opts = sshauthopt_merge(principals_opts,
551 		    cert_opts, &reason)) == NULL) {
552  fail_reason:
553 			error("%s", reason);
554 			auth_debug_add("%s", reason);
555 			goto out;
556 		}
557 	}
558 
559 	/* Success */
560 	verbose("Accepted certificate ID \"%s\" (serial %llu) signed by "
561 	    "%s CA %s via %s", key->cert->key_id,
562 	    (unsigned long long)key->cert->serial,
563 	    sshkey_type(key->cert->signature_key), ca_fp,
564 	    options.trusted_user_ca_keys);
565 	if (authoptsp != NULL) {
566 		*authoptsp = final_opts;
567 		final_opts = NULL;
568 	}
569 	ret = 1;
570  out:
571 	sshauthopt_free(principals_opts);
572 	sshauthopt_free(cert_opts);
573 	sshauthopt_free(final_opts);
574 	free(principals_file);
575 	free(ca_fp);
576 	return ret;
577 }
578 
579 /*
580  * Checks whether key is allowed in file.
581  * returns 1 if the key is allowed or 0 otherwise.
582  */
583 static int
584 user_key_allowed2(struct passwd *pw, struct sshkey *key,
585     char *file, const char *remote_ip, const char *remote_host,
586     struct sshauthopt **authoptsp)
587 {
588 	FILE *f;
589 	int found_key = 0;
590 
591 	if (authoptsp != NULL)
592 		*authoptsp = NULL;
593 
594 	/* Temporarily use the user's uid. */
595 	temporarily_use_uid(pw);
596 
597 	debug("trying public key file %s", file);
598 	if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) {
599 		found_key = auth_check_authkeys_file(pw, f, file,
600 		    key, remote_ip, remote_host, authoptsp);
601 		fclose(f);
602 	}
603 
604 	restore_uid();
605 	return found_key;
606 }
607 
608 /*
609  * Checks whether key is allowed in output of command.
610  * returns 1 if the key is allowed or 0 otherwise.
611  */
612 static int
613 user_key_command_allowed2(struct passwd *user_pw, struct sshkey *key,
614     const char *remote_ip, const char *remote_host,
615     const char *conn_id, const char *rdomain, struct sshauthopt **authoptsp)
616 {
617 	struct passwd *runas_pw = NULL;
618 	FILE *f = NULL;
619 	int r, ok, found_key = 0;
620 	int i, uid_swapped = 0, ac = 0;
621 	pid_t pid;
622 	char *username = NULL, *key_fp = NULL, *keytext = NULL;
623 	char uidstr[32], *tmp, *command = NULL, **av = NULL;
624 	void (*osigchld)(int);
625 
626 	if (authoptsp != NULL)
627 		*authoptsp = NULL;
628 	if (options.authorized_keys_command == NULL)
629 		return 0;
630 	if (options.authorized_keys_command_user == NULL) {
631 		error("No user for AuthorizedKeysCommand specified, skipping");
632 		return 0;
633 	}
634 
635 	/*
636 	 * NB. all returns later this function should go via "out" to
637 	 * ensure the original SIGCHLD handler is restored properly.
638 	 */
639 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
640 
641 	/* Prepare and verify the user for the command */
642 	username = percent_expand(options.authorized_keys_command_user,
643 	    "u", user_pw->pw_name, (char *)NULL);
644 	runas_pw = getpwnam(username);
645 	if (runas_pw == NULL) {
646 		error("AuthorizedKeysCommandUser \"%s\" not found: %s",
647 		    username, strerror(errno));
648 		goto out;
649 	}
650 
651 	/* Prepare AuthorizedKeysCommand */
652 	if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash,
653 	    SSH_FP_DEFAULT)) == NULL) {
654 		error_f("sshkey_fingerprint failed");
655 		goto out;
656 	}
657 	if ((r = sshkey_to_base64(key, &keytext)) != 0) {
658 		error_fr(r, "sshkey_to_base64 failed");
659 		goto out;
660 	}
661 
662 	/* Turn the command into an argument vector */
663 	if (argv_split(options.authorized_keys_command, &ac, &av, 0) != 0) {
664 		error("AuthorizedKeysCommand \"%s\" contains invalid quotes",
665 		    options.authorized_keys_command);
666 		goto out;
667 	}
668 	if (ac == 0) {
669 		error("AuthorizedKeysCommand \"%s\" yielded no arguments",
670 		    options.authorized_keys_command);
671 		goto out;
672 	}
673 	snprintf(uidstr, sizeof(uidstr), "%llu",
674 	    (unsigned long long)user_pw->pw_uid);
675 	for (i = 1; i < ac; i++) {
676 		tmp = percent_expand(av[i],
677 		    "C", conn_id,
678 		    "D", rdomain,
679 		    "U", uidstr,
680 		    "u", user_pw->pw_name,
681 		    "h", user_pw->pw_dir,
682 		    "t", sshkey_ssh_name(key),
683 		    "f", key_fp,
684 		    "k", keytext,
685 		    (char *)NULL);
686 		if (tmp == NULL)
687 			fatal_f("percent_expand failed");
688 		free(av[i]);
689 		av[i] = tmp;
690 	}
691 	/* Prepare a printable command for logs, etc. */
692 	command = argv_assemble(ac, av);
693 
694 	/*
695 	 * If AuthorizedKeysCommand was run without arguments
696 	 * then fall back to the old behaviour of passing the
697 	 * target username as a single argument.
698 	 */
699 	if (ac == 1) {
700 		av = xreallocarray(av, ac + 2, sizeof(*av));
701 		av[1] = xstrdup(user_pw->pw_name);
702 		av[2] = NULL;
703 		/* Fix up command too, since it is used in log messages */
704 		free(command);
705 		xasprintf(&command, "%s %s", av[0], av[1]);
706 	}
707 
708 	if ((pid = subprocess("AuthorizedKeysCommand", command,
709 	    ac, av, &f,
710 	    SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
711 	    runas_pw, temporarily_use_uid, restore_uid)) == 0)
712 		goto out;
713 
714 	uid_swapped = 1;
715 	temporarily_use_uid(runas_pw);
716 
717 	ok = auth_check_authkeys_file(user_pw, f,
718 	    options.authorized_keys_command, key, remote_ip,
719 	    remote_host, authoptsp);
720 
721 	fclose(f);
722 	f = NULL;
723 
724 	if (exited_cleanly(pid, "AuthorizedKeysCommand", command, 0) != 0)
725 		goto out;
726 
727 	/* Read completed successfully */
728 	found_key = ok;
729  out:
730 	if (f != NULL)
731 		fclose(f);
732 	ssh_signal(SIGCHLD, osigchld);
733 	for (i = 0; i < ac; i++)
734 		free(av[i]);
735 	free(av);
736 	if (uid_swapped)
737 		restore_uid();
738 	free(command);
739 	free(username);
740 	free(key_fp);
741 	free(keytext);
742 	return found_key;
743 }
744 
745 /*
746  * Check whether key authenticates and authorises the user.
747  */
748 int
749 user_key_allowed(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
750     int auth_attempt, struct sshauthopt **authoptsp)
751 {
752 	u_int success = 0, i;
753 	char *file, *conn_id;
754 	struct sshauthopt *opts = NULL;
755 	const char *rdomain, *remote_ip, *remote_host;
756 
757 	if (authoptsp != NULL)
758 		*authoptsp = NULL;
759 
760 	if (auth_key_is_revoked(key))
761 		return 0;
762 	if (sshkey_is_cert(key) &&
763 	    auth_key_is_revoked(key->cert->signature_key))
764 		return 0;
765 
766 	if ((rdomain = ssh_packet_rdomain_in(ssh)) == NULL)
767 		rdomain = "";
768 	remote_ip = ssh_remote_ipaddr(ssh);
769 	remote_host = auth_get_canonical_hostname(ssh, options.use_dns);
770 	xasprintf(&conn_id, "%s %d %s %d",
771 	    ssh_local_ipaddr(ssh), ssh_local_port(ssh),
772 	    remote_ip, ssh_remote_port(ssh));
773 
774 	for (i = 0; !success && i < options.num_authkeys_files; i++) {
775 		if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
776 			continue;
777 		file = expand_authorized_keys(
778 		    options.authorized_keys_files[i], pw);
779 		success = user_key_allowed2(pw, key, file,
780 		    remote_ip, remote_host, &opts);
781 		free(file);
782 		if (!success) {
783 			sshauthopt_free(opts);
784 			opts = NULL;
785 		}
786 	}
787 	if (success)
788 		goto out;
789 
790 	if ((success = user_cert_trusted_ca(pw, key, remote_ip, remote_host,
791 	    conn_id, rdomain, &opts)) != 0)
792 		goto out;
793 	sshauthopt_free(opts);
794 	opts = NULL;
795 
796 	if ((success = user_key_command_allowed2(pw, key, remote_ip,
797 	    remote_host, conn_id, rdomain, &opts)) != 0)
798 		goto out;
799 	sshauthopt_free(opts);
800 	opts = NULL;
801 
802  out:
803 	free(conn_id);
804 	if (success && authoptsp != NULL) {
805 		*authoptsp = opts;
806 		opts = NULL;
807 	}
808 	sshauthopt_free(opts);
809 	return success;
810 }
811 
812 Authmethod method_pubkey = {
813 	"publickey",
814 	"publickey-hostbound-v00@openssh.com",
815 	userauth_pubkey,
816 	&options.pubkey_authentication
817 };
818