1 /*	$NetBSD: ssh-agent.c,v 1.35 2023/07/26 17:58:15 christos Exp $	*/
2 /* $OpenBSD: ssh-agent.c,v 1.297 2023/03/09 21:06:24 jcs Exp $ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * The authentication agent program.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #include "includes.h"
39 __RCSID("$NetBSD: ssh-agent.c,v 1.35 2023/07/26 17:58:15 christos Exp $");
40 
41 #include <sys/param.h>	/* MIN MAX */
42 #include <sys/types.h>
43 #include <sys/time.h>
44 #include <sys/queue.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <sys/stat.h>
48 #include <sys/un.h>
49 #include <sys/wait.h>
50 
51 #ifdef WITH_OPENSSL
52 #include <openssl/evp.h>
53 #endif
54 
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <paths.h>
58 #include <poll.h>
59 #include <signal.h>
60 #include <stdlib.h>
61 #include <stdio.h>
62 #include <string.h>
63 #include <stdarg.h>
64 #include <limits.h>
65 #include <time.h>
66 #include <unistd.h>
67 #include <util.h>
68 
69 #include "xmalloc.h"
70 #include "ssh.h"
71 #include "ssh2.h"
72 #include "sshbuf.h"
73 #include "sshkey.h"
74 #include "authfd.h"
75 #include "log.h"
76 #include "misc.h"
77 #include "getpeereid.h"
78 #include "digest.h"
79 #include "ssherr.h"
80 #include "match.h"
81 #include "msg.h"
82 #include "pathnames.h"
83 #include "ssh-pkcs11.h"
84 #include "sk-api.h"
85 #include "myproposal.h"
86 
87 #ifndef DEFAULT_ALLOWED_PROVIDERS
88 # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/pkg/lib*/*"
89 #endif
90 
91 /* Maximum accepted message length */
92 #define AGENT_MAX_LEN		(256*1024)
93 /* Maximum bytes to read from client socket */
94 #define AGENT_RBUF_LEN		(4096)
95 /* Maximum number of recorded session IDs/hostkeys per connection */
96 #define AGENT_MAX_SESSION_IDS		16
97 /* Maximum size of session ID */
98 #define AGENT_MAX_SID_LEN		128
99 /* Maximum number of destination constraints to accept on a key */
100 #define AGENT_MAX_DEST_CONSTRAINTS	1024
101 
102 /* XXX store hostkey_sid in a refcounted tree */
103 
104 typedef enum {
105 	AUTH_UNUSED = 0,
106 	AUTH_SOCKET = 1,
107 	AUTH_CONNECTION = 2,
108 } sock_type;
109 
110 struct hostkey_sid {
111 	struct sshkey *key;
112 	struct sshbuf *sid;
113 	int forwarded;
114 };
115 
116 typedef struct socket_entry {
117 	int fd;
118 	sock_type type;
119 	struct sshbuf *input;
120 	struct sshbuf *output;
121 	struct sshbuf *request;
122 	size_t nsession_ids;
123 	struct hostkey_sid *session_ids;
124 } SocketEntry;
125 
126 u_int sockets_alloc = 0;
127 SocketEntry *sockets = NULL;
128 
129 typedef struct identity {
130 	TAILQ_ENTRY(identity) next;
131 	struct sshkey *key;
132 	char *comment;
133 	char *provider;
134 	time_t death;
135 	u_int confirm;
136 	char *sk_provider;
137 	struct dest_constraint *dest_constraints;
138 	size_t ndest_constraints;
139 } Identity;
140 
141 struct idtable {
142 	int nentries;
143 	TAILQ_HEAD(idqueue, identity) idlist;
144 };
145 
146 /* private key table */
147 struct idtable *idtab;
148 
149 int max_fd = 0;
150 
151 /* pid of shell == parent of agent */
152 pid_t parent_pid = -1;
153 time_t parent_alive_interval = 0;
154 
155 /* pid of process for which cleanup_socket is applicable */
156 pid_t cleanup_pid = 0;
157 
158 /* pathname and directory for AUTH_SOCKET */
159 char socket_name[PATH_MAX];
160 char socket_dir[PATH_MAX];
161 
162 /* Pattern-list of allowed PKCS#11/Security key paths */
163 static char *allowed_providers;
164 
165 /*
166  * Allows PKCS11 providers or SK keys that use non-internal providers to
167  * be added over a remote connection (identified by session-bind@openssh.com).
168  */
169 static int remote_add_provider;
170 
171 /* locking */
172 #define LOCK_SIZE	32
173 #define LOCK_SALT_SIZE	16
174 #define LOCK_ROUNDS	1
175 int locked = 0;
176 u_char lock_pwhash[LOCK_SIZE];
177 u_char lock_salt[LOCK_SALT_SIZE];
178 
179 extern char *__progname;
180 
181 /* Default lifetime in seconds (0 == forever) */
182 static int lifetime = 0;
183 
184 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
185 
186 /* Refuse signing of non-SSH messages for web-origin FIDO keys */
187 static int restrict_websafe = 1;
188 
189 static void
close_socket(SocketEntry * e)190 close_socket(SocketEntry *e)
191 {
192 	size_t i;
193 
194 	close(e->fd);
195 	sshbuf_free(e->input);
196 	sshbuf_free(e->output);
197 	sshbuf_free(e->request);
198 	for (i = 0; i < e->nsession_ids; i++) {
199 		sshkey_free(e->session_ids[i].key);
200 		sshbuf_free(e->session_ids[i].sid);
201 	}
202 	free(e->session_ids);
203 	memset(e, '\0', sizeof(*e));
204 	e->fd = -1;
205 	e->type = AUTH_UNUSED;
206 }
207 
208 static void
idtab_init(void)209 idtab_init(void)
210 {
211 	idtab = xcalloc(1, sizeof(*idtab));
212 	TAILQ_INIT(&idtab->idlist);
213 	idtab->nentries = 0;
214 }
215 
216 static void
free_dest_constraint_hop(struct dest_constraint_hop * dch)217 free_dest_constraint_hop(struct dest_constraint_hop *dch)
218 {
219 	u_int i;
220 
221 	if (dch == NULL)
222 		return;
223 	free(dch->user);
224 	free(dch->hostname);
225 	for (i = 0; i < dch->nkeys; i++)
226 		sshkey_free(dch->keys[i]);
227 	free(dch->keys);
228 	free(dch->key_is_ca);
229 }
230 
231 static void
free_dest_constraints(struct dest_constraint * dcs,size_t ndcs)232 free_dest_constraints(struct dest_constraint *dcs, size_t ndcs)
233 {
234 	size_t i;
235 
236 	for (i = 0; i < ndcs; i++) {
237 		free_dest_constraint_hop(&dcs[i].from);
238 		free_dest_constraint_hop(&dcs[i].to);
239 	}
240 	free(dcs);
241 }
242 
243 static void
free_identity(Identity * id)244 free_identity(Identity *id)
245 {
246 	sshkey_free(id->key);
247 	free(id->provider);
248 	free(id->comment);
249 	free(id->sk_provider);
250 	free_dest_constraints(id->dest_constraints, id->ndest_constraints);
251 	free(id);
252 }
253 
254 /*
255  * Match 'key' against the key/CA list in a destination constraint hop
256  * Returns 0 on success or -1 otherwise.
257  */
258 static int
match_key_hop(const char * tag,const struct sshkey * key,const struct dest_constraint_hop * dch)259 match_key_hop(const char *tag, const struct sshkey *key,
260     const struct dest_constraint_hop *dch)
261 {
262 	const char *reason = NULL;
263 	const char *hostname = dch->hostname ? dch->hostname : "(ORIGIN)";
264 	u_int i;
265 	char *fp;
266 
267 	if (key == NULL)
268 		return -1;
269 	/* XXX logspam */
270 	if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
271 	    SSH_FP_DEFAULT)) == NULL)
272 		fatal_f("fingerprint failed");
273 	debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail",
274 	    tag, hostname, sshkey_type(key), fp, dch->nkeys);
275 	free(fp);
276 	for (i = 0; i < dch->nkeys; i++) {
277 		if (dch->keys[i] == NULL)
278 			return -1;
279 		/* XXX logspam */
280 		if ((fp = sshkey_fingerprint(dch->keys[i], SSH_FP_HASH_DEFAULT,
281 		    SSH_FP_DEFAULT)) == NULL)
282 			fatal_f("fingerprint failed");
283 		debug3_f("%s: key %u: %s%s %s", tag, i,
284 		    dch->key_is_ca[i] ? "CA " : "",
285 		    sshkey_type(dch->keys[i]), fp);
286 		free(fp);
287 		if (!sshkey_is_cert(key)) {
288 			/* plain key */
289 			if (dch->key_is_ca[i] ||
290 			    !sshkey_equal(key, dch->keys[i]))
291 				continue;
292 			return 0;
293 		}
294 		/* certificate */
295 		if (!dch->key_is_ca[i])
296 			continue;
297 		if (key->cert == NULL || key->cert->signature_key == NULL)
298 			return -1; /* shouldn't happen */
299 		if (!sshkey_equal(key->cert->signature_key, dch->keys[i]))
300 			continue;
301 		if (sshkey_cert_check_host(key, hostname, 1,
302 		    SSH_ALLOWED_CA_SIGALGS, &reason) != 0) {
303 			debug_f("cert %s / hostname %s rejected: %s",
304 			    key->cert->key_id, hostname, reason);
305 			continue;
306 		}
307 		return 0;
308 	}
309 	return -1;
310 }
311 
312 /* Check destination constraints on an identity against the hostkey/user */
313 static int
permitted_by_dest_constraints(const struct sshkey * fromkey,const struct sshkey * tokey,Identity * id,const char * user,const char ** hostnamep)314 permitted_by_dest_constraints(const struct sshkey *fromkey,
315     const struct sshkey *tokey, Identity *id, const char *user,
316     const char **hostnamep)
317 {
318 	size_t i;
319 	struct dest_constraint *d;
320 
321 	if (hostnamep != NULL)
322 		*hostnamep = NULL;
323 	for (i = 0; i < id->ndest_constraints; i++) {
324 		d = id->dest_constraints + i;
325 		/* XXX remove logspam */
326 		debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)",
327 		    i, d->from.user ? d->from.user : "",
328 		    d->from.user ? "@" : "",
329 		    d->from.hostname ? d->from.hostname : "(ORIGIN)",
330 		    d->from.nkeys,
331 		    d->to.user ? d->to.user : "", d->to.user ? "@" : "",
332 		    d->to.hostname ? d->to.hostname : "(ANY)", d->to.nkeys);
333 
334 		/* Match 'from' key */
335 		if (fromkey == NULL) {
336 			/* We are matching the first hop */
337 			if (d->from.hostname != NULL || d->from.nkeys != 0)
338 				continue;
339 		} else if (match_key_hop("from", fromkey, &d->from) != 0)
340 			continue;
341 
342 		/* Match 'to' key */
343 		if (tokey != NULL && match_key_hop("to", tokey, &d->to) != 0)
344 			continue;
345 
346 		/* Match user if specified */
347 		if (d->to.user != NULL && user != NULL &&
348 		    !match_pattern(user, d->to.user))
349 			continue;
350 
351 		/* successfully matched this constraint */
352 		if (hostnamep != NULL)
353 			*hostnamep = d->to.hostname;
354 		debug2_f("allowed for hostname %s",
355 		    d->to.hostname == NULL ? "*" : d->to.hostname);
356 		return 0;
357 	}
358 	/* no match */
359 	debug2_f("%s identity \"%s\" not permitted for this destination",
360 	    sshkey_type(id->key), id->comment);
361 	return -1;
362 }
363 
364 /*
365  * Check whether hostkeys on a SocketEntry and the optionally specified user
366  * are permitted by the destination constraints on the Identity.
367  * Returns 0 on success or -1 otherwise.
368  */
369 static int
identity_permitted(Identity * id,SocketEntry * e,char * user,const char ** forward_hostnamep,const char ** last_hostnamep)370 identity_permitted(Identity *id, SocketEntry *e, char *user,
371     const char **forward_hostnamep, const char **last_hostnamep)
372 {
373 	size_t i;
374 	const char **hp;
375 	struct hostkey_sid *hks;
376 	const struct sshkey *fromkey = NULL;
377 	const char *test_user;
378 	char *fp1, *fp2;
379 
380 	/* XXX remove logspam */
381 	debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
382 	    "%zu constraints", sshkey_type(id->key), id->comment,
383 	    e->nsession_ids, id->ndest_constraints);
384 	if (id->ndest_constraints == 0)
385 		return 0; /* unconstrained */
386 	if (e->nsession_ids == 0)
387 		return 0; /* local use */
388 	/*
389 	 * Walk through the hops recorded by session_id and try to find a
390 	 * constraint that satisfies each.
391 	 */
392 	for (i = 0; i < e->nsession_ids; i++) {
393 		hks = e->session_ids + i;
394 		if (hks->key == NULL)
395 			fatal_f("internal error: no bound key");
396 		/* XXX remove logspam */
397 		fp1 = fp2 = NULL;
398 		if (fromkey != NULL &&
399 		    (fp1 = sshkey_fingerprint(fromkey, SSH_FP_HASH_DEFAULT,
400 		    SSH_FP_DEFAULT)) == NULL)
401 			fatal_f("fingerprint failed");
402 		if ((fp2 = sshkey_fingerprint(hks->key, SSH_FP_HASH_DEFAULT,
403 		    SSH_FP_DEFAULT)) == NULL)
404 			fatal_f("fingerprint failed");
405 		debug3_f("socketentry fd=%d, entry %zu %s, "
406 		    "from hostkey %s %s to user %s hostkey %s %s",
407 		    e->fd, i, hks->forwarded ? "FORWARD" : "AUTH",
408 		    fromkey ? sshkey_type(fromkey) : "(ORIGIN)",
409 		    fromkey ? fp1 : "", user ? user : "(ANY)",
410 		    sshkey_type(hks->key), fp2);
411 		free(fp1);
412 		free(fp2);
413 		/*
414 		 * Record the hostnames for the initial forwarding and
415 		 * the final destination.
416 		 */
417 		hp = NULL;
418 		if (i == e->nsession_ids - 1)
419 			hp = last_hostnamep;
420 		else if (i == 0)
421 			hp = forward_hostnamep;
422 		/* Special handling for final recorded binding */
423 		test_user = NULL;
424 		if (i == e->nsession_ids - 1) {
425 			/* Can only check user at final hop */
426 			test_user = user;
427 			/*
428 			 * user is only presented for signature requests.
429 			 * If this is the case, make sure last binding is not
430 			 * for a forwarding.
431 			 */
432 			if (hks->forwarded && user != NULL) {
433 				error_f("tried to sign on forwarding hop");
434 				return -1;
435 			}
436 		} else if (!hks->forwarded) {
437 			error_f("tried to forward though signing bind");
438 			return -1;
439 		}
440 		if (permitted_by_dest_constraints(fromkey, hks->key, id,
441 		    test_user, hp) != 0)
442 			return -1;
443 		fromkey = hks->key;
444 	}
445 	/*
446 	 * Another special case: if the last bound session ID was for a
447 	 * forwarding, and this function is not being called to check a sign
448 	 * request (i.e. no 'user' supplied), then only permit the key if
449 	 * there is a permission that would allow it to be used at another
450 	 * destination. This hides keys that are allowed to be used to
451 	 * authenticate *to* a host but not permitted for *use* beyond it.
452 	 */
453 	hks = &e->session_ids[e->nsession_ids - 1];
454 	if (hks->forwarded && user == NULL &&
455 	    permitted_by_dest_constraints(hks->key, NULL, id,
456 	    NULL, NULL) != 0) {
457 		debug3_f("key permitted at host but not after");
458 		return -1;
459 	}
460 
461 	/* success */
462 	return 0;
463 }
464 
465 /* return matching private key for given public key */
466 static Identity *
lookup_identity(struct sshkey * key)467 lookup_identity(struct sshkey *key)
468 {
469 	Identity *id;
470 
471 	TAILQ_FOREACH(id, &idtab->idlist, next) {
472 		if (sshkey_equal(key, id->key))
473 			return (id);
474 	}
475 	return (NULL);
476 }
477 
478 /* Check confirmation of keysign request */
479 static int
confirm_key(Identity * id,const char * extra)480 confirm_key(Identity *id, const char *extra)
481 {
482 	char *p;
483 	int ret = -1;
484 
485 	p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
486 	if (p != NULL &&
487 	    ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
488 	    id->comment, p,
489 	    extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
490 		ret = 0;
491 	free(p);
492 
493 	return (ret);
494 }
495 
496 static void
send_status(SocketEntry * e,int success)497 send_status(SocketEntry *e, int success)
498 {
499 	int r;
500 
501 	if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
502 	    (r = sshbuf_put_u8(e->output, success ?
503 	    SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
504 		fatal_fr(r, "compose");
505 }
506 
507 /* send list of supported public keys to 'client' */
508 static void
process_request_identities(SocketEntry * e)509 process_request_identities(SocketEntry *e)
510 {
511 	Identity *id;
512 	struct sshbuf *msg, *keys;
513 	int r;
514 	u_int nentries = 0;
515 
516 	debug2_f("entering");
517 
518 	if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL)
519 		fatal_f("sshbuf_new failed");
520 	TAILQ_FOREACH(id, &idtab->idlist, next) {
521 		/* identity not visible, don't include in response */
522 		if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
523 			continue;
524 		if ((r = sshkey_puts_opts(id->key, keys,
525 		    SSHKEY_SERIALIZE_INFO)) != 0 ||
526 		    (r = sshbuf_put_cstring(keys, id->comment)) != 0) {
527 			error_fr(r, "compose key/comment");
528 			continue;
529 		}
530 		nentries++;
531 	}
532 	debug2_f("replying with %u allowed of %u available keys",
533 	    nentries, idtab->nentries);
534 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
535 	    (r = sshbuf_put_u32(msg, nentries)) != 0 ||
536 	    (r = sshbuf_putb(msg, keys)) != 0)
537 		fatal_fr(r, "compose");
538 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
539 		fatal_fr(r, "enqueue");
540 	sshbuf_free(msg);
541 	sshbuf_free(keys);
542 }
543 
544 
545 static const char *
agent_decode_alg(struct sshkey * key,u_int flags)546 agent_decode_alg(struct sshkey *key, u_int flags)
547 {
548 	if (key->type == KEY_RSA) {
549 		if (flags & SSH_AGENT_RSA_SHA2_256)
550 			return "rsa-sha2-256";
551 		else if (flags & SSH_AGENT_RSA_SHA2_512)
552 			return "rsa-sha2-512";
553 	} else if (key->type == KEY_RSA_CERT) {
554 		if (flags & SSH_AGENT_RSA_SHA2_256)
555 			return "rsa-sha2-256-cert-v01@openssh.com";
556 		else if (flags & SSH_AGENT_RSA_SHA2_512)
557 			return "rsa-sha2-512-cert-v01@openssh.com";
558 	}
559 	return NULL;
560 }
561 
562 /*
563  * Attempt to parse the contents of a buffer as a SSH publickey userauth
564  * request, checking its contents for consistency and matching the embedded
565  * key against the one that is being used for signing.
566  * Note: does not modify msg buffer.
567  * Optionally extract the username, session ID and/or hostkey from the request.
568  */
569 static int
parse_userauth_request(struct sshbuf * msg,const struct sshkey * expected_key,char ** userp,struct sshbuf ** sess_idp,struct sshkey ** hostkeyp)570 parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
571     char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp)
572 {
573 	struct sshbuf *b = NULL, *sess_id = NULL;
574 	char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
575 	int r;
576 	u_char t, sig_follows;
577 	struct sshkey *mkey = NULL, *hostkey = NULL;
578 
579 	if (userp != NULL)
580 		*userp = NULL;
581 	if (sess_idp != NULL)
582 		*sess_idp = NULL;
583 	if (hostkeyp != NULL)
584 		*hostkeyp = NULL;
585 	if ((b = sshbuf_fromb(msg)) == NULL)
586 		fatal_f("sshbuf_fromb");
587 
588 	/* SSH userauth request */
589 	if ((r = sshbuf_froms(b, &sess_id)) != 0)
590 		goto out;
591 	if (sshbuf_len(sess_id) == 0) {
592 		r = SSH_ERR_INVALID_FORMAT;
593 		goto out;
594 	}
595 	if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
596 	    (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
597 	    (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
598 	    (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
599 	    (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
600 	    (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
601 	    (r = sshkey_froms(b, &mkey)) != 0) /* key */
602 		goto out;
603 	if (t != SSH2_MSG_USERAUTH_REQUEST ||
604 	    sig_follows != 1 ||
605 	    strcmp(service, "ssh-connection") != 0 ||
606 	    !sshkey_equal(expected_key, mkey) ||
607 	    sshkey_type_from_name(pkalg) != expected_key->type) {
608 		r = SSH_ERR_INVALID_FORMAT;
609 		goto out;
610 	}
611 	if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) {
612 		if ((r = sshkey_froms(b, &hostkey)) != 0)
613 			goto out;
614 	} else if (strcmp(method, "publickey") != 0) {
615 		r = SSH_ERR_INVALID_FORMAT;
616 		goto out;
617 	}
618 	if (sshbuf_len(b) != 0) {
619 		r = SSH_ERR_INVALID_FORMAT;
620 		goto out;
621 	}
622 	/* success */
623 	r = 0;
624 	debug3_f("well formed userauth");
625 	if (userp != NULL) {
626 		*userp = user;
627 		user = NULL;
628 	}
629 	if (sess_idp != NULL) {
630 		*sess_idp = sess_id;
631 		sess_id = NULL;
632 	}
633 	if (hostkeyp != NULL) {
634 		*hostkeyp = hostkey;
635 		hostkey = NULL;
636 	}
637  out:
638 	sshbuf_free(b);
639 	sshbuf_free(sess_id);
640 	free(user);
641 	free(service);
642 	free(method);
643 	free(pkalg);
644 	sshkey_free(mkey);
645 	sshkey_free(hostkey);
646 	return r;
647 }
648 
649 /*
650  * Attempt to parse the contents of a buffer as a SSHSIG signature request.
651  * Note: does not modify buffer.
652  */
653 static int
parse_sshsig_request(struct sshbuf * msg)654 parse_sshsig_request(struct sshbuf *msg)
655 {
656 	int r;
657 	struct sshbuf *b;
658 
659 	if ((b = sshbuf_fromb(msg)) == NULL)
660 		fatal_f("sshbuf_fromb");
661 
662 	if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
663 	    (r = sshbuf_consume(b, 6)) != 0 ||
664 	    (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
665 	    (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
666 	    (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
667 	    (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
668 		goto out;
669 	if (sshbuf_len(b) != 0) {
670 		r = SSH_ERR_INVALID_FORMAT;
671 		goto out;
672 	}
673 	/* success */
674 	r = 0;
675  out:
676 	sshbuf_free(b);
677 	return r;
678 }
679 
680 /*
681  * This function inspects a message to be signed by a FIDO key that has a
682  * web-like application string (i.e. one that does not begin with "ssh:".
683  * It checks that the message is one of those expected for SSH operations
684  * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
685  * for the web.
686  */
687 static int
check_websafe_message_contents(struct sshkey * key,struct sshbuf * data)688 check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
689 {
690 	if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) {
691 		debug_f("signed data matches public key userauth request");
692 		return 1;
693 	}
694 	if (parse_sshsig_request(data) == 0) {
695 		debug_f("signed data matches SSHSIG signature request");
696 		return 1;
697 	}
698 
699 	/* XXX check CA signature operation */
700 
701 	error("web-origin key attempting to sign non-SSH message");
702 	return 0;
703 }
704 
705 static int
buf_equal(const struct sshbuf * a,const struct sshbuf * b)706 buf_equal(const struct sshbuf *a, const struct sshbuf *b)
707 {
708 	if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL)
709 		return SSH_ERR_INVALID_ARGUMENT;
710 	if (sshbuf_len(a) != sshbuf_len(b))
711 		return SSH_ERR_INVALID_FORMAT;
712 	if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0)
713 		return SSH_ERR_INVALID_FORMAT;
714 	return 0;
715 }
716 
717 /* ssh2 only */
718 static void
process_sign_request2(SocketEntry * e)719 process_sign_request2(SocketEntry *e)
720 {
721 	u_char *signature = NULL;
722 	size_t slen = 0;
723 	u_int compat = 0, flags;
724 	int r, ok = -1, retried = 0;
725 	char *fp = NULL, *pin = NULL, *prompt = NULL;
726 	char *user = NULL, *sig_dest = NULL;
727 	const char *fwd_host = NULL, *dest_host = NULL;
728 	struct sshbuf *msg = NULL, *data = NULL, *sid = NULL;
729 	struct sshkey *key = NULL, *hostkey = NULL;
730 	struct identity *id;
731 	struct notifier_ctx *notifier = NULL;
732 
733 	debug_f("entering");
734 
735 	if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
736 		fatal_f("sshbuf_new failed");
737 	if ((r = sshkey_froms(e->request, &key)) != 0 ||
738 	    (r = sshbuf_get_stringb(e->request, data)) != 0 ||
739 	    (r = sshbuf_get_u32(e->request, &flags)) != 0) {
740 		error_fr(r, "parse");
741 		goto send;
742 	}
743 
744 	if ((id = lookup_identity(key)) == NULL) {
745 		verbose_f("%s key not found", sshkey_type(key));
746 		goto send;
747 	}
748 	if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
749 	    SSH_FP_DEFAULT)) == NULL)
750 		fatal_f("fingerprint failed");
751 
752 	if (id->ndest_constraints != 0) {
753 		if (e->nsession_ids == 0) {
754 			logit_f("refusing use of destination-constrained key "
755 			    "to sign on unbound connection");
756 			goto send;
757 		}
758 		if (parse_userauth_request(data, key, &user, &sid,
759 		    &hostkey) != 0) {
760 			logit_f("refusing use of destination-constrained key "
761 			   "to sign an unidentified signature");
762 			goto send;
763 		}
764 		/* XXX logspam */
765 		debug_f("user=%s", user);
766 		if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
767 			goto send;
768 		/* XXX display fwd_host/dest_host in askpass UI */
769 		/*
770 		 * Ensure that the session ID is the most recent one
771 		 * registered on the socket - it should have been bound by
772 		 * ssh immediately before userauth.
773 		 */
774 		if (buf_equal(sid,
775 		    e->session_ids[e->nsession_ids - 1].sid) != 0) {
776 			error_f("unexpected session ID (%zu listed) on "
777 			    "signature request for target user %s with "
778 			    "key %s %s", e->nsession_ids, user,
779 			    sshkey_type(id->key), fp);
780 			goto send;
781 		}
782 		/*
783 		 * Ensure that the hostkey embedded in the signature matches
784 		 * the one most recently bound to the socket. An exception is
785 		 * made for the initial forwarding hop.
786 		 */
787 		if (e->nsession_ids > 1 && hostkey == NULL) {
788 			error_f("refusing use of destination-constrained key: "
789 			    "no hostkey recorded in signature for forwarded "
790 			    "connection");
791 			goto send;
792 		}
793 		if (hostkey != NULL && !sshkey_equal(hostkey,
794 		    e->session_ids[e->nsession_ids - 1].key)) {
795 			error_f("refusing use of destination-constrained key: "
796 			    "mismatch between hostkey in request and most "
797 			    "recently bound session");
798 			goto send;
799 		}
800 		xasprintf(&sig_dest, "public key authentication request for "
801 		    "user \"%s\" to listed host", user);
802 	}
803 	if (id->confirm && confirm_key(id, sig_dest) != 0) {
804 		verbose_f("user refused key");
805 		goto send;
806 	}
807 	if (sshkey_is_sk(id->key)) {
808 		if (restrict_websafe &&
809 		    strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
810 		    !check_websafe_message_contents(key, data)) {
811 			/* error already logged */
812 			goto send;
813 		}
814 		if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
815 			notifier = notify_start(0,
816 			    "Confirm user presence for key %s %s%s%s",
817 			    sshkey_type(id->key), fp,
818 			    sig_dest == NULL ? "" : "\n",
819 			    sig_dest == NULL ? "" : sig_dest);
820 		}
821 	}
822  retry_pin:
823 	if ((r = sshkey_sign(id->key, &signature, &slen,
824 	    sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
825 	    id->sk_provider, pin, compat)) != 0) {
826 		debug_fr(r, "sshkey_sign");
827 		if (pin == NULL && !retried && sshkey_is_sk(id->key) &&
828 		    r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
829 			notify_complete(notifier, NULL);
830 			notifier = NULL;
831 			/* XXX include sig_dest */
832 			xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
833 			    (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
834 			    " and confirm user presence " : " ",
835 			    sshkey_type(id->key), fp);
836 			pin = read_passphrase(prompt, RP_USE_ASKPASS);
837 			retried = 1;
838 			goto retry_pin;
839 		}
840 		error_fr(r, "sshkey_sign");
841 		goto send;
842 	}
843 	/* Success */
844 	ok = 0;
845  send:
846 	debug_f("good signature");
847 	notify_complete(notifier, "User presence confirmed");
848 
849 	if (ok == 0) {
850 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
851 		    (r = sshbuf_put_string(msg, signature, slen)) != 0)
852 			fatal_fr(r, "compose");
853 	} else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
854 		fatal_fr(r, "compose failure");
855 
856 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
857 		fatal_fr(r, "enqueue");
858 
859 	sshbuf_free(sid);
860 	sshbuf_free(data);
861 	sshbuf_free(msg);
862 	sshkey_free(key);
863 	sshkey_free(hostkey);
864 	free(fp);
865 	free(signature);
866 	free(sig_dest);
867 	free(user);
868 	free(prompt);
869 	if (pin != NULL)
870 		freezero(pin, strlen(pin));
871 }
872 
873 /* shared */
874 static void
process_remove_identity(SocketEntry * e)875 process_remove_identity(SocketEntry *e)
876 {
877 	int r, success = 0;
878 	struct sshkey *key = NULL;
879 	Identity *id;
880 
881 	debug2_f("entering");
882 	if ((r = sshkey_froms(e->request, &key)) != 0) {
883 		error_fr(r, "parse key");
884 		goto done;
885 	}
886 	if ((id = lookup_identity(key)) == NULL) {
887 		debug_f("key not found");
888 		goto done;
889 	}
890 	/* identity not visible, cannot be removed */
891 	if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
892 		goto done; /* error already logged */
893 	/* We have this key, free it. */
894 	if (idtab->nentries < 1)
895 		fatal_f("internal error: nentries %d", idtab->nentries);
896 	TAILQ_REMOVE(&idtab->idlist, id, next);
897 	free_identity(id);
898 	idtab->nentries--;
899 	success = 1;
900  done:
901 	sshkey_free(key);
902 	send_status(e, success);
903 }
904 
905 static void
process_remove_all_identities(SocketEntry * e)906 process_remove_all_identities(SocketEntry *e)
907 {
908 	Identity *id;
909 
910 	debug2_f("entering");
911 	/* Loop over all identities and clear the keys. */
912 	for (id = TAILQ_FIRST(&idtab->idlist); id;
913 	    id = TAILQ_FIRST(&idtab->idlist)) {
914 		TAILQ_REMOVE(&idtab->idlist, id, next);
915 		free_identity(id);
916 	}
917 
918 	/* Mark that there are no identities. */
919 	idtab->nentries = 0;
920 
921 	/* Send success. */
922 	send_status(e, 1);
923 }
924 
925 /* removes expired keys and returns number of seconds until the next expiry */
926 static time_t
reaper(void)927 reaper(void)
928 {
929 	time_t deadline = 0, now = monotime();
930 	Identity *id, *nxt;
931 
932 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
933 		nxt = TAILQ_NEXT(id, next);
934 		if (id->death == 0)
935 			continue;
936 		if (now >= id->death) {
937 			debug("expiring key '%s'", id->comment);
938 			TAILQ_REMOVE(&idtab->idlist, id, next);
939 			free_identity(id);
940 			idtab->nentries--;
941 		} else
942 			deadline = (deadline == 0) ? id->death :
943 			    MINIMUM(deadline, id->death);
944 	}
945 	if (deadline == 0 || deadline <= now)
946 		return 0;
947 	else
948 		return (deadline - now);
949 }
950 
951 static int
parse_dest_constraint_hop(struct sshbuf * b,struct dest_constraint_hop * dch)952 parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
953 {
954 	u_char key_is_ca;
955 	size_t elen = 0;
956 	int r;
957 	struct sshkey *k = NULL;
958 	char *fp;
959 
960 	memset(dch, '\0', sizeof(*dch));
961 	if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
962 	    (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
963 	    (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
964 		error_fr(r, "parse");
965 		goto out;
966 	}
967 	if (elen != 0) {
968 		error_f("unsupported extensions (len %zu)", elen);
969 		r = SSH_ERR_FEATURE_UNSUPPORTED;
970 		goto out;
971 	}
972 	if (*dch->hostname == '\0') {
973 		free(dch->hostname);
974 		dch->hostname = NULL;
975 	}
976 	if (*dch->user == '\0') {
977 		free(dch->user);
978 		dch->user = NULL;
979 	}
980 	while (sshbuf_len(b) != 0) {
981 		dch->keys = xrecallocarray(dch->keys, dch->nkeys,
982 		    dch->nkeys + 1, sizeof(*dch->keys));
983 		dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
984 		    dch->nkeys + 1, sizeof(*dch->key_is_ca));
985 		if ((r = sshkey_froms(b, &k)) != 0 ||
986 		    (r = sshbuf_get_u8(b, &key_is_ca)) != 0)
987 			goto out;
988 		if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
989 		    SSH_FP_DEFAULT)) == NULL)
990 			fatal_f("fingerprint failed");
991 		debug3_f("%s%s%s: adding %skey %s %s",
992 		    dch->user == NULL ? "" : dch->user,
993 		    dch->user == NULL ? "" : "@",
994 		    dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
995 		free(fp);
996 		dch->keys[dch->nkeys] = k;
997 		dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
998 		dch->nkeys++;
999 		k = NULL; /* transferred */
1000 	}
1001 	/* success */
1002 	r = 0;
1003  out:
1004 	sshkey_free(k);
1005 	return r;
1006 }
1007 
1008 static int
parse_dest_constraint(struct sshbuf * m,struct dest_constraint * dc)1009 parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
1010 {
1011 	struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
1012 	int r;
1013 	size_t elen = 0;
1014 
1015 	debug3_f("entering");
1016 
1017 	memset(dc, '\0', sizeof(*dc));
1018 	if ((r = sshbuf_froms(m, &b)) != 0 ||
1019 	    (r = sshbuf_froms(b, &frombuf)) != 0 ||
1020 	    (r = sshbuf_froms(b, &tobuf)) != 0 ||
1021 	    (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1022 		error_fr(r, "parse");
1023 		goto out;
1024 	}
1025 	if ((r = parse_dest_constraint_hop(frombuf, &dc->from)) != 0 ||
1026 	    (r = parse_dest_constraint_hop(tobuf, &dc->to)) != 0)
1027 		goto out; /* already logged */
1028 	if (elen != 0) {
1029 		error_f("unsupported extensions (len %zu)", elen);
1030 		r = SSH_ERR_FEATURE_UNSUPPORTED;
1031 		goto out;
1032 	}
1033 	debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
1034 	    dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
1035 	    dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
1036 	    dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
1037 	/* check consistency */
1038 	if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
1039 	    dc->from.user != NULL) {
1040 		error_f("inconsistent \"from\" specification");
1041 		r = SSH_ERR_INVALID_FORMAT;
1042 		goto out;
1043 	}
1044 	if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
1045 		error_f("incomplete \"to\" specification");
1046 		r = SSH_ERR_INVALID_FORMAT;
1047 		goto out;
1048 	}
1049 	/* success */
1050 	r = 0;
1051  out:
1052 	sshbuf_free(b);
1053 	sshbuf_free(frombuf);
1054 	sshbuf_free(tobuf);
1055 	return r;
1056 }
1057 
1058 static int
parse_key_constraint_extension(struct sshbuf * m,char ** sk_providerp,struct dest_constraint ** dcsp,size_t * ndcsp)1059 parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
1060     struct dest_constraint **dcsp, size_t *ndcsp)
1061 {
1062 	char *ext_name = NULL;
1063 	int r;
1064 	struct sshbuf *b = NULL;
1065 
1066 	if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
1067 		error_fr(r, "parse constraint extension");
1068 		goto out;
1069 	}
1070 	debug_f("constraint ext %s", ext_name);
1071 	if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
1072 		if (sk_providerp == NULL) {
1073 			error_f("%s not valid here", ext_name);
1074 			r = SSH_ERR_INVALID_FORMAT;
1075 			goto out;
1076 		}
1077 		if (*sk_providerp != NULL) {
1078 			error_f("%s already set", ext_name);
1079 			r = SSH_ERR_INVALID_FORMAT;
1080 			goto out;
1081 		}
1082 		if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
1083 			error_fr(r, "parse %s", ext_name);
1084 			goto out;
1085 		}
1086 	} else if (strcmp(ext_name,
1087 	    "restrict-destination-v00@openssh.com") == 0) {
1088 		if (*dcsp != NULL) {
1089 			error_f("%s already set", ext_name);
1090 			goto out;
1091 		}
1092 		if ((r = sshbuf_froms(m, &b)) != 0) {
1093 			error_fr(r, "parse %s outer", ext_name);
1094 			goto out;
1095 		}
1096 		while (sshbuf_len(b) != 0) {
1097 			if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
1098 				error_f("too many %s constraints", ext_name);
1099 				goto out;
1100 			}
1101 			*dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
1102 			    sizeof(**dcsp));
1103 			if ((r = parse_dest_constraint(b,
1104 			    *dcsp + (*ndcsp)++)) != 0)
1105 				goto out; /* error already logged */
1106 		}
1107 	} else {
1108 		error_f("unsupported constraint \"%s\"", ext_name);
1109 		r = SSH_ERR_FEATURE_UNSUPPORTED;
1110 		goto out;
1111 	}
1112 	/* success */
1113 	r = 0;
1114  out:
1115 	free(ext_name);
1116 	sshbuf_free(b);
1117 	return r;
1118 }
1119 
1120 static int
parse_key_constraints(struct sshbuf * m,struct sshkey * k,time_t * deathp,u_int * secondsp,int * confirmp,char ** sk_providerp,struct dest_constraint ** dcsp,size_t * ndcsp)1121 parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
1122     u_int *secondsp, int *confirmp, char **sk_providerp,
1123     struct dest_constraint **dcsp, size_t *ndcsp)
1124 {
1125 	u_char ctype;
1126 	int r;
1127 	u_int seconds, maxsign = 0;
1128 
1129 	while (sshbuf_len(m)) {
1130 		if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
1131 			error_fr(r, "parse constraint type");
1132 			goto out;
1133 		}
1134 		switch (ctype) {
1135 		case SSH_AGENT_CONSTRAIN_LIFETIME:
1136 			if (*deathp != 0) {
1137 				error_f("lifetime already set");
1138 				r = SSH_ERR_INVALID_FORMAT;
1139 				goto out;
1140 			}
1141 			if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
1142 				error_fr(r, "parse lifetime constraint");
1143 				goto out;
1144 			}
1145 			*deathp = monotime() + seconds;
1146 			*secondsp = seconds;
1147 			break;
1148 		case SSH_AGENT_CONSTRAIN_CONFIRM:
1149 			if (*confirmp != 0) {
1150 				error_f("confirm already set");
1151 				r = SSH_ERR_INVALID_FORMAT;
1152 				goto out;
1153 			}
1154 			*confirmp = 1;
1155 			break;
1156 		case SSH_AGENT_CONSTRAIN_MAXSIGN:
1157 			if (k == NULL) {
1158 				error_f("maxsign not valid here");
1159 				r = SSH_ERR_INVALID_FORMAT;
1160 				goto out;
1161 			}
1162 			if (maxsign != 0) {
1163 				error_f("maxsign already set");
1164 				r = SSH_ERR_INVALID_FORMAT;
1165 				goto out;
1166 			}
1167 			if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
1168 				error_fr(r, "parse maxsign constraint");
1169 				goto out;
1170 			}
1171 			if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
1172 				error_fr(r, "enable maxsign");
1173 				goto out;
1174 			}
1175 			break;
1176 		case SSH_AGENT_CONSTRAIN_EXTENSION:
1177 			if ((r = parse_key_constraint_extension(m,
1178 			    sk_providerp, dcsp, ndcsp)) != 0)
1179 				goto out; /* error already logged */
1180 			break;
1181 		default:
1182 			error_f("Unknown constraint %d", ctype);
1183 			r = SSH_ERR_FEATURE_UNSUPPORTED;
1184 			goto out;
1185 		}
1186 	}
1187 	/* success */
1188 	r = 0;
1189  out:
1190 	return r;
1191 }
1192 
1193 static void
process_add_identity(SocketEntry * e)1194 process_add_identity(SocketEntry *e)
1195 {
1196 	Identity *id;
1197 	int success = 0, confirm = 0;
1198 	char *fp, *comment = NULL, *sk_provider = NULL;
1199 	char canonical_provider[PATH_MAX];
1200 	time_t death = 0;
1201 	u_int seconds = 0;
1202 	struct dest_constraint *dest_constraints = NULL;
1203 	size_t ndest_constraints = 0;
1204 	struct sshkey *k = NULL;
1205 	int r = SSH_ERR_INTERNAL_ERROR;
1206 
1207 	debug2_f("entering");
1208 	if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
1209 	    k == NULL ||
1210 	    (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
1211 		error_fr(r, "parse");
1212 		goto out;
1213 	}
1214 	if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
1215 	    &sk_provider, &dest_constraints, &ndest_constraints) != 0) {
1216 		error_f("failed to parse constraints");
1217 		sshbuf_reset(e->request);
1218 		goto out;
1219 	}
1220 
1221 	if (sk_provider != NULL) {
1222 		if (!sshkey_is_sk(k)) {
1223 			error("Cannot add provider: %s is not an "
1224 			    "authenticator-hosted key", sshkey_type(k));
1225 			goto out;
1226 		}
1227 		if (strcasecmp(sk_provider, "internal") == 0) {
1228 			debug_f("internal provider");
1229 		} else {
1230 			if (e->nsession_ids != 0 && !remote_add_provider) {
1231 				verbose("failed add of SK provider \"%.100s\": "
1232 				    "remote addition of providers is disabled",
1233 				    sk_provider);
1234 				goto out;
1235 			}
1236 			if (realpath(sk_provider, canonical_provider) == NULL) {
1237 				verbose("failed provider \"%.100s\": "
1238 				    "realpath: %s", sk_provider,
1239 				    strerror(errno));
1240 				goto out;
1241 			}
1242 			free(sk_provider);
1243 			sk_provider = xstrdup(canonical_provider);
1244 			if (match_pattern_list(sk_provider,
1245 			    allowed_providers, 0) != 1) {
1246 				error("Refusing add key: "
1247 				    "provider %s not allowed", sk_provider);
1248 				goto out;
1249 			}
1250 		}
1251 	}
1252 	if ((r = sshkey_shield_private(k)) != 0) {
1253 		error_fr(r, "shield private");
1254 		goto out;
1255 	}
1256 	if (lifetime && !death)
1257 		death = monotime() + lifetime;
1258 	if ((id = lookup_identity(k)) == NULL) {
1259 		id = xcalloc(1, sizeof(Identity));
1260 		TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1261 		/* Increment the number of identities. */
1262 		idtab->nentries++;
1263 	} else {
1264 		/* identity not visible, do not update */
1265 		if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1266 			goto out; /* error already logged */
1267 		/* key state might have been updated */
1268 		sshkey_free(id->key);
1269 		free(id->comment);
1270 		free(id->sk_provider);
1271 		free_dest_constraints(id->dest_constraints,
1272 		    id->ndest_constraints);
1273 	}
1274 	/* success */
1275 	id->key = k;
1276 	id->comment = comment;
1277 	id->death = death;
1278 	id->confirm = confirm;
1279 	id->sk_provider = sk_provider;
1280 	id->dest_constraints = dest_constraints;
1281 	id->ndest_constraints = ndest_constraints;
1282 
1283 	if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1284 	    SSH_FP_DEFAULT)) == NULL)
1285 		fatal_f("sshkey_fingerprint failed");
1286 	debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1287 	    "(provider: %s) (destination constraints: %zu)",
1288 	    sshkey_ssh_name(k), fp, comment, seconds, confirm,
1289 	    sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
1290 	free(fp);
1291 	/* transferred */
1292 	k = NULL;
1293 	comment = NULL;
1294 	sk_provider = NULL;
1295 	dest_constraints = NULL;
1296 	ndest_constraints = 0;
1297 	success = 1;
1298  out:
1299 	free(sk_provider);
1300 	free(comment);
1301 	sshkey_free(k);
1302 	free_dest_constraints(dest_constraints, ndest_constraints);
1303 	send_status(e, success);
1304 }
1305 
1306 /* XXX todo: encrypt sensitive data with passphrase */
1307 static void
process_lock_agent(SocketEntry * e,int lock)1308 process_lock_agent(SocketEntry *e, int lock)
1309 {
1310 	int r, success = 0, delay;
1311 	char *passwd;
1312 	u_char passwdhash[LOCK_SIZE];
1313 	static u_int fail_count = 0;
1314 	size_t pwlen;
1315 
1316 	debug2_f("entering");
1317 	/*
1318 	 * This is deliberately fatal: the user has requested that we lock,
1319 	 * but we can't parse their request properly. The only safe thing to
1320 	 * do is abort.
1321 	 */
1322 	if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
1323 		fatal_fr(r, "parse");
1324 	if (pwlen == 0) {
1325 		debug("empty password not supported");
1326 	} else if (locked && !lock) {
1327 		if (bcrypt_pbkdf(passwd, pwlen, (uint8_t *)lock_salt, sizeof(lock_salt),
1328 		    (uint8_t *)passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
1329 			fatal("bcrypt_pbkdf");
1330 		if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1331 			debug("agent unlocked");
1332 			locked = 0;
1333 			fail_count = 0;
1334 			explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1335 			success = 1;
1336 		} else {
1337 			/* delay in 0.1s increments up to 10s */
1338 			if (fail_count < 100)
1339 				fail_count++;
1340 			delay = 100000 * fail_count;
1341 			debug("unlock failed, delaying %0.1lf seconds",
1342 			    (double)delay/1000000);
1343 			usleep(delay);
1344 		}
1345 		explicit_bzero(passwdhash, sizeof(passwdhash));
1346 	} else if (!locked && lock) {
1347 		debug("agent locked");
1348 		locked = 1;
1349 		arc4random_buf(lock_salt, sizeof(lock_salt));
1350 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1351 		    lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1352 			fatal("bcrypt_pbkdf");
1353 		success = 1;
1354 	}
1355 	freezero(passwd, pwlen);
1356 	send_status(e, success);
1357 }
1358 
1359 static void
no_identities(SocketEntry * e)1360 no_identities(SocketEntry *e)
1361 {
1362 	struct sshbuf *msg;
1363 	int r;
1364 
1365 	if ((msg = sshbuf_new()) == NULL)
1366 		fatal_f("sshbuf_new failed");
1367 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1368 	    (r = sshbuf_put_u32(msg, 0)) != 0 ||
1369 	    (r = sshbuf_put_stringb(e->output, msg)) != 0)
1370 		fatal_fr(r, "compose");
1371 	sshbuf_free(msg);
1372 }
1373 
1374 #ifdef ENABLE_PKCS11
1375 static void
process_add_smartcard_key(SocketEntry * e)1376 process_add_smartcard_key(SocketEntry *e)
1377 {
1378 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1379 	char **comments = NULL;
1380 	int r, i, count = 0, success = 0, confirm = 0;
1381 	u_int seconds = 0;
1382 	time_t death = 0;
1383 	struct sshkey **keys = NULL, *k;
1384 	Identity *id;
1385 	struct dest_constraint *dest_constraints = NULL;
1386 	size_t ndest_constraints = 0;
1387 
1388 	debug2_f("entering");
1389 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1390 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1391 		error_fr(r, "parse");
1392 		goto send;
1393 	}
1394 	if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
1395 	    NULL, &dest_constraints, &ndest_constraints) != 0) {
1396 		error_f("failed to parse constraints");
1397 		goto send;
1398 	}
1399 	if (e->nsession_ids != 0 && !remote_add_provider) {
1400 		verbose("failed PKCS#11 add of \"%.100s\": remote addition of "
1401 		    "providers is disabled", provider);
1402 		goto send;
1403 	}
1404 	if (realpath(provider, canonical_provider) == NULL) {
1405 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1406 		    provider, strerror(errno));
1407 		goto send;
1408 	}
1409 	if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
1410 		verbose("refusing PKCS#11 add of \"%.100s\": "
1411 		    "provider not allowed", canonical_provider);
1412 		goto send;
1413 	}
1414 	debug_f("add %.100s", canonical_provider);
1415 	if (lifetime && !death)
1416 		death = monotime() + lifetime;
1417 
1418 	count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
1419 	for (i = 0; i < count; i++) {
1420 		k = keys[i];
1421 		if (lookup_identity(k) == NULL) {
1422 			id = xcalloc(1, sizeof(Identity));
1423 			id->key = k;
1424 			keys[i] = NULL; /* transferred */
1425 			id->provider = xstrdup(canonical_provider);
1426 			if (*comments[i] != '\0') {
1427 				id->comment = comments[i];
1428 				comments[i] = NULL; /* transferred */
1429 			} else {
1430 				id->comment = xstrdup(canonical_provider);
1431 			}
1432 			id->death = death;
1433 			id->confirm = confirm;
1434 			id->dest_constraints = dest_constraints;
1435 			id->ndest_constraints = ndest_constraints;
1436 			dest_constraints = NULL; /* transferred */
1437 			ndest_constraints = 0;
1438 			TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1439 			idtab->nentries++;
1440 			success = 1;
1441 		}
1442 		/* XXX update constraints for existing keys */
1443 		sshkey_free(keys[i]);
1444 		free(comments[i]);
1445 	}
1446 send:
1447 	free(pin);
1448 	free(provider);
1449 	free(keys);
1450 	free(comments);
1451 	free_dest_constraints(dest_constraints, ndest_constraints);
1452 	send_status(e, success);
1453 }
1454 
1455 static void
process_remove_smartcard_key(SocketEntry * e)1456 process_remove_smartcard_key(SocketEntry *e)
1457 {
1458 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1459 	int r, success = 0;
1460 	Identity *id, *nxt;
1461 
1462 	debug2_f("entering");
1463 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1464 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1465 		error_fr(r, "parse");
1466 		goto send;
1467 	}
1468 	free(pin);
1469 
1470 	if (realpath(provider, canonical_provider) == NULL) {
1471 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1472 		    provider, strerror(errno));
1473 		goto send;
1474 	}
1475 
1476 	debug_f("remove %.100s", canonical_provider);
1477 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1478 		nxt = TAILQ_NEXT(id, next);
1479 		/* Skip file--based keys */
1480 		if (id->provider == NULL)
1481 			continue;
1482 		if (!strcmp(canonical_provider, id->provider)) {
1483 			TAILQ_REMOVE(&idtab->idlist, id, next);
1484 			free_identity(id);
1485 			idtab->nentries--;
1486 		}
1487 	}
1488 	if (pkcs11_del_provider(canonical_provider) == 0)
1489 		success = 1;
1490 	else
1491 		error_f("pkcs11_del_provider failed");
1492 send:
1493 	free(provider);
1494 	send_status(e, success);
1495 }
1496 #endif /* ENABLE_PKCS11 */
1497 
1498 static int
process_ext_session_bind(SocketEntry * e)1499 process_ext_session_bind(SocketEntry *e)
1500 {
1501 	int r, sid_match, key_match;
1502 	struct sshkey *key = NULL;
1503 	struct sshbuf *sid = NULL, *sig = NULL;
1504 	char *fp = NULL;
1505 	size_t i;
1506 	u_char fwd = 0;
1507 
1508 	debug2_f("entering");
1509 	if ((r = sshkey_froms(e->request, &key)) != 0 ||
1510 	    (r = sshbuf_froms(e->request, &sid)) != 0 ||
1511 	    (r = sshbuf_froms(e->request, &sig)) != 0 ||
1512 	    (r = sshbuf_get_u8(e->request, &fwd)) != 0) {
1513 		error_fr(r, "parse");
1514 		goto out;
1515 	}
1516 	if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
1517 	    SSH_FP_DEFAULT)) == NULL)
1518 		fatal_f("fingerprint failed");
1519 	/* check signature with hostkey on session ID */
1520 	if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
1521 	    sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
1522 		error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
1523 		goto out;
1524 	}
1525 	/* check whether sid/key already recorded */
1526 	for (i = 0; i < e->nsession_ids; i++) {
1527 		if (!e->session_ids[i].forwarded) {
1528 			error_f("attempt to bind session ID to socket "
1529 			    "previously bound for authentication attempt");
1530 			r = -1;
1531 			goto out;
1532 		}
1533 		sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
1534 		key_match = sshkey_equal(key, e->session_ids[i].key);
1535 		if (sid_match && key_match) {
1536 			debug_f("session ID already recorded for %s %s",
1537 			    sshkey_type(key), fp);
1538 			r = 0;
1539 			goto out;
1540 		} else if (sid_match) {
1541 			error_f("session ID recorded against different key "
1542 			    "for %s %s", sshkey_type(key), fp);
1543 			r = -1;
1544 			goto out;
1545 		}
1546 		/*
1547 		 * new sid with previously-seen key can happen, e.g. multiple
1548 		 * connections to the same host.
1549 		 */
1550 	}
1551 	/* record new key/sid */
1552 	if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
1553 		error_f("too many session IDs recorded");
1554 		goto out;
1555 	}
1556 	e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
1557 	    e->nsession_ids + 1, sizeof(*e->session_ids));
1558 	i = e->nsession_ids++;
1559 	debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
1560 	    AGENT_MAX_SESSION_IDS);
1561 	e->session_ids[i].key = key;
1562 	e->session_ids[i].forwarded = fwd != 0;
1563 	key = NULL; /* transferred */
1564 	/* can't transfer sid; it's refcounted and scoped to request's life */
1565 	if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
1566 		fatal_f("sshbuf_new");
1567 	if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
1568 		fatal_fr(r, "sshbuf_putb session ID");
1569 	/* success */
1570 	r = 0;
1571  out:
1572 	free(fp);
1573 	sshkey_free(key);
1574 	sshbuf_free(sid);
1575 	sshbuf_free(sig);
1576 	return r == 0 ? 1 : 0;
1577 }
1578 
1579 static void
process_extension(SocketEntry * e)1580 process_extension(SocketEntry *e)
1581 {
1582 	int r, success = 0;
1583 	char *name;
1584 
1585 	debug2_f("entering");
1586 	if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
1587 		error_fr(r, "parse");
1588 		goto send;
1589 	}
1590 	if (strcmp(name, "session-bind@openssh.com") == 0)
1591 		success = process_ext_session_bind(e);
1592 	else
1593 		debug_f("unsupported extension \"%s\"", name);
1594 	free(name);
1595 send:
1596 	send_status(e, success);
1597 }
1598 /*
1599  * dispatch incoming message.
1600  * returns 1 on success, 0 for incomplete messages or -1 on error.
1601  */
1602 static int
process_message(u_int socknum)1603 process_message(u_int socknum)
1604 {
1605 	u_int msg_len;
1606 	u_char type;
1607 	const u_char *cp;
1608 	int r;
1609 	SocketEntry *e;
1610 
1611 	if (socknum >= sockets_alloc)
1612 		fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
1613 	e = &sockets[socknum];
1614 
1615 	if (sshbuf_len(e->input) < 5)
1616 		return 0;		/* Incomplete message header. */
1617 	cp = sshbuf_ptr(e->input);
1618 	msg_len = PEEK_U32(cp);
1619 	if (msg_len > AGENT_MAX_LEN) {
1620 		debug_f("socket %u (fd=%d) message too long %u > %u",
1621 		    socknum, e->fd, msg_len, AGENT_MAX_LEN);
1622 		return -1;
1623 	}
1624 	if (sshbuf_len(e->input) < msg_len + 4)
1625 		return 0;		/* Incomplete message body. */
1626 
1627 	/* move the current input to e->request */
1628 	sshbuf_reset(e->request);
1629 	if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1630 	    (r = sshbuf_get_u8(e->request, &type)) != 0) {
1631 		if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1632 		    r == SSH_ERR_STRING_TOO_LARGE) {
1633 			error_fr(r, "parse");
1634 			return -1;
1635 		}
1636 		fatal_fr(r, "parse");
1637 	}
1638 
1639 	debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1640 
1641 	/* check whether agent is locked */
1642 	if (locked && type != SSH_AGENTC_UNLOCK) {
1643 		sshbuf_reset(e->request);
1644 		switch (type) {
1645 		case SSH2_AGENTC_REQUEST_IDENTITIES:
1646 			/* send empty lists */
1647 			no_identities(e);
1648 			break;
1649 		default:
1650 			/* send a fail message for all other request types */
1651 			send_status(e, 0);
1652 		}
1653 		return 1;
1654 	}
1655 
1656 	switch (type) {
1657 	case SSH_AGENTC_LOCK:
1658 	case SSH_AGENTC_UNLOCK:
1659 		process_lock_agent(e, type == SSH_AGENTC_LOCK);
1660 		break;
1661 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1662 		process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1663 		break;
1664 	/* ssh2 */
1665 	case SSH2_AGENTC_SIGN_REQUEST:
1666 		process_sign_request2(e);
1667 		break;
1668 	case SSH2_AGENTC_REQUEST_IDENTITIES:
1669 		process_request_identities(e);
1670 		break;
1671 	case SSH2_AGENTC_ADD_IDENTITY:
1672 	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1673 		process_add_identity(e);
1674 		break;
1675 	case SSH2_AGENTC_REMOVE_IDENTITY:
1676 		process_remove_identity(e);
1677 		break;
1678 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1679 		process_remove_all_identities(e);
1680 		break;
1681 #ifdef ENABLE_PKCS11
1682 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
1683 	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1684 		process_add_smartcard_key(e);
1685 		break;
1686 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1687 		process_remove_smartcard_key(e);
1688 		break;
1689 #endif /* ENABLE_PKCS11 */
1690 	case SSH_AGENTC_EXTENSION:
1691 		process_extension(e);
1692 		break;
1693 	default:
1694 		/* Unknown message.  Respond with failure. */
1695 		error("Unknown message %d", type);
1696 		sshbuf_reset(e->request);
1697 		send_status(e, 0);
1698 		break;
1699 	}
1700 	return 1;
1701 }
1702 
1703 static void
new_socket(sock_type type,int fd)1704 new_socket(sock_type type, int fd)
1705 {
1706 	u_int i, old_alloc, new_alloc;
1707 
1708 	debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1709 	    (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1710 	set_nonblock(fd);
1711 
1712 	if (fd > max_fd)
1713 		max_fd = fd;
1714 
1715 	for (i = 0; i < sockets_alloc; i++)
1716 		if (sockets[i].type == AUTH_UNUSED) {
1717 			sockets[i].fd = fd;
1718 			if ((sockets[i].input = sshbuf_new()) == NULL ||
1719 			    (sockets[i].output = sshbuf_new()) == NULL ||
1720 			    (sockets[i].request = sshbuf_new()) == NULL)
1721 				fatal_f("sshbuf_new failed");
1722 			sockets[i].type = type;
1723 			return;
1724 		}
1725 	old_alloc = sockets_alloc;
1726 	new_alloc = sockets_alloc + 10;
1727 	sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1728 	    sizeof(sockets[0]));
1729 	for (i = old_alloc; i < new_alloc; i++)
1730 		sockets[i].type = AUTH_UNUSED;
1731 	sockets_alloc = new_alloc;
1732 	sockets[old_alloc].fd = fd;
1733 	if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1734 	    (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1735 	    (sockets[old_alloc].request = sshbuf_new()) == NULL)
1736 		fatal_f("sshbuf_new failed");
1737 	sockets[old_alloc].type = type;
1738 }
1739 
1740 static int
handle_socket_read(u_int socknum)1741 handle_socket_read(u_int socknum)
1742 {
1743 	struct sockaddr_un sunaddr;
1744 	socklen_t slen;
1745 	uid_t euid;
1746 	gid_t egid;
1747 	int fd;
1748 
1749 	slen = sizeof(sunaddr);
1750 	fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1751 	if (fd == -1) {
1752 		error("accept from AUTH_SOCKET: %s", strerror(errno));
1753 		return -1;
1754 	}
1755 	if (getpeereid(fd, &euid, &egid) == -1) {
1756 		error("getpeereid %d failed: %s", fd, strerror(errno));
1757 		close(fd);
1758 		return -1;
1759 	}
1760 	if ((euid != 0) && (getuid() != euid)) {
1761 		error("uid mismatch: peer euid %u != uid %u",
1762 		    (u_int) euid, (u_int) getuid());
1763 		close(fd);
1764 		return -1;
1765 	}
1766 	new_socket(AUTH_CONNECTION, fd);
1767 	return 0;
1768 }
1769 
1770 static int
handle_conn_read(u_int socknum)1771 handle_conn_read(u_int socknum)
1772 {
1773 	char buf[AGENT_RBUF_LEN];
1774 	ssize_t len;
1775 	int r;
1776 
1777 	if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1778 		if (len == -1) {
1779 			if (errno == EAGAIN || errno == EINTR)
1780 				return 0;
1781 			error_f("read error on socket %u (fd %d): %s",
1782 			    socknum, sockets[socknum].fd, strerror(errno));
1783 		}
1784 		return -1;
1785 	}
1786 	if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1787 		fatal_fr(r, "compose");
1788 	explicit_bzero(buf, sizeof(buf));
1789 	for (;;) {
1790 		if ((r = process_message(socknum)) == -1)
1791 			return -1;
1792 		else if (r == 0)
1793 			break;
1794 	}
1795 	return 0;
1796 }
1797 
1798 static int
handle_conn_write(u_int socknum)1799 handle_conn_write(u_int socknum)
1800 {
1801 	ssize_t len;
1802 	int r;
1803 
1804 	if (sshbuf_len(sockets[socknum].output) == 0)
1805 		return 0; /* shouldn't happen */
1806 	if ((len = write(sockets[socknum].fd,
1807 	    sshbuf_ptr(sockets[socknum].output),
1808 	    sshbuf_len(sockets[socknum].output))) <= 0) {
1809 		if (len == -1) {
1810 			if (errno == EAGAIN || errno == EINTR)
1811 				return 0;
1812 			error_f("read error on socket %u (fd %d): %s",
1813 			    socknum, sockets[socknum].fd, strerror(errno));
1814 		}
1815 		return -1;
1816 	}
1817 	if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
1818 		fatal_fr(r, "consume");
1819 	return 0;
1820 }
1821 
1822 static void
after_poll(struct pollfd * pfd,size_t npfd,u_int maxfds)1823 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
1824 {
1825 	size_t i;
1826 	u_int socknum, activefds = npfd;
1827 
1828 	for (i = 0; i < npfd; i++) {
1829 		if (pfd[i].revents == 0)
1830 			continue;
1831 		/* Find sockets entry */
1832 		for (socknum = 0; socknum < sockets_alloc; socknum++) {
1833 			if (sockets[socknum].type != AUTH_SOCKET &&
1834 			    sockets[socknum].type != AUTH_CONNECTION)
1835 				continue;
1836 			if (pfd[i].fd == sockets[socknum].fd)
1837 				break;
1838 		}
1839 		if (socknum >= sockets_alloc) {
1840 			error_f("no socket for fd %d", pfd[i].fd);
1841 			continue;
1842 		}
1843 		/* Process events */
1844 		switch (sockets[socknum].type) {
1845 		case AUTH_SOCKET:
1846 			if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
1847 				break;
1848 			if (npfd > maxfds) {
1849 				debug3("out of fds (active %u >= limit %u); "
1850 				    "skipping accept", activefds, maxfds);
1851 				break;
1852 			}
1853 			if (handle_socket_read(socknum) == 0)
1854 				activefds++;
1855 			break;
1856 		case AUTH_CONNECTION:
1857 			if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
1858 			    handle_conn_read(socknum) != 0)
1859 				goto close_sock;
1860 			if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
1861 			    handle_conn_write(socknum) != 0) {
1862  close_sock:
1863 				if (activefds == 0)
1864 					fatal("activefds == 0 at close_sock");
1865 				close_socket(&sockets[socknum]);
1866 				activefds--;
1867 				break;
1868 			}
1869 			break;
1870 		default:
1871 			break;
1872 		}
1873 	}
1874 }
1875 
1876 static int
prepare_poll(struct pollfd ** pfdp,size_t * npfdp,int * timeoutp,u_int maxfds)1877 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1878 {
1879 	struct pollfd *pfd = *pfdp;
1880 	size_t i, j, npfd = 0;
1881 	time_t deadline;
1882 	int r;
1883 
1884 	/* Count active sockets */
1885 	for (i = 0; i < sockets_alloc; i++) {
1886 		switch (sockets[i].type) {
1887 		case AUTH_SOCKET:
1888 		case AUTH_CONNECTION:
1889 			npfd++;
1890 			break;
1891 		case AUTH_UNUSED:
1892 			break;
1893 		default:
1894 			fatal("Unknown socket type %d", sockets[i].type);
1895 			break;
1896 		}
1897 	}
1898 	if (npfd != *npfdp &&
1899 	    (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1900 		fatal_f("recallocarray failed");
1901 	*pfdp = pfd;
1902 	*npfdp = npfd;
1903 
1904 	for (i = j = 0; i < sockets_alloc; i++) {
1905 		switch (sockets[i].type) {
1906 		case AUTH_SOCKET:
1907 			if (npfd > maxfds) {
1908 				debug3("out of fds (active %zu >= limit %u); "
1909 				    "skipping arming listener", npfd, maxfds);
1910 				break;
1911 			}
1912 			pfd[j].fd = sockets[i].fd;
1913 			pfd[j].revents = 0;
1914 			pfd[j].events = POLLIN;
1915 			j++;
1916 			break;
1917 		case AUTH_CONNECTION:
1918 			pfd[j].fd = sockets[i].fd;
1919 			pfd[j].revents = 0;
1920 			/*
1921 			 * Only prepare to read if we can handle a full-size
1922 			 * input read buffer and enqueue a max size reply..
1923 			 */
1924 			if ((r = sshbuf_check_reserve(sockets[i].input,
1925 			    AGENT_RBUF_LEN)) == 0 &&
1926 			    (r = sshbuf_check_reserve(sockets[i].output,
1927 			    AGENT_MAX_LEN)) == 0)
1928 				pfd[j].events = POLLIN;
1929 			else if (r != SSH_ERR_NO_BUFFER_SPACE)
1930 				fatal_fr(r, "reserve");
1931 			if (sshbuf_len(sockets[i].output) > 0)
1932 				pfd[j].events |= POLLOUT;
1933 			j++;
1934 			break;
1935 		default:
1936 			break;
1937 		}
1938 	}
1939 	deadline = reaper();
1940 	if (parent_alive_interval != 0)
1941 		deadline = (deadline == 0) ? parent_alive_interval :
1942 		    MINIMUM(deadline, parent_alive_interval);
1943 	if (deadline == 0) {
1944 		*timeoutp = -1; /* INFTIM */
1945 	} else {
1946 		if (deadline > INT_MAX / 1000)
1947 			*timeoutp = INT_MAX / 1000;
1948 		else
1949 			*timeoutp = deadline * 1000;
1950 	}
1951 	return (1);
1952 }
1953 
1954 static void
cleanup_socket(void)1955 cleanup_socket(void)
1956 {
1957 	if (cleanup_pid != 0 && getpid() != cleanup_pid)
1958 		return;
1959 	debug_f("cleanup");
1960 	if (socket_name[0])
1961 		unlink(socket_name);
1962 	if (socket_dir[0])
1963 		rmdir(socket_dir);
1964 }
1965 
1966 void
cleanup_exit(int i)1967 cleanup_exit(int i)
1968 {
1969 	cleanup_socket();
1970 	_exit(i);
1971 }
1972 
1973 /*ARGSUSED*/
1974 __dead static void
cleanup_handler(int sig)1975 cleanup_handler(int sig)
1976 {
1977 	cleanup_socket();
1978 #ifdef ENABLE_PKCS11
1979 	pkcs11_terminate();
1980 #endif
1981 	_exit(2);
1982 }
1983 
1984 static void
check_parent_exists(void)1985 check_parent_exists(void)
1986 {
1987 	/*
1988 	 * If our parent has exited then getppid() will return (pid_t)1,
1989 	 * so testing for that should be safe.
1990 	 */
1991 	if (parent_pid != -1 && getppid() != parent_pid) {
1992 		/* printf("Parent has died - Authentication agent exiting.\n"); */
1993 		cleanup_socket();
1994 		_exit(2);
1995 	}
1996 }
1997 
1998 __dead static void
usage(void)1999 usage(void)
2000 {
2001 	fprintf(stderr,
2002 	    "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
2003 	    "                 [-O option] [-P allowed_providers] [-t life]\n"
2004 	    "       ssh-agent [-a bind_address] [-E fingerprint_hash] [-O option]\n"
2005 	    "                 [-P allowed_providers] [-t life] command [arg ...]\n"
2006 	    "       ssh-agent [-c | -s] -k\n");
2007 	exit(1);
2008 }
2009 
2010 static void
csh_setenv(const char * name,const char * value)2011 csh_setenv(const char *name, const char *value)
2012 {
2013 	printf("setenv %s %s;\n", name, value);
2014 }
2015 
2016 static void
csh_unsetenv(const char * name)2017 csh_unsetenv(const char *name)
2018 {
2019 	printf("unsetenv %s;\n", name);
2020 }
2021 
2022 static void
sh_setenv(const char * name,const char * value)2023 sh_setenv(const char *name, const char *value)
2024 {
2025 	printf("%s=%s; export %s;\n", name, value, name);
2026 }
2027 
2028 static void
sh_unsetenv(const char * name)2029 sh_unsetenv(const char *name)
2030 {
2031 	printf("unset %s;\n", name);
2032 }
2033 int
main(int ac,char ** av)2034 main(int ac, char **av)
2035 {
2036 	int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
2037 	int sock, ch, result, saved_errno;
2038 	char *shell, *pidstr, *agentsocket = NULL;
2039 	struct rlimit rlim;
2040 	void (*f_setenv)(const char *, const char *);
2041 	void (*f_unsetenv)(const char *);
2042 	extern int optind;
2043 	extern char *optarg;
2044 	pid_t pid;
2045 	char pidstrbuf[1 + 3 * sizeof pid];
2046 	size_t len;
2047 	mode_t prev_mask;
2048 	int timeout = -1; /* INFTIM */
2049 	struct pollfd *pfd = NULL;
2050 	size_t npfd = 0;
2051 	u_int maxfds;
2052 
2053 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2054 	sanitise_stdfd();
2055 
2056 	/* drop */
2057 	setegid(getgid());
2058 	setgid(getgid());
2059 
2060 	if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
2061 		fatal("%s: getrlimit: %s", __progname, strerror(errno));
2062 
2063 #ifdef WITH_OPENSSL
2064 	OpenSSL_add_all_algorithms();
2065 #endif
2066 
2067 	while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:")) != -1) {
2068 		switch (ch) {
2069 		case 'E':
2070 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
2071 			if (fingerprint_hash == -1)
2072 				fatal("Invalid hash algorithm \"%s\"", optarg);
2073 			break;
2074 		case 'c':
2075 			if (s_flag)
2076 				usage();
2077 			c_flag++;
2078 			break;
2079 		case 'k':
2080 			k_flag++;
2081 			break;
2082 		case 'O':
2083 			if (strcmp(optarg, "no-restrict-websafe") == 0)
2084 				restrict_websafe = 0;
2085 			else if (strcmp(optarg, "allow-remote-pkcs11") == 0)
2086 				remote_add_provider = 1;
2087 			else
2088 				fatal("Unknown -O option");
2089 			break;
2090 		case 'P':
2091 			if (allowed_providers != NULL)
2092 				fatal("-P option already specified");
2093 			allowed_providers = xstrdup(optarg);
2094 			break;
2095 		case 's':
2096 			if (c_flag)
2097 				usage();
2098 			s_flag++;
2099 			break;
2100 		case 'd':
2101 			if (d_flag || D_flag)
2102 				usage();
2103 			d_flag++;
2104 			break;
2105 		case 'D':
2106 			if (d_flag || D_flag)
2107 				usage();
2108 			D_flag++;
2109 			break;
2110 		case 'a':
2111 			agentsocket = optarg;
2112 			break;
2113 		case 't':
2114 			if ((lifetime = convtime(optarg)) == -1) {
2115 				fprintf(stderr, "Invalid lifetime\n");
2116 				usage();
2117 			}
2118 			break;
2119 		default:
2120 			usage();
2121 		}
2122 	}
2123 	ac -= optind;
2124 	av += optind;
2125 
2126 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
2127 		usage();
2128 
2129 	if (allowed_providers == NULL)
2130 		allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
2131 
2132 	if (ac == 0 && !c_flag && !s_flag) {
2133 		shell = getenv("SHELL");
2134 		if (shell != NULL && (len = strlen(shell)) > 2 &&
2135 		    strncmp(shell + len - 3, "csh", 3) == 0)
2136 			c_flag = 1;
2137 	}
2138 	if (c_flag) {
2139 		f_setenv = csh_setenv;
2140 		f_unsetenv = csh_unsetenv;
2141 	} else {
2142 		f_setenv = sh_setenv;
2143 		f_unsetenv = sh_unsetenv;
2144 	}
2145 	if (k_flag) {
2146 		const char *errstr = NULL;
2147 
2148 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
2149 		if (pidstr == NULL) {
2150 			fprintf(stderr, "%s not set, cannot kill agent\n",
2151 			    SSH_AGENTPID_ENV_NAME);
2152 			exit(1);
2153 		}
2154 		pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
2155 		if (errstr) {
2156 			fprintf(stderr,
2157 			    "%s=\"%s\", which is not a good PID: %s\n",
2158 			    SSH_AGENTPID_ENV_NAME, pidstr, errstr);
2159 			exit(1);
2160 		}
2161 		if (kill(pid, SIGTERM) == -1) {
2162 			perror("kill");
2163 			exit(1);
2164 		}
2165 		(*f_unsetenv)(SSH_AUTHSOCKET_ENV_NAME);
2166 		(*f_unsetenv)(SSH_AGENTPID_ENV_NAME);
2167 		printf("echo Agent pid %ld killed;\n", (long)pid);
2168 		exit(0);
2169 	}
2170 
2171 	/*
2172 	 * Minimum file descriptors:
2173 	 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
2174 	 * a few spare for libc / stack protectors / sanitisers, etc.
2175 	 */
2176 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
2177 	if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
2178 		fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
2179 		    __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
2180 	maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
2181 
2182 	parent_pid = getpid();
2183 
2184 	if (agentsocket == NULL) {
2185 		/* Create private directory for agent socket */
2186 		mktemp_proto(socket_dir, sizeof(socket_dir));
2187 		if (mkdtemp(socket_dir) == NULL) {
2188 			perror("mkdtemp: private socket dir");
2189 			exit(1);
2190 		}
2191 		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
2192 		    (long)parent_pid);
2193 	} else {
2194 		/* Try to use specified agent socket */
2195 		socket_dir[0] = '\0';
2196 		strlcpy(socket_name, agentsocket, sizeof socket_name);
2197 	}
2198 
2199 	/*
2200 	 * Create socket early so it will exist before command gets run from
2201 	 * the parent.
2202 	 */
2203 	prev_mask = umask(0177);
2204 	sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
2205 	if (sock < 0) {
2206 		/* XXX - unix_listener() calls error() not perror() */
2207 		*socket_name = '\0'; /* Don't unlink any existing file */
2208 		cleanup_exit(1);
2209 	}
2210 	umask(prev_mask);
2211 
2212 	/*
2213 	 * Fork, and have the parent execute the command, if any, or present
2214 	 * the socket data.  The child continues as the authentication agent.
2215 	 */
2216 	if (D_flag || d_flag) {
2217 		log_init(__progname,
2218 		    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2219 		    SYSLOG_FACILITY_AUTH, 1);
2220 		if (c_flag)
2221 			printf("setenv %s %s;\n",
2222 			    SSH_AUTHSOCKET_ENV_NAME, socket_name);
2223 		else
2224 			printf("%s=%s; export %s;\n",
2225 			    SSH_AUTHSOCKET_ENV_NAME, socket_name,
2226 			    SSH_AUTHSOCKET_ENV_NAME);
2227 		printf("echo Agent pid %ld;\n", (long)parent_pid);
2228 		fflush(stdout);
2229 		goto skip;
2230 	}
2231 	pid = fork();
2232 	if (pid == -1) {
2233 		perror("fork");
2234 		cleanup_exit(1);
2235 	}
2236 	if (pid != 0) {		/* Parent - execute the given command. */
2237 		close(sock);
2238 		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
2239 		if (ac == 0) {
2240 			(*f_setenv)(SSH_AUTHSOCKET_ENV_NAME, socket_name);
2241 			(*f_setenv)(SSH_AGENTPID_ENV_NAME, pidstrbuf);
2242 			printf("echo Agent pid %ld;\n", (long)pid);
2243 			exit(0);
2244 		}
2245 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
2246 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
2247 			perror("setenv");
2248 			exit(1);
2249 		}
2250 		execvp(av[0], av);
2251 		perror(av[0]);
2252 		exit(1);
2253 	}
2254 	/* child */
2255 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
2256 
2257 	if (setsid() == -1) {
2258 		error("setsid: %s", strerror(errno));
2259 		cleanup_exit(1);
2260 	}
2261 
2262 	(void)chdir("/");
2263 	if (stdfd_devnull(1, 1, 1) == -1)
2264 		error_f("stdfd_devnull failed");
2265 
2266 	/* deny core dumps, since memory contains unencrypted private keys */
2267 	rlim.rlim_cur = rlim.rlim_max = 0;
2268 	if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
2269 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
2270 		cleanup_exit(1);
2271 	}
2272 
2273 skip:
2274 
2275 	cleanup_pid = getpid();
2276 
2277 #ifdef ENABLE_PKCS11
2278 	pkcs11_init(0);
2279 #endif
2280 	new_socket(AUTH_SOCKET, sock);
2281 	if (ac > 0)
2282 		parent_alive_interval = 10;
2283 	idtab_init();
2284 	ssh_signal(SIGPIPE, SIG_IGN);
2285 	ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
2286 	ssh_signal(SIGHUP, cleanup_handler);
2287 	ssh_signal(SIGTERM, cleanup_handler);
2288 
2289 #ifdef __OpenBSD__
2290 	if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
2291 		fatal("%s: pledge: %s", __progname, strerror(errno));
2292 #endif
2293 
2294 	while (1) {
2295 		prepare_poll(&pfd, &npfd, &timeout, maxfds);
2296 		result = poll(pfd, npfd, timeout);
2297 		saved_errno = errno;
2298 		if (parent_alive_interval != 0)
2299 			check_parent_exists();
2300 		(void) reaper();	/* remove expired keys */
2301 		if (result == -1) {
2302 			if (saved_errno == EINTR)
2303 				continue;
2304 			fatal("poll: %s", strerror(saved_errno));
2305 		} else if (result > 0)
2306 			after_poll(pfd, npfd, maxfds);
2307 	}
2308 	/* NOTREACHED */
2309 }
2310