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