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