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