xref: /openssh-portable/auth2-pubkey.c (revision ee9c0da8)
1 /* $OpenBSD: auth2-pubkey.c,v 1.104 2021/01/22 02:44:58 dtucker 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 #include "includes.h"
27 
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 
31 #include <stdlib.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #ifdef HAVE_PATHS_H
35 # include <paths.h>
36 #endif
37 #include <pwd.h>
38 #include <signal.h>
39 #include <stdio.h>
40 #include <stdarg.h>
41 #include <string.h>
42 #include <time.h>
43 #include <unistd.h>
44 #include <limits.h>
45 
46 #include "xmalloc.h"
47 #include "ssh.h"
48 #include "ssh2.h"
49 #include "packet.h"
50 #include "sshbuf.h"
51 #include "log.h"
52 #include "misc.h"
53 #include "servconf.h"
54 #include "compat.h"
55 #include "sshkey.h"
56 #include "hostfile.h"
57 #include "auth.h"
58 #include "pathnames.h"
59 #include "uidswap.h"
60 #include "auth-options.h"
61 #include "canohost.h"
62 #ifdef GSSAPI
63 #include "ssh-gss.h"
64 #endif
65 #include "monitor_wrap.h"
66 #include "authfile.h"
67 #include "match.h"
68 #include "ssherr.h"
69 #include "channels.h" /* XXX for session.h */
70 #include "session.h" /* XXX for child_set_env(); refactor? */
71 #include "sk-api.h"
72 
73 /* import */
74 extern ServerOptions options;
75 extern u_char *session_id2;
76 extern u_int session_id2_len;
77 
78 static char *
79 format_key(const struct sshkey *key)
80 {
81 	char *ret, *fp = sshkey_fingerprint(key,
82 	    options.fingerprint_hash, SSH_FP_DEFAULT);
83 
84 	xasprintf(&ret, "%s %s", sshkey_type(key), fp);
85 	free(fp);
86 	return ret;
87 }
88 
89 static int
90 userauth_pubkey(struct ssh *ssh)
91 {
92 	Authctxt *authctxt = ssh->authctxt;
93 	struct passwd *pw = authctxt->pw;
94 	struct sshbuf *b = NULL;
95 	struct sshkey *key = NULL;
96 	char *pkalg = NULL, *userstyle = NULL, *key_s = NULL, *ca_s = NULL;
97 	u_char *pkblob = NULL, *sig = NULL, have_sig;
98 	size_t blen, slen;
99 	int r, pktype;
100 	int req_presence = 0, req_verify = 0, authenticated = 0;
101 	struct sshauthopt *authopts = NULL;
102 	struct sshkey_sig_details *sig_details = NULL;
103 
104 	if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 ||
105 	    (r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
106 	    (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0)
107 		fatal_fr(r, "parse packet");
108 
109 	if (log_level_get() >= SYSLOG_LEVEL_DEBUG2) {
110 		char *keystring;
111 		struct sshbuf *pkbuf;
112 
113 		if ((pkbuf = sshbuf_from(pkblob, blen)) == NULL)
114 			fatal_f("sshbuf_from failed");
115 		if ((keystring = sshbuf_dtob64_string(pkbuf, 0)) == NULL)
116 			fatal_f("sshbuf_dtob64 failed");
117 		debug2_f("%s user %s %s public key %s %s",
118 		    authctxt->valid ? "valid" : "invalid", authctxt->user,
119 		    have_sig ? "attempting" : "querying", pkalg, keystring);
120 		sshbuf_free(pkbuf);
121 		free(keystring);
122 	}
123 
124 	pktype = sshkey_type_from_name(pkalg);
125 	if (pktype == KEY_UNSPEC) {
126 		/* this is perfectly legal */
127 		verbose_f("unsupported public key algorithm: %s", pkalg);
128 		goto done;
129 	}
130 	if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
131 		error_fr(r, "parse key");
132 		goto done;
133 	}
134 	if (key == NULL) {
135 		error_f("cannot decode key: %s", pkalg);
136 		goto done;
137 	}
138 	if (key->type != pktype) {
139 		error_f("type mismatch for decoded key "
140 		    "(received %d, expected %d)", key->type, pktype);
141 		goto done;
142 	}
143 	if (sshkey_type_plain(key->type) == KEY_RSA &&
144 	    (ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
145 		logit("Refusing RSA key because client uses unsafe "
146 		    "signature scheme");
147 		goto done;
148 	}
149 	if (auth2_key_already_used(authctxt, key)) {
150 		logit("refusing previously-used %s key", sshkey_type(key));
151 		goto done;
152 	}
153 	if (match_pattern_list(pkalg, options.pubkey_accepted_algos, 0) != 1) {
154 		logit_f("key type %s not in PubkeyAcceptedAlgorithms",
155 		    sshkey_ssh_name(key));
156 		goto done;
157 	}
158 	if ((r = sshkey_check_cert_sigtype(key,
159 	    options.ca_sign_algorithms)) != 0) {
160 		logit_fr(r, "certificate signature algorithm %s",
161 		    (key->cert == NULL || key->cert->signature_type == NULL) ?
162 		    "(null)" : key->cert->signature_type);
163 		goto done;
164 	}
165 	key_s = format_key(key);
166 	if (sshkey_is_cert(key))
167 		ca_s = format_key(key->cert->signature_key);
168 
169 	if (have_sig) {
170 		debug3_f("have %s signature for %s%s%s", pkalg, key_s,
171 		    ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
172 		if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 ||
173 		    (r = sshpkt_get_end(ssh)) != 0)
174 			fatal_fr(r, "parse signature packet");
175 		if ((b = sshbuf_new()) == NULL)
176 			fatal_f("sshbuf_new failed");
177 		if (ssh->compat & SSH_OLD_SESSIONID) {
178 			if ((r = sshbuf_put(b, session_id2, session_id2_len)) != 0)
179 				fatal_fr(r, "put old session id");
180 		} else {
181 			if ((r = sshbuf_put_string(b, session_id2,
182 			    session_id2_len)) != 0)
183 				fatal_fr(r, "put session id");
184 		}
185 		if (!authctxt->valid || authctxt->user == NULL) {
186 			debug2_f("disabled because of invalid user");
187 			goto done;
188 		}
189 		/* reconstruct packet */
190 		xasprintf(&userstyle, "%s%s%s", authctxt->user,
191 		    authctxt->style ? ":" : "",
192 		    authctxt->style ? authctxt->style : "");
193 		if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
194 		    (r = sshbuf_put_cstring(b, userstyle)) != 0 ||
195 		    (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
196 		    (r = sshbuf_put_cstring(b, "publickey")) != 0 ||
197 		    (r = sshbuf_put_u8(b, have_sig)) != 0 ||
198 		    (r = sshbuf_put_cstring(b, pkalg)) != 0 ||
199 		    (r = sshbuf_put_string(b, pkblob, blen)) != 0)
200 			fatal_fr(r, "reconstruct packet");
201 #ifdef DEBUG_PK
202 		sshbuf_dump(b, stderr);
203 #endif
204 		/* test for correct signature */
205 		authenticated = 0;
206 		if (PRIVSEP(user_key_allowed(ssh, pw, key, 1, &authopts)) &&
207 		    PRIVSEP(sshkey_verify(key, sig, slen,
208 		    sshbuf_ptr(b), sshbuf_len(b),
209 		    (ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL,
210 		    ssh->compat, &sig_details)) == 0) {
211 			authenticated = 1;
212 		}
213 		if (authenticated == 1 && sig_details != NULL) {
214 			auth2_record_info(authctxt, "signature count = %u",
215 			    sig_details->sk_counter);
216 			debug_f("sk_counter = %u, sk_flags = 0x%02x",
217 			    sig_details->sk_counter, sig_details->sk_flags);
218 			req_presence = (options.pubkey_auth_options &
219 			    PUBKEYAUTH_TOUCH_REQUIRED) ||
220 			    !authopts->no_require_user_presence;
221 			if (req_presence && (sig_details->sk_flags &
222 			    SSH_SK_USER_PRESENCE_REQD) == 0) {
223 				error("public key %s signature for %s%s from "
224 				    "%.128s port %d rejected: user presence "
225 				    "(authenticator touch) requirement "
226 				    "not met ", key_s,
227 				    authctxt->valid ? "" : "invalid user ",
228 				    authctxt->user, ssh_remote_ipaddr(ssh),
229 				    ssh_remote_port(ssh));
230 				authenticated = 0;
231 				goto done;
232 			}
233 			req_verify = (options.pubkey_auth_options &
234 			    PUBKEYAUTH_VERIFY_REQUIRED) ||
235 			    authopts->require_verify;
236 			if (req_verify && (sig_details->sk_flags &
237 			    SSH_SK_USER_VERIFICATION_REQD) == 0) {
238 				error("public key %s signature for %s%s from "
239 				    "%.128s port %d rejected: user "
240 				    "verification requirement not met ", key_s,
241 				    authctxt->valid ? "" : "invalid user ",
242 				    authctxt->user, ssh_remote_ipaddr(ssh),
243 				    ssh_remote_port(ssh));
244 				authenticated = 0;
245 				goto done;
246 			}
247 		}
248 		auth2_record_key(authctxt, authenticated, key);
249 	} else {
250 		debug_f("test pkalg %s pkblob %s%s%s", pkalg, key_s,
251 		    ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
252 
253 		if ((r = sshpkt_get_end(ssh)) != 0)
254 			fatal_fr(r, "parse packet");
255 
256 		if (!authctxt->valid || authctxt->user == NULL) {
257 			debug2_f("disabled because of invalid user");
258 			goto done;
259 		}
260 		/* XXX fake reply and always send PK_OK ? */
261 		/*
262 		 * XXX this allows testing whether a user is allowed
263 		 * to login: if you happen to have a valid pubkey this
264 		 * message is sent. the message is NEVER sent at all
265 		 * if a user is not allowed to login. is this an
266 		 * issue? -markus
267 		 */
268 		if (PRIVSEP(user_key_allowed(ssh, pw, key, 0, NULL))) {
269 			if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK))
270 			    != 0 ||
271 			    (r = sshpkt_put_cstring(ssh, pkalg)) != 0 ||
272 			    (r = sshpkt_put_string(ssh, pkblob, blen)) != 0 ||
273 			    (r = sshpkt_send(ssh)) != 0 ||
274 			    (r = ssh_packet_write_wait(ssh)) != 0)
275 				fatal_fr(r, "send packet");
276 			authctxt->postponed = 1;
277 		}
278 	}
279 done:
280 	if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) {
281 		debug_f("key options inconsistent with existing");
282 		authenticated = 0;
283 	}
284 	debug2_f("authenticated %d pkalg %s", authenticated, pkalg);
285 
286 	sshbuf_free(b);
287 	sshauthopt_free(authopts);
288 	sshkey_free(key);
289 	free(userstyle);
290 	free(pkalg);
291 	free(pkblob);
292 	free(key_s);
293 	free(ca_s);
294 	free(sig);
295 	sshkey_sig_details_free(sig_details);
296 	return authenticated;
297 }
298 
299 static int
300 match_principals_option(const char *principal_list, struct sshkey_cert *cert)
301 {
302 	char *result;
303 	u_int i;
304 
305 	/* XXX percent_expand() sequences for authorized_principals? */
306 
307 	for (i = 0; i < cert->nprincipals; i++) {
308 		if ((result = match_list(cert->principals[i],
309 		    principal_list, NULL)) != NULL) {
310 			debug3("matched principal from key options \"%.100s\"",
311 			    result);
312 			free(result);
313 			return 1;
314 		}
315 	}
316 	return 0;
317 }
318 
319 /*
320  * Process a single authorized_principals format line. Returns 0 and sets
321  * authoptsp is principal is authorised, -1 otherwise. "loc" is used as a
322  * log preamble for file/line information.
323  */
324 static int
325 check_principals_line(struct ssh *ssh, char *cp, const struct sshkey_cert *cert,
326     const char *loc, struct sshauthopt **authoptsp)
327 {
328 	u_int i, found = 0;
329 	char *ep, *line_opts;
330 	const char *reason = NULL;
331 	struct sshauthopt *opts = NULL;
332 
333 	if (authoptsp != NULL)
334 		*authoptsp = NULL;
335 
336 	/* Trim trailing whitespace. */
337 	ep = cp + strlen(cp) - 1;
338 	while (ep > cp && (*ep == '\n' || *ep == ' ' || *ep == '\t'))
339 		*ep-- = '\0';
340 
341 	/*
342 	 * If the line has internal whitespace then assume it has
343 	 * key options.
344 	 */
345 	line_opts = NULL;
346 	if ((ep = strrchr(cp, ' ')) != NULL ||
347 	    (ep = strrchr(cp, '\t')) != NULL) {
348 		for (; *ep == ' ' || *ep == '\t'; ep++)
349 			;
350 		line_opts = cp;
351 		cp = ep;
352 	}
353 	if ((opts = sshauthopt_parse(line_opts, &reason)) == NULL) {
354 		debug("%s: bad principals options: %s", loc, reason);
355 		auth_debug_add("%s: bad principals options: %s", loc, reason);
356 		return -1;
357 	}
358 	/* Check principals in cert against those on line */
359 	for (i = 0; i < cert->nprincipals; i++) {
360 		if (strcmp(cp, cert->principals[i]) != 0)
361 			continue;
362 		debug3("%s: matched principal \"%.100s\"",
363 		    loc, cert->principals[i]);
364 		found = 1;
365 	}
366 	if (found && authoptsp != NULL) {
367 		*authoptsp = opts;
368 		opts = NULL;
369 	}
370 	sshauthopt_free(opts);
371 	return found ? 0 : -1;
372 }
373 
374 static int
375 process_principals(struct ssh *ssh, FILE *f, const char *file,
376     const struct sshkey_cert *cert, struct sshauthopt **authoptsp)
377 {
378 	char loc[256], *line = NULL, *cp, *ep;
379 	size_t linesize = 0;
380 	u_long linenum = 0;
381 	u_int found_principal = 0;
382 
383 	if (authoptsp != NULL)
384 		*authoptsp = NULL;
385 
386 	while (getline(&line, &linesize, f) != -1) {
387 		linenum++;
388 		/* Always consume entire input */
389 		if (found_principal)
390 			continue;
391 
392 		/* Skip leading whitespace. */
393 		for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
394 			;
395 		/* Skip blank and comment lines. */
396 		if ((ep = strchr(cp, '#')) != NULL)
397 			*ep = '\0';
398 		if (!*cp || *cp == '\n')
399 			continue;
400 
401 		snprintf(loc, sizeof(loc), "%.200s:%lu", file, linenum);
402 		if (check_principals_line(ssh, cp, cert, loc, authoptsp) == 0)
403 			found_principal = 1;
404 	}
405 	free(line);
406 	return found_principal;
407 }
408 
409 /* XXX remove pw args here and elsewhere once ssh->authctxt is guaranteed */
410 
411 static int
412 match_principals_file(struct ssh *ssh, struct passwd *pw, char *file,
413     struct sshkey_cert *cert, struct sshauthopt **authoptsp)
414 {
415 	FILE *f;
416 	int success;
417 
418 	if (authoptsp != NULL)
419 		*authoptsp = NULL;
420 
421 	temporarily_use_uid(pw);
422 	debug("trying authorized principals file %s", file);
423 	if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) {
424 		restore_uid();
425 		return 0;
426 	}
427 	success = process_principals(ssh, f, file, cert, authoptsp);
428 	fclose(f);
429 	restore_uid();
430 	return success;
431 }
432 
433 /*
434  * Checks whether principal is allowed in output of command.
435  * returns 1 if the principal is allowed or 0 otherwise.
436  */
437 static int
438 match_principals_command(struct ssh *ssh, struct passwd *user_pw,
439     const struct sshkey *key, struct sshauthopt **authoptsp)
440 {
441 	struct passwd *runas_pw = NULL;
442 	const struct sshkey_cert *cert = key->cert;
443 	FILE *f = NULL;
444 	int r, ok, found_principal = 0;
445 	int i, ac = 0, uid_swapped = 0;
446 	pid_t pid;
447 	char *tmp, *username = NULL, *command = NULL, **av = NULL;
448 	char *ca_fp = NULL, *key_fp = NULL, *catext = NULL, *keytext = NULL;
449 	char serial_s[32], uidstr[32];
450 	void (*osigchld)(int);
451 
452 	if (authoptsp != NULL)
453 		*authoptsp = NULL;
454 	if (options.authorized_principals_command == NULL)
455 		return 0;
456 	if (options.authorized_principals_command_user == NULL) {
457 		error("No user for AuthorizedPrincipalsCommand specified, "
458 		    "skipping");
459 		return 0;
460 	}
461 
462 	/*
463 	 * NB. all returns later this function should go via "out" to
464 	 * ensure the original SIGCHLD handler is restored properly.
465 	 */
466 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
467 
468 	/* Prepare and verify the user for the command */
469 	username = percent_expand(options.authorized_principals_command_user,
470 	    "u", user_pw->pw_name, (char *)NULL);
471 	runas_pw = getpwnam(username);
472 	if (runas_pw == NULL) {
473 		error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s",
474 		    username, strerror(errno));
475 		goto out;
476 	}
477 
478 	/* Turn the command into an argument vector */
479 	if (argv_split(options.authorized_principals_command, &ac, &av) != 0) {
480 		error("AuthorizedPrincipalsCommand \"%s\" contains "
481 		    "invalid quotes", options.authorized_principals_command);
482 		goto out;
483 	}
484 	if (ac == 0) {
485 		error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments",
486 		    options.authorized_principals_command);
487 		goto out;
488 	}
489 	if ((ca_fp = sshkey_fingerprint(cert->signature_key,
490 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
491 		error_f("sshkey_fingerprint failed");
492 		goto out;
493 	}
494 	if ((key_fp = sshkey_fingerprint(key,
495 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
496 		error_f("sshkey_fingerprint failed");
497 		goto out;
498 	}
499 	if ((r = sshkey_to_base64(cert->signature_key, &catext)) != 0) {
500 		error_fr(r, "sshkey_to_base64 failed");
501 		goto out;
502 	}
503 	if ((r = sshkey_to_base64(key, &keytext)) != 0) {
504 		error_fr(r, "sshkey_to_base64 failed");
505 		goto out;
506 	}
507 	snprintf(serial_s, sizeof(serial_s), "%llu",
508 	    (unsigned long long)cert->serial);
509 	snprintf(uidstr, sizeof(uidstr), "%llu",
510 	    (unsigned long long)user_pw->pw_uid);
511 	for (i = 1; i < ac; i++) {
512 		tmp = percent_expand(av[i],
513 		    "U", uidstr,
514 		    "u", user_pw->pw_name,
515 		    "h", user_pw->pw_dir,
516 		    "t", sshkey_ssh_name(key),
517 		    "T", sshkey_ssh_name(cert->signature_key),
518 		    "f", key_fp,
519 		    "F", ca_fp,
520 		    "k", keytext,
521 		    "K", catext,
522 		    "i", cert->key_id,
523 		    "s", serial_s,
524 		    (char *)NULL);
525 		if (tmp == NULL)
526 			fatal_f("percent_expand failed");
527 		free(av[i]);
528 		av[i] = tmp;
529 	}
530 	/* Prepare a printable command for logs, etc. */
531 	command = argv_assemble(ac, av);
532 
533 	if ((pid = subprocess("AuthorizedPrincipalsCommand", command,
534 	    ac, av, &f,
535 	    SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
536 	    runas_pw, temporarily_use_uid, restore_uid)) == 0)
537 		goto out;
538 
539 	uid_swapped = 1;
540 	temporarily_use_uid(runas_pw);
541 
542 	ok = process_principals(ssh, f, "(command)", cert, authoptsp);
543 
544 	fclose(f);
545 	f = NULL;
546 
547 	if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command, 0) != 0)
548 		goto out;
549 
550 	/* Read completed successfully */
551 	found_principal = ok;
552  out:
553 	if (f != NULL)
554 		fclose(f);
555 	ssh_signal(SIGCHLD, osigchld);
556 	for (i = 0; i < ac; i++)
557 		free(av[i]);
558 	free(av);
559 	if (uid_swapped)
560 		restore_uid();
561 	free(command);
562 	free(username);
563 	free(ca_fp);
564 	free(key_fp);
565 	free(catext);
566 	free(keytext);
567 	return found_principal;
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_f("keytype %d failed", 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 (sshkey_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_f("fingerprint failed");
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_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;
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_fr(r, "CA %s %s is not listed in %s",
769 		    sshkey_type(key->cert->signature_key), ca_fp,
770 		    options.trusted_user_ca_keys);
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_f("internal error: missing principals_opts");
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 = ssh_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_f("sshkey_fingerprint failed");
921 		goto out;
922 	}
923 	if ((r = sshkey_to_base64(key, &keytext)) != 0) {
924 		error_fr(r, "sshkey_to_base64 failed");
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 		    options.authorized_keys_command);
932 		goto out;
933 	}
934 	if (ac == 0) {
935 		error("AuthorizedKeysCommand \"%s\" yielded no arguments",
936 		    options.authorized_keys_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_f("percent_expand failed");
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", command,
973 	    ac, av, &f,
974 	    SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
975 	    runas_pw, temporarily_use_uid, restore_uid)) == 0)
976 		goto out;
977 
978 	uid_swapped = 1;
979 	temporarily_use_uid(runas_pw);
980 
981 	ok = check_authkeys_file(ssh, user_pw, f,
982 	    options.authorized_keys_command, key, authoptsp);
983 
984 	fclose(f);
985 	f = NULL;
986 
987 	if (exited_cleanly(pid, "AuthorizedKeysCommand", command, 0) != 0)
988 		goto out;
989 
990 	/* Read completed successfully */
991 	found_key = ok;
992  out:
993 	if (f != NULL)
994 		fclose(f);
995 	ssh_signal(SIGCHLD, osigchld);
996 	for (i = 0; i < ac; i++)
997 		free(av[i]);
998 	free(av);
999 	if (uid_swapped)
1000 		restore_uid();
1001 	free(command);
1002 	free(username);
1003 	free(key_fp);
1004 	free(keytext);
1005 	return found_key;
1006 }
1007 
1008 /*
1009  * Check whether key authenticates and authorises the user.
1010  */
1011 int
1012 user_key_allowed(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
1013     int auth_attempt, struct sshauthopt **authoptsp)
1014 {
1015 	u_int success = 0, i;
1016 	char *file;
1017 	struct sshauthopt *opts = NULL;
1018 
1019 	if (authoptsp != NULL)
1020 		*authoptsp = NULL;
1021 
1022 	if (auth_key_is_revoked(key))
1023 		return 0;
1024 	if (sshkey_is_cert(key) &&
1025 	    auth_key_is_revoked(key->cert->signature_key))
1026 		return 0;
1027 
1028 	for (i = 0; !success && i < options.num_authkeys_files; i++) {
1029 		if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
1030 			continue;
1031 		file = expand_authorized_keys(
1032 		    options.authorized_keys_files[i], pw);
1033 		success = user_key_allowed2(ssh, pw, key, file, &opts);
1034 		free(file);
1035 		if (!success) {
1036 			sshauthopt_free(opts);
1037 			opts = NULL;
1038 		}
1039 	}
1040 	if (success)
1041 		goto out;
1042 
1043 	if ((success = user_cert_trusted_ca(ssh, pw, key, &opts)) != 0)
1044 		goto out;
1045 	sshauthopt_free(opts);
1046 	opts = NULL;
1047 
1048 	if ((success = user_key_command_allowed2(ssh, pw, key, &opts)) != 0)
1049 		goto out;
1050 	sshauthopt_free(opts);
1051 	opts = NULL;
1052 
1053  out:
1054 	if (success && authoptsp != NULL) {
1055 		*authoptsp = opts;
1056 		opts = NULL;
1057 	}
1058 	sshauthopt_free(opts);
1059 	return success;
1060 }
1061 
1062 Authmethod method_pubkey = {
1063 	"publickey",
1064 	userauth_pubkey,
1065 	&options.pubkey_authentication
1066 };
1067