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