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