xref: /openbsd-src/usr.bin/ssh/auth2-pubkey.c (revision 4e1ee0786f11cc571bd0be17d38e46f635c719fc)
1 /* $OpenBSD: auth2-pubkey.c,v 1.110 2021/09/29 01:33:32 djm Exp $ */
2 /*
3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <paths.h>
34 #include <pwd.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 
74 static char *
75 format_key(const struct sshkey *key)
76 {
77 	char *ret, *fp = sshkey_fingerprint(key,
78 	    options.fingerprint_hash, SSH_FP_DEFAULT);
79 
80 	xasprintf(&ret, "%s %s", sshkey_type(key), fp);
81 	free(fp);
82 	return ret;
83 }
84 
85 static int
86 userauth_pubkey(struct ssh *ssh)
87 {
88 	Authctxt *authctxt = ssh->authctxt;
89 	struct passwd *pw = authctxt->pw;
90 	struct sshbuf *b = NULL;
91 	struct sshkey *key = NULL;
92 	char *pkalg = NULL, *userstyle = NULL, *key_s = NULL, *ca_s = NULL;
93 	u_char *pkblob = NULL, *sig = NULL, have_sig;
94 	size_t blen, slen;
95 	int r, pktype;
96 	int req_presence = 0, req_verify = 0, authenticated = 0;
97 	struct sshauthopt *authopts = NULL;
98 	struct sshkey_sig_details *sig_details = NULL;
99 
100 	if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 ||
101 	    (r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
102 	    (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0)
103 		fatal_fr(r, "parse packet");
104 
105 	if (log_level_get() >= SYSLOG_LEVEL_DEBUG2) {
106 		char *keystring;
107 		struct sshbuf *pkbuf;
108 
109 		if ((pkbuf = sshbuf_from(pkblob, blen)) == NULL)
110 			fatal_f("sshbuf_from failed");
111 		if ((keystring = sshbuf_dtob64_string(pkbuf, 0)) == NULL)
112 			fatal_f("sshbuf_dtob64 failed");
113 		debug2_f("%s user %s %s public key %s %s",
114 		    authctxt->valid ? "valid" : "invalid", authctxt->user,
115 		    have_sig ? "attempting" : "querying", pkalg, keystring);
116 		sshbuf_free(pkbuf);
117 		free(keystring);
118 	}
119 
120 	pktype = sshkey_type_from_name(pkalg);
121 	if (pktype == KEY_UNSPEC) {
122 		/* this is perfectly legal */
123 		verbose_f("unsupported public key algorithm: %s", pkalg);
124 		goto done;
125 	}
126 	if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
127 		error_fr(r, "parse key");
128 		goto done;
129 	}
130 	if (key == NULL) {
131 		error_f("cannot decode key: %s", pkalg);
132 		goto done;
133 	}
134 	if (key->type != pktype) {
135 		error_f("type mismatch for decoded key "
136 		    "(received %d, expected %d)", key->type, pktype);
137 		goto done;
138 	}
139 	if (sshkey_type_plain(key->type) == KEY_RSA &&
140 	    (ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
141 		logit("Refusing RSA key because client uses unsafe "
142 		    "signature scheme");
143 		goto done;
144 	}
145 	if (auth2_key_already_used(authctxt, key)) {
146 		logit("refusing previously-used %s key", sshkey_type(key));
147 		goto done;
148 	}
149 	if (match_pattern_list(pkalg, options.pubkey_accepted_algos, 0) != 1) {
150 		logit_f("key type %s not in PubkeyAcceptedAlgorithms",
151 		    sshkey_ssh_name(key));
152 		goto done;
153 	}
154 	if ((r = sshkey_check_cert_sigtype(key,
155 	    options.ca_sign_algorithms)) != 0) {
156 		logit_fr(r, "certificate signature algorithm %s",
157 		    (key->cert == NULL || key->cert->signature_type == NULL) ?
158 		    "(null)" : key->cert->signature_type);
159 		goto done;
160 	}
161 	key_s = format_key(key);
162 	if (sshkey_is_cert(key))
163 		ca_s = format_key(key->cert->signature_key);
164 
165 	if (have_sig) {
166 		debug3_f("have %s signature for %s%s%s", pkalg, key_s,
167 		    ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
168 		if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 ||
169 		    (r = sshpkt_get_end(ssh)) != 0)
170 			fatal_fr(r, "parse signature packet");
171 		if ((b = sshbuf_new()) == NULL)
172 			fatal_f("sshbuf_new failed");
173 		if (ssh->compat & SSH_OLD_SESSIONID) {
174 			if ((r = sshbuf_putb(b, ssh->kex->session_id)) != 0)
175 				fatal_fr(r, "put old session id");
176 		} else {
177 			if ((r = sshbuf_put_stringb(b,
178 			    ssh->kex->session_id)) != 0)
179 				fatal_fr(r, "put session id");
180 		}
181 		if (!authctxt->valid || authctxt->user == NULL) {
182 			debug2_f("disabled because of invalid user");
183 			goto done;
184 		}
185 		/* reconstruct packet */
186 		xasprintf(&userstyle, "%s%s%s", authctxt->user,
187 		    authctxt->style ? ":" : "",
188 		    authctxt->style ? authctxt->style : "");
189 		if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
190 		    (r = sshbuf_put_cstring(b, userstyle)) != 0 ||
191 		    (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
192 		    (r = sshbuf_put_cstring(b, "publickey")) != 0 ||
193 		    (r = sshbuf_put_u8(b, have_sig)) != 0 ||
194 		    (r = sshbuf_put_cstring(b, pkalg)) != 0 ||
195 		    (r = sshbuf_put_string(b, pkblob, blen)) != 0)
196 			fatal_fr(r, "reconstruct packet");
197 #ifdef DEBUG_PK
198 		sshbuf_dump(b, stderr);
199 #endif
200 		/* test for correct signature */
201 		authenticated = 0;
202 		if (PRIVSEP(user_key_allowed(ssh, pw, key, 1, &authopts)) &&
203 		    PRIVSEP(sshkey_verify(key, sig, slen,
204 		    sshbuf_ptr(b), sshbuf_len(b),
205 		    (ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL,
206 		    ssh->compat, &sig_details)) == 0) {
207 			authenticated = 1;
208 		}
209 		if (authenticated == 1 && sig_details != NULL) {
210 			auth2_record_info(authctxt, "signature count = %u",
211 			    sig_details->sk_counter);
212 			debug_f("sk_counter = %u, sk_flags = 0x%02x",
213 			    sig_details->sk_counter, sig_details->sk_flags);
214 			req_presence = (options.pubkey_auth_options &
215 			    PUBKEYAUTH_TOUCH_REQUIRED) ||
216 			    !authopts->no_require_user_presence;
217 			if (req_presence && (sig_details->sk_flags &
218 			    SSH_SK_USER_PRESENCE_REQD) == 0) {
219 				error("public key %s signature for %s%s from "
220 				    "%.128s port %d rejected: user presence "
221 				    "(authenticator touch) requirement "
222 				    "not met ", key_s,
223 				    authctxt->valid ? "" : "invalid user ",
224 				    authctxt->user, ssh_remote_ipaddr(ssh),
225 				    ssh_remote_port(ssh));
226 				authenticated = 0;
227 				goto done;
228 			}
229 			req_verify = (options.pubkey_auth_options &
230 			    PUBKEYAUTH_VERIFY_REQUIRED) ||
231 			    authopts->require_verify;
232 			if (req_verify && (sig_details->sk_flags &
233 			    SSH_SK_USER_VERIFICATION_REQD) == 0) {
234 				error("public key %s signature for %s%s from "
235 				    "%.128s port %d rejected: user "
236 				    "verification requirement not met ", key_s,
237 				    authctxt->valid ? "" : "invalid user ",
238 				    authctxt->user, ssh_remote_ipaddr(ssh),
239 				    ssh_remote_port(ssh));
240 				authenticated = 0;
241 				goto done;
242 			}
243 		}
244 		auth2_record_key(authctxt, authenticated, key);
245 	} else {
246 		debug_f("test pkalg %s pkblob %s%s%s", pkalg, key_s,
247 		    ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
248 
249 		if ((r = sshpkt_get_end(ssh)) != 0)
250 			fatal_fr(r, "parse packet");
251 
252 		if (!authctxt->valid || authctxt->user == NULL) {
253 			debug2_f("disabled because of invalid user");
254 			goto done;
255 		}
256 		/* XXX fake reply and always send PK_OK ? */
257 		/*
258 		 * XXX this allows testing whether a user is allowed
259 		 * to login: if you happen to have a valid pubkey this
260 		 * message is sent. the message is NEVER sent at all
261 		 * if a user is not allowed to login. is this an
262 		 * issue? -markus
263 		 */
264 		if (PRIVSEP(user_key_allowed(ssh, pw, key, 0, NULL))) {
265 			if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK))
266 			    != 0 ||
267 			    (r = sshpkt_put_cstring(ssh, pkalg)) != 0 ||
268 			    (r = sshpkt_put_string(ssh, pkblob, blen)) != 0 ||
269 			    (r = sshpkt_send(ssh)) != 0 ||
270 			    (r = ssh_packet_write_wait(ssh)) != 0)
271 				fatal_fr(r, "send packet");
272 			authctxt->postponed = 1;
273 		}
274 	}
275 done:
276 	if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) {
277 		debug_f("key options inconsistent with existing");
278 		authenticated = 0;
279 	}
280 	debug2_f("authenticated %d pkalg %s", authenticated, pkalg);
281 
282 	sshbuf_free(b);
283 	sshauthopt_free(authopts);
284 	sshkey_free(key);
285 	free(userstyle);
286 	free(pkalg);
287 	free(pkblob);
288 	free(key_s);
289 	free(ca_s);
290 	free(sig);
291 	sshkey_sig_details_free(sig_details);
292 	return authenticated;
293 }
294 
295 static int
296 match_principals_option(const char *principal_list, struct sshkey_cert *cert)
297 {
298 	char *result;
299 	u_int i;
300 
301 	/* XXX percent_expand() sequences for authorized_principals? */
302 
303 	for (i = 0; i < cert->nprincipals; i++) {
304 		if ((result = match_list(cert->principals[i],
305 		    principal_list, NULL)) != NULL) {
306 			debug3("matched principal from key options \"%.100s\"",
307 			    result);
308 			free(result);
309 			return 1;
310 		}
311 	}
312 	return 0;
313 }
314 
315 /*
316  * Process a single authorized_principals format line. Returns 0 and sets
317  * authoptsp is principal is authorised, -1 otherwise. "loc" is used as a
318  * log preamble for file/line information.
319  */
320 static int
321 check_principals_line(struct ssh *ssh, char *cp, const struct sshkey_cert *cert,
322     const char *loc, struct sshauthopt **authoptsp)
323 {
324 	u_int i, found = 0;
325 	char *ep, *line_opts;
326 	const char *reason = NULL;
327 	struct sshauthopt *opts = NULL;
328 
329 	if (authoptsp != NULL)
330 		*authoptsp = NULL;
331 
332 	/* Trim trailing whitespace. */
333 	ep = cp + strlen(cp) - 1;
334 	while (ep > cp && (*ep == '\n' || *ep == ' ' || *ep == '\t'))
335 		*ep-- = '\0';
336 
337 	/*
338 	 * If the line has internal whitespace then assume it has
339 	 * key options.
340 	 */
341 	line_opts = NULL;
342 	if ((ep = strrchr(cp, ' ')) != NULL ||
343 	    (ep = strrchr(cp, '\t')) != NULL) {
344 		for (; *ep == ' ' || *ep == '\t'; ep++)
345 			;
346 		line_opts = cp;
347 		cp = ep;
348 	}
349 	if ((opts = sshauthopt_parse(line_opts, &reason)) == NULL) {
350 		debug("%s: bad principals options: %s", loc, reason);
351 		auth_debug_add("%s: bad principals options: %s", loc, reason);
352 		return -1;
353 	}
354 	/* Check principals in cert against those on line */
355 	for (i = 0; i < cert->nprincipals; i++) {
356 		if (strcmp(cp, cert->principals[i]) != 0)
357 			continue;
358 		debug3("%s: matched principal \"%.100s\"",
359 		    loc, cert->principals[i]);
360 		found = 1;
361 	}
362 	if (found && authoptsp != NULL) {
363 		*authoptsp = opts;
364 		opts = NULL;
365 	}
366 	sshauthopt_free(opts);
367 	return found ? 0 : -1;
368 }
369 
370 static int
371 process_principals(struct ssh *ssh, FILE *f, const char *file,
372     const struct sshkey_cert *cert, struct sshauthopt **authoptsp)
373 {
374 	char loc[256], *line = NULL, *cp, *ep;
375 	size_t linesize = 0;
376 	u_long linenum = 0, nonblank = 0;
377 	u_int found_principal = 0;
378 
379 	if (authoptsp != NULL)
380 		*authoptsp = NULL;
381 
382 	while (getline(&line, &linesize, f) != -1) {
383 		linenum++;
384 		/* Always consume entire input */
385 		if (found_principal)
386 			continue;
387 
388 		/* Skip leading whitespace. */
389 		for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
390 			;
391 		/* Skip blank and comment lines. */
392 		if ((ep = strchr(cp, '#')) != NULL)
393 			*ep = '\0';
394 		if (!*cp || *cp == '\n')
395 			continue;
396 
397 		nonblank++;
398 		snprintf(loc, sizeof(loc), "%.200s:%lu", file, linenum);
399 		if (check_principals_line(ssh, cp, cert, loc, authoptsp) == 0)
400 			found_principal = 1;
401 	}
402 	debug2_f("%s: processed %lu/%lu lines", file, nonblank, linenum);
403 	free(line);
404 	return found_principal;
405 }
406 
407 /* XXX remove pw args here and elsewhere once ssh->authctxt is guaranteed */
408 
409 static int
410 match_principals_file(struct ssh *ssh, struct passwd *pw, char *file,
411     struct sshkey_cert *cert, struct sshauthopt **authoptsp)
412 {
413 	FILE *f;
414 	int success;
415 
416 	if (authoptsp != NULL)
417 		*authoptsp = NULL;
418 
419 	temporarily_use_uid(pw);
420 	debug("trying authorized principals file %s", file);
421 	if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) {
422 		restore_uid();
423 		return 0;
424 	}
425 	success = process_principals(ssh, f, file, cert, authoptsp);
426 	fclose(f);
427 	restore_uid();
428 	return success;
429 }
430 
431 /*
432  * Checks whether principal is allowed in output of command.
433  * returns 1 if the principal is allowed or 0 otherwise.
434  */
435 static int
436 match_principals_command(struct ssh *ssh, struct passwd *user_pw,
437     const struct sshkey *key, struct sshauthopt **authoptsp)
438 {
439 	struct passwd *runas_pw = NULL;
440 	const struct sshkey_cert *cert = key->cert;
441 	FILE *f = NULL;
442 	int r, ok, found_principal = 0;
443 	int i, ac = 0, uid_swapped = 0;
444 	pid_t pid;
445 	char *tmp, *username = NULL, *command = NULL, **av = NULL;
446 	char *ca_fp = NULL, *key_fp = NULL, *catext = NULL, *keytext = NULL;
447 	char serial_s[32], uidstr[32];
448 	void (*osigchld)(int);
449 
450 	if (authoptsp != NULL)
451 		*authoptsp = NULL;
452 	if (options.authorized_principals_command == NULL)
453 		return 0;
454 	if (options.authorized_principals_command_user == NULL) {
455 		error("No user for AuthorizedPrincipalsCommand specified, "
456 		    "skipping");
457 		return 0;
458 	}
459 
460 	/*
461 	 * NB. all returns later this function should go via "out" to
462 	 * ensure the original SIGCHLD handler is restored properly.
463 	 */
464 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
465 
466 	/* Prepare and verify the user for the command */
467 	username = percent_expand(options.authorized_principals_command_user,
468 	    "u", user_pw->pw_name, (char *)NULL);
469 	runas_pw = getpwnam(username);
470 	if (runas_pw == NULL) {
471 		error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s",
472 		    username, strerror(errno));
473 		goto out;
474 	}
475 
476 	/* Turn the command into an argument vector */
477 	if (argv_split(options.authorized_principals_command,
478 	    &ac, &av, 0) != 0) {
479 		error("AuthorizedPrincipalsCommand \"%s\" contains "
480 		    "invalid quotes", options.authorized_principals_command);
481 		goto out;
482 	}
483 	if (ac == 0) {
484 		error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments",
485 		    options.authorized_principals_command);
486 		goto out;
487 	}
488 	if ((ca_fp = sshkey_fingerprint(cert->signature_key,
489 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
490 		error_f("sshkey_fingerprint failed");
491 		goto out;
492 	}
493 	if ((key_fp = sshkey_fingerprint(key,
494 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
495 		error_f("sshkey_fingerprint failed");
496 		goto out;
497 	}
498 	if ((r = sshkey_to_base64(cert->signature_key, &catext)) != 0) {
499 		error_fr(r, "sshkey_to_base64 failed");
500 		goto out;
501 	}
502 	if ((r = sshkey_to_base64(key, &keytext)) != 0) {
503 		error_fr(r, "sshkey_to_base64 failed");
504 		goto out;
505 	}
506 	snprintf(serial_s, sizeof(serial_s), "%llu",
507 	    (unsigned long long)cert->serial);
508 	snprintf(uidstr, sizeof(uidstr), "%llu",
509 	    (unsigned long long)user_pw->pw_uid);
510 	for (i = 1; i < ac; i++) {
511 		tmp = percent_expand(av[i],
512 		    "U", uidstr,
513 		    "u", user_pw->pw_name,
514 		    "h", user_pw->pw_dir,
515 		    "t", sshkey_ssh_name(key),
516 		    "T", sshkey_ssh_name(cert->signature_key),
517 		    "f", key_fp,
518 		    "F", ca_fp,
519 		    "k", keytext,
520 		    "K", catext,
521 		    "i", cert->key_id,
522 		    "s", serial_s,
523 		    (char *)NULL);
524 		if (tmp == NULL)
525 			fatal_f("percent_expand failed");
526 		free(av[i]);
527 		av[i] = tmp;
528 	}
529 	/* Prepare a printable command for logs, etc. */
530 	command = argv_assemble(ac, av);
531 
532 	if ((pid = subprocess("AuthorizedPrincipalsCommand", command,
533 	    ac, av, &f,
534 	    SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
535 	    runas_pw, temporarily_use_uid, restore_uid)) == 0)
536 		goto out;
537 
538 	uid_swapped = 1;
539 	temporarily_use_uid(runas_pw);
540 
541 	ok = process_principals(ssh, f, "(command)", cert, authoptsp);
542 
543 	fclose(f);
544 	f = NULL;
545 
546 	if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command, 0) != 0)
547 		goto out;
548 
549 	/* Read completed successfully */
550 	found_principal = ok;
551  out:
552 	if (f != NULL)
553 		fclose(f);
554 	ssh_signal(SIGCHLD, osigchld);
555 	for (i = 0; i < ac; i++)
556 		free(av[i]);
557 	free(av);
558 	if (uid_swapped)
559 		restore_uid();
560 	free(command);
561 	free(username);
562 	free(ca_fp);
563 	free(key_fp);
564 	free(catext);
565 	free(keytext);
566 	return found_principal;
567 }
568 
569 /*
570  * Check a single line of an authorized_keys-format file. Returns 0 if key
571  * matches, -1 otherwise. Will return key/cert options via *authoptsp
572  * on success. "loc" is used as file/line location in log messages.
573  */
574 static int
575 check_authkey_line(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
576     char *cp, const char *loc, struct sshauthopt **authoptsp)
577 {
578 	int want_keytype = sshkey_is_cert(key) ? KEY_UNSPEC : key->type;
579 	struct sshkey *found = NULL;
580 	struct sshauthopt *keyopts = NULL, *certopts = NULL, *finalopts = NULL;
581 	char *key_options = NULL, *fp = NULL;
582 	const char *reason = NULL;
583 	int ret = -1;
584 
585 	if (authoptsp != NULL)
586 		*authoptsp = NULL;
587 
588 	if ((found = sshkey_new(want_keytype)) == NULL) {
589 		debug3_f("keytype %d failed", want_keytype);
590 		goto out;
591 	}
592 
593 	/* XXX djm: peek at key type in line and skip if unwanted */
594 
595 	if (sshkey_read(found, &cp) != 0) {
596 		/* no key?  check for options */
597 		debug2("%s: check options: '%s'", loc, cp);
598 		key_options = cp;
599 		if (sshkey_advance_past_options(&cp) != 0) {
600 			reason = "invalid key option string";
601 			goto fail_reason;
602 		}
603 		skip_space(&cp);
604 		if (sshkey_read(found, &cp) != 0) {
605 			/* still no key?  advance to next line*/
606 			debug2("%s: advance: '%s'", loc, cp);
607 			goto out;
608 		}
609 	}
610 	/* Parse key options now; we need to know if this is a CA key */
611 	if ((keyopts = sshauthopt_parse(key_options, &reason)) == NULL) {
612 		debug("%s: bad key options: %s", loc, reason);
613 		auth_debug_add("%s: bad key options: %s", loc, reason);
614 		goto out;
615 	}
616 	/* Ignore keys that don't match or incorrectly marked as CAs */
617 	if (sshkey_is_cert(key)) {
618 		/* Certificate; check signature key against CA */
619 		if (!sshkey_equal(found, key->cert->signature_key) ||
620 		    !keyopts->cert_authority)
621 			goto out;
622 	} else {
623 		/* Plain key: check it against key found in file */
624 		if (!sshkey_equal(found, key) || keyopts->cert_authority)
625 			goto out;
626 	}
627 
628 	/* We have a candidate key, perform authorisation checks */
629 	if ((fp = sshkey_fingerprint(found,
630 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
631 		fatal_f("fingerprint failed");
632 
633 	debug("%s: matching %s found: %s %s", loc,
634 	    sshkey_is_cert(key) ? "CA" : "key", sshkey_type(found), fp);
635 
636 	if (auth_authorise_keyopts(ssh, pw, keyopts,
637 	    sshkey_is_cert(key), loc) != 0) {
638 		reason = "Refused by key options";
639 		goto fail_reason;
640 	}
641 	/* That's all we need for plain keys. */
642 	if (!sshkey_is_cert(key)) {
643 		verbose("Accepted key %s %s found at %s",
644 		    sshkey_type(found), fp, loc);
645 		finalopts = keyopts;
646 		keyopts = NULL;
647 		goto success;
648 	}
649 
650 	/*
651 	 * Additional authorisation for certificates.
652 	 */
653 
654 	/* Parse and check options present in certificate */
655 	if ((certopts = sshauthopt_from_cert(key)) == NULL) {
656 		reason = "Invalid certificate options";
657 		goto fail_reason;
658 	}
659 	if (auth_authorise_keyopts(ssh, pw, certopts, 0, loc) != 0) {
660 		reason = "Refused by certificate options";
661 		goto fail_reason;
662 	}
663 	if ((finalopts = sshauthopt_merge(keyopts, certopts, &reason)) == NULL)
664 		goto fail_reason;
665 
666 	/*
667 	 * If the user has specified a list of principals as
668 	 * a key option, then prefer that list to matching
669 	 * their username in the certificate principals list.
670 	 */
671 	if (keyopts->cert_principals != NULL &&
672 	    !match_principals_option(keyopts->cert_principals, key->cert)) {
673 		reason = "Certificate does not contain an authorized principal";
674 		goto fail_reason;
675 	}
676 	if (sshkey_cert_check_authority_now(key, 0, 0, 0,
677 	    keyopts->cert_principals == NULL ? pw->pw_name : NULL,
678 	    &reason) != 0)
679 		goto fail_reason;
680 
681 	verbose("Accepted certificate ID \"%s\" (serial %llu) "
682 	    "signed by CA %s %s found at %s",
683 	    key->cert->key_id,
684 	    (unsigned long long)key->cert->serial,
685 	    sshkey_type(found), fp, loc);
686 
687  success:
688 	if (finalopts == NULL)
689 		fatal_f("internal error: missing options");
690 	if (authoptsp != NULL) {
691 		*authoptsp = finalopts;
692 		finalopts = NULL;
693 	}
694 	/* success */
695 	ret = 0;
696 	goto out;
697 
698  fail_reason:
699 	error("%s", reason);
700 	auth_debug_add("%s", reason);
701  out:
702 	free(fp);
703 	sshauthopt_free(keyopts);
704 	sshauthopt_free(certopts);
705 	sshauthopt_free(finalopts);
706 	sshkey_free(found);
707 	return ret;
708 }
709 
710 /*
711  * Checks whether key is allowed in authorized_keys-format file,
712  * returns 1 if the key is allowed or 0 otherwise.
713  */
714 static int
715 check_authkeys_file(struct ssh *ssh, struct passwd *pw, FILE *f,
716     char *file, struct sshkey *key, struct sshauthopt **authoptsp)
717 {
718 	char *cp, *line = NULL, loc[256];
719 	size_t linesize = 0;
720 	int found_key = 0;
721 	u_long linenum = 0, nonblank = 0;
722 
723 	if (authoptsp != NULL)
724 		*authoptsp = NULL;
725 
726 	while (getline(&line, &linesize, f) != -1) {
727 		linenum++;
728 		/* Always consume entire file */
729 		if (found_key)
730 			continue;
731 
732 		/* Skip leading whitespace, empty and comment lines. */
733 		cp = line;
734 		skip_space(&cp);
735 		if (!*cp || *cp == '\n' || *cp == '#')
736 			continue;
737 
738 		nonblank++;
739 		snprintf(loc, sizeof(loc), "%.200s:%lu", file, linenum);
740 		if (check_authkey_line(ssh, pw, key, cp, loc, authoptsp) == 0)
741 			found_key = 1;
742 	}
743 	free(line);
744 	debug2_f("%s: processed %lu/%lu lines", file, nonblank, linenum);
745 	return found_key;
746 }
747 
748 /* Authenticate a certificate key against TrustedUserCAKeys */
749 static int
750 user_cert_trusted_ca(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
751     struct sshauthopt **authoptsp)
752 {
753 	char *ca_fp, *principals_file = NULL;
754 	const char *reason;
755 	struct sshauthopt *principals_opts = NULL, *cert_opts = NULL;
756 	struct sshauthopt *final_opts = NULL;
757 	int r, ret = 0, found_principal = 0, use_authorized_principals;
758 
759 	if (authoptsp != NULL)
760 		*authoptsp = NULL;
761 
762 	if (!sshkey_is_cert(key) || options.trusted_user_ca_keys == NULL)
763 		return 0;
764 
765 	if ((ca_fp = sshkey_fingerprint(key->cert->signature_key,
766 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
767 		return 0;
768 
769 	if ((r = sshkey_in_file(key->cert->signature_key,
770 	    options.trusted_user_ca_keys, 1, 0)) != 0) {
771 		debug2_fr(r, "CA %s %s is not listed in %s",
772 		    sshkey_type(key->cert->signature_key), ca_fp,
773 		    options.trusted_user_ca_keys);
774 		goto out;
775 	}
776 	/*
777 	 * If AuthorizedPrincipals is in use, then compare the certificate
778 	 * principals against the names in that file rather than matching
779 	 * against the username.
780 	 */
781 	if ((principals_file = authorized_principals_file(pw)) != NULL) {
782 		if (match_principals_file(ssh, pw, principals_file,
783 		    key->cert, &principals_opts))
784 			found_principal = 1;
785 	}
786 	/* Try querying command if specified */
787 	if (!found_principal && match_principals_command(ssh, pw, key,
788 	    &principals_opts))
789 		found_principal = 1;
790 	/* If principals file or command is specified, then require a match */
791 	use_authorized_principals = principals_file != NULL ||
792 	    options.authorized_principals_command != NULL;
793 	if (!found_principal && use_authorized_principals) {
794 		reason = "Certificate does not contain an authorized principal";
795 		goto fail_reason;
796 	}
797 	if (use_authorized_principals && principals_opts == NULL)
798 		fatal_f("internal error: missing principals_opts");
799 	if (sshkey_cert_check_authority_now(key, 0, 1, 0,
800 	    use_authorized_principals ? NULL : pw->pw_name, &reason) != 0)
801 		goto fail_reason;
802 
803 	/* Check authority from options in key and from principals file/cmd */
804 	if ((cert_opts = sshauthopt_from_cert(key)) == NULL) {
805 		reason = "Invalid certificate options";
806 		goto fail_reason;
807 	}
808 	if (auth_authorise_keyopts(ssh, pw, cert_opts, 0, "cert") != 0) {
809 		reason = "Refused by certificate options";
810 		goto fail_reason;
811 	}
812 	if (principals_opts == NULL) {
813 		final_opts = cert_opts;
814 		cert_opts = NULL;
815 	} else {
816 		if (auth_authorise_keyopts(ssh, pw, principals_opts, 0,
817 		    "principals") != 0) {
818 			reason = "Refused by certificate principals options";
819 			goto fail_reason;
820 		}
821 		if ((final_opts = sshauthopt_merge(principals_opts,
822 		    cert_opts, &reason)) == NULL) {
823  fail_reason:
824 			error("%s", reason);
825 			auth_debug_add("%s", reason);
826 			goto out;
827 		}
828 	}
829 
830 	/* Success */
831 	verbose("Accepted certificate ID \"%s\" (serial %llu) signed by "
832 	    "%s CA %s via %s", key->cert->key_id,
833 	    (unsigned long long)key->cert->serial,
834 	    sshkey_type(key->cert->signature_key), ca_fp,
835 	    options.trusted_user_ca_keys);
836 	if (authoptsp != NULL) {
837 		*authoptsp = final_opts;
838 		final_opts = NULL;
839 	}
840 	ret = 1;
841  out:
842 	sshauthopt_free(principals_opts);
843 	sshauthopt_free(cert_opts);
844 	sshauthopt_free(final_opts);
845 	free(principals_file);
846 	free(ca_fp);
847 	return ret;
848 }
849 
850 /*
851  * Checks whether key is allowed in file.
852  * returns 1 if the key is allowed or 0 otherwise.
853  */
854 static int
855 user_key_allowed2(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
856     char *file, struct sshauthopt **authoptsp)
857 {
858 	FILE *f;
859 	int found_key = 0;
860 
861 	if (authoptsp != NULL)
862 		*authoptsp = NULL;
863 
864 	/* Temporarily use the user's uid. */
865 	temporarily_use_uid(pw);
866 
867 	debug("trying public key file %s", file);
868 	if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) {
869 		found_key = check_authkeys_file(ssh, pw, f, file,
870 		    key, authoptsp);
871 		fclose(f);
872 	}
873 
874 	restore_uid();
875 	return found_key;
876 }
877 
878 /*
879  * Checks whether key is allowed in output of command.
880  * returns 1 if the key is allowed or 0 otherwise.
881  */
882 static int
883 user_key_command_allowed2(struct ssh *ssh, struct passwd *user_pw,
884     struct sshkey *key, struct sshauthopt **authoptsp)
885 {
886 	struct passwd *runas_pw = NULL;
887 	FILE *f = NULL;
888 	int r, ok, found_key = 0;
889 	int i, uid_swapped = 0, ac = 0;
890 	pid_t pid;
891 	char *username = NULL, *key_fp = NULL, *keytext = NULL;
892 	char uidstr[32], *tmp, *command = NULL, **av = NULL;
893 	void (*osigchld)(int);
894 
895 	if (authoptsp != NULL)
896 		*authoptsp = NULL;
897 	if (options.authorized_keys_command == NULL)
898 		return 0;
899 	if (options.authorized_keys_command_user == NULL) {
900 		error("No user for AuthorizedKeysCommand specified, skipping");
901 		return 0;
902 	}
903 
904 	/*
905 	 * NB. all returns later this function should go via "out" to
906 	 * ensure the original SIGCHLD handler is restored properly.
907 	 */
908 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
909 
910 	/* Prepare and verify the user for the command */
911 	username = percent_expand(options.authorized_keys_command_user,
912 	    "u", user_pw->pw_name, (char *)NULL);
913 	runas_pw = getpwnam(username);
914 	if (runas_pw == NULL) {
915 		error("AuthorizedKeysCommandUser \"%s\" not found: %s",
916 		    username, strerror(errno));
917 		goto out;
918 	}
919 
920 	/* Prepare AuthorizedKeysCommand */
921 	if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash,
922 	    SSH_FP_DEFAULT)) == NULL) {
923 		error_f("sshkey_fingerprint failed");
924 		goto out;
925 	}
926 	if ((r = sshkey_to_base64(key, &keytext)) != 0) {
927 		error_fr(r, "sshkey_to_base64 failed");
928 		goto out;
929 	}
930 
931 	/* Turn the command into an argument vector */
932 	if (argv_split(options.authorized_keys_command, &ac, &av, 0) != 0) {
933 		error("AuthorizedKeysCommand \"%s\" contains invalid quotes",
934 		    options.authorized_keys_command);
935 		goto out;
936 	}
937 	if (ac == 0) {
938 		error("AuthorizedKeysCommand \"%s\" yielded no arguments",
939 		    options.authorized_keys_command);
940 		goto out;
941 	}
942 	snprintf(uidstr, sizeof(uidstr), "%llu",
943 	    (unsigned long long)user_pw->pw_uid);
944 	for (i = 1; i < ac; i++) {
945 		tmp = percent_expand(av[i],
946 		    "U", uidstr,
947 		    "u", user_pw->pw_name,
948 		    "h", user_pw->pw_dir,
949 		    "t", sshkey_ssh_name(key),
950 		    "f", key_fp,
951 		    "k", keytext,
952 		    (char *)NULL);
953 		if (tmp == NULL)
954 			fatal_f("percent_expand failed");
955 		free(av[i]);
956 		av[i] = tmp;
957 	}
958 	/* Prepare a printable command for logs, etc. */
959 	command = argv_assemble(ac, av);
960 
961 	/*
962 	 * If AuthorizedKeysCommand was run without arguments
963 	 * then fall back to the old behaviour of passing the
964 	 * target username as a single argument.
965 	 */
966 	if (ac == 1) {
967 		av = xreallocarray(av, ac + 2, sizeof(*av));
968 		av[1] = xstrdup(user_pw->pw_name);
969 		av[2] = NULL;
970 		/* Fix up command too, since it is used in log messages */
971 		free(command);
972 		xasprintf(&command, "%s %s", av[0], av[1]);
973 	}
974 
975 	if ((pid = subprocess("AuthorizedKeysCommand", command,
976 	    ac, av, &f,
977 	    SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
978 	    runas_pw, temporarily_use_uid, restore_uid)) == 0)
979 		goto out;
980 
981 	uid_swapped = 1;
982 	temporarily_use_uid(runas_pw);
983 
984 	ok = check_authkeys_file(ssh, user_pw, f,
985 	    options.authorized_keys_command, key, authoptsp);
986 
987 	fclose(f);
988 	f = NULL;
989 
990 	if (exited_cleanly(pid, "AuthorizedKeysCommand", command, 0) != 0)
991 		goto out;
992 
993 	/* Read completed successfully */
994 	found_key = ok;
995  out:
996 	if (f != NULL)
997 		fclose(f);
998 	ssh_signal(SIGCHLD, osigchld);
999 	for (i = 0; i < ac; i++)
1000 		free(av[i]);
1001 	free(av);
1002 	if (uid_swapped)
1003 		restore_uid();
1004 	free(command);
1005 	free(username);
1006 	free(key_fp);
1007 	free(keytext);
1008 	return found_key;
1009 }
1010 
1011 /*
1012  * Check whether key authenticates and authorises the user.
1013  */
1014 int
1015 user_key_allowed(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
1016     int auth_attempt, struct sshauthopt **authoptsp)
1017 {
1018 	u_int success = 0, i;
1019 	char *file;
1020 	struct sshauthopt *opts = NULL;
1021 
1022 	if (authoptsp != NULL)
1023 		*authoptsp = NULL;
1024 
1025 	if (auth_key_is_revoked(key))
1026 		return 0;
1027 	if (sshkey_is_cert(key) &&
1028 	    auth_key_is_revoked(key->cert->signature_key))
1029 		return 0;
1030 
1031 	for (i = 0; !success && i < options.num_authkeys_files; i++) {
1032 		if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
1033 			continue;
1034 		file = expand_authorized_keys(
1035 		    options.authorized_keys_files[i], pw);
1036 		success = user_key_allowed2(ssh, pw, key, file, &opts);
1037 		free(file);
1038 		if (!success) {
1039 			sshauthopt_free(opts);
1040 			opts = NULL;
1041 		}
1042 	}
1043 	if (success)
1044 		goto out;
1045 
1046 	if ((success = user_cert_trusted_ca(ssh, pw, key, &opts)) != 0)
1047 		goto out;
1048 	sshauthopt_free(opts);
1049 	opts = NULL;
1050 
1051 	if ((success = user_key_command_allowed2(ssh, pw, key, &opts)) != 0)
1052 		goto out;
1053 	sshauthopt_free(opts);
1054 	opts = NULL;
1055 
1056  out:
1057 	if (success && authoptsp != NULL) {
1058 		*authoptsp = opts;
1059 		opts = NULL;
1060 	}
1061 	sshauthopt_free(opts);
1062 	return success;
1063 }
1064 
1065 Authmethod method_pubkey = {
1066 	"publickey",
1067 	userauth_pubkey,
1068 	&options.pubkey_authentication
1069 };
1070