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