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