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