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