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