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