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