1 /* $OpenBSD: ssh-agent.c,v 1.278 2021/04/03 06:18:41 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/param.h>
41 #include <sys/resource.h>
42 #include <sys/stat.h>
43 #include <sys/socket.h>
44 #include <sys/wait.h>
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
47 #endif
48 #ifdef HAVE_SYS_UN_H
49 # include <sys/un.h>
50 #endif
51 #include "openbsd-compat/sys-queue.h"
52 
53 #ifdef WITH_OPENSSL
54 #include <openssl/evp.h>
55 #include "openbsd-compat/openssl-compat.h"
56 #endif
57 
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <limits.h>
61 #ifdef HAVE_PATHS_H
62 # include <paths.h>
63 #endif
64 #ifdef HAVE_POLL_H
65 # include <poll.h>
66 #endif
67 #include <signal.h>
68 #include <stdarg.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <time.h>
72 #include <string.h>
73 #include <unistd.h>
74 #ifdef HAVE_UTIL_H
75 # include <util.h>
76 #endif
77 
78 #include "xmalloc.h"
79 #include "ssh.h"
80 #include "ssh2.h"
81 #include "sshbuf.h"
82 #include "sshkey.h"
83 #include "authfd.h"
84 #include "compat.h"
85 #include "log.h"
86 #include "misc.h"
87 #include "digest.h"
88 #include "ssherr.h"
89 #include "match.h"
90 #include "msg.h"
91 #include "ssherr.h"
92 #include "pathnames.h"
93 #include "ssh-pkcs11.h"
94 #include "sk-api.h"
95 
96 #ifndef DEFAULT_ALLOWED_PROVIDERS
97 # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
98 #endif
99 
100 /* Maximum accepted message length */
101 #define AGENT_MAX_LEN	(256*1024)
102 /* Maximum bytes to read from client socket */
103 #define AGENT_RBUF_LEN	(4096)
104 
105 typedef enum {
106 	AUTH_UNUSED = 0,
107 	AUTH_SOCKET = 1,
108 	AUTH_CONNECTION = 2,
109 } sock_type;
110 
111 typedef struct socket_entry {
112 	int fd;
113 	sock_type type;
114 	struct sshbuf *input;
115 	struct sshbuf *output;
116 	struct sshbuf *request;
117 } SocketEntry;
118 
119 u_int sockets_alloc = 0;
120 SocketEntry *sockets = NULL;
121 
122 typedef struct identity {
123 	TAILQ_ENTRY(identity) next;
124 	struct sshkey *key;
125 	char *comment;
126 	char *provider;
127 	time_t death;
128 	u_int confirm;
129 	char *sk_provider;
130 } Identity;
131 
132 struct idtable {
133 	int nentries;
134 	TAILQ_HEAD(idqueue, identity) idlist;
135 };
136 
137 /* private key table */
138 struct idtable *idtab;
139 
140 int max_fd = 0;
141 
142 /* pid of shell == parent of agent */
143 pid_t parent_pid = -1;
144 time_t parent_alive_interval = 0;
145 
146 /* pid of process for which cleanup_socket is applicable */
147 pid_t cleanup_pid = 0;
148 
149 /* pathname and directory for AUTH_SOCKET */
150 char socket_name[PATH_MAX];
151 char socket_dir[PATH_MAX];
152 
153 /* Pattern-list of allowed PKCS#11/Security key paths */
154 static char *allowed_providers;
155 
156 /* locking */
157 #define LOCK_SIZE	32
158 #define LOCK_SALT_SIZE	16
159 #define LOCK_ROUNDS	1
160 int locked = 0;
161 u_char lock_pwhash[LOCK_SIZE];
162 u_char lock_salt[LOCK_SALT_SIZE];
163 
164 extern char *__progname;
165 
166 /* Default lifetime in seconds (0 == forever) */
167 static int lifetime = 0;
168 
169 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
170 
171 /* Refuse signing of non-SSH messages for web-origin FIDO keys */
172 static int restrict_websafe = 1;
173 
174 /*
175  * Client connection count; incremented in new_socket() and decremented in
176  * close_socket().  When it reaches 0, ssh-agent will exit.  Since it is
177  * normally initialized to 1, it will never reach 0.  However, if the -x
178  * option is specified, it is initialized to 0 in main(); in that case,
179  * ssh-agent will exit as soon as it has had at least one client but no
180  * longer has any.
181  */
182 static int xcount = 1;
183 
184 static void
close_socket(SocketEntry * e)185 close_socket(SocketEntry *e)
186 {
187 	int last = 0;
188 
189 	if (e->type == AUTH_CONNECTION) {
190 		debug("xcount %d -> %d", xcount, xcount - 1);
191 		if (--xcount == 0)
192 			last = 1;
193 	}
194 	close(e->fd);
195 	sshbuf_free(e->input);
196 	sshbuf_free(e->output);
197 	sshbuf_free(e->request);
198 	memset(e, '\0', sizeof(*e));
199 	e->fd = -1;
200 	e->type = AUTH_UNUSED;
201 	if (last)
202 		cleanup_exit(0);
203 }
204 
205 static void
idtab_init(void)206 idtab_init(void)
207 {
208 	idtab = xcalloc(1, sizeof(*idtab));
209 	TAILQ_INIT(&idtab->idlist);
210 	idtab->nentries = 0;
211 }
212 
213 static void
free_identity(Identity * id)214 free_identity(Identity *id)
215 {
216 	sshkey_free(id->key);
217 	free(id->provider);
218 	free(id->comment);
219 	free(id->sk_provider);
220 	free(id);
221 }
222 
223 /* return matching private key for given public key */
224 static Identity *
lookup_identity(struct sshkey * key)225 lookup_identity(struct sshkey *key)
226 {
227 	Identity *id;
228 
229 	TAILQ_FOREACH(id, &idtab->idlist, next) {
230 		if (sshkey_equal(key, id->key))
231 			return (id);
232 	}
233 	return (NULL);
234 }
235 
236 /* Check confirmation of keysign request */
237 static int
confirm_key(Identity * id,const char * extra)238 confirm_key(Identity *id, const char *extra)
239 {
240 	char *p;
241 	int ret = -1;
242 
243 	p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
244 	if (p != NULL &&
245 	    ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
246 	    id->comment, p,
247 	    extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
248 		ret = 0;
249 	free(p);
250 
251 	return (ret);
252 }
253 
254 static void
send_status(SocketEntry * e,int success)255 send_status(SocketEntry *e, int success)
256 {
257 	int r;
258 
259 	if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
260 	    (r = sshbuf_put_u8(e->output, success ?
261 	    SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
262 		fatal_fr(r, "compose");
263 }
264 
265 /* send list of supported public keys to 'client' */
266 static void
process_request_identities(SocketEntry * e)267 process_request_identities(SocketEntry *e)
268 {
269 	Identity *id;
270 	struct sshbuf *msg;
271 	int r;
272 
273 	debug2_f("entering");
274 
275 	if ((msg = sshbuf_new()) == NULL)
276 		fatal_f("sshbuf_new failed");
277 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
278 	    (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
279 		fatal_fr(r, "compose");
280 	TAILQ_FOREACH(id, &idtab->idlist, next) {
281 		if ((r = sshkey_puts_opts(id->key, msg,
282 		    SSHKEY_SERIALIZE_INFO)) != 0 ||
283 		    (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
284 			error_fr(r, "compose key/comment");
285 			continue;
286 		}
287 	}
288 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
289 		fatal_fr(r, "enqueue");
290 	sshbuf_free(msg);
291 }
292 
293 
294 static char *
agent_decode_alg(struct sshkey * key,u_int flags)295 agent_decode_alg(struct sshkey *key, u_int flags)
296 {
297 	if (key->type == KEY_RSA) {
298 		if (flags & SSH_AGENT_RSA_SHA2_256)
299 			return "rsa-sha2-256";
300 		else if (flags & SSH_AGENT_RSA_SHA2_512)
301 			return "rsa-sha2-512";
302 	} else if (key->type == KEY_RSA_CERT) {
303 		if (flags & SSH_AGENT_RSA_SHA2_256)
304 			return "rsa-sha2-256-cert-v01@openssh.com";
305 		else if (flags & SSH_AGENT_RSA_SHA2_512)
306 			return "rsa-sha2-512-cert-v01@openssh.com";
307 	}
308 	return NULL;
309 }
310 
311 /*
312  * Attempt to parse the contents of a buffer as a SSH publickey userauth
313  * request, checking its contents for consistency and matching the embedded
314  * key against the one that is being used for signing.
315  * Note: does not modify msg buffer.
316  * Optionally extract the username and session ID from the request.
317  */
318 static int
parse_userauth_request(struct sshbuf * msg,const struct sshkey * expected_key,char ** userp,struct sshbuf ** sess_idp)319 parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
320     char **userp, struct sshbuf **sess_idp)
321 {
322 	struct sshbuf *b = NULL, *sess_id = NULL;
323 	char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
324 	int r;
325 	u_char t, sig_follows;
326 	struct sshkey *mkey = NULL;
327 
328 	if (userp != NULL)
329 		*userp = NULL;
330 	if (sess_idp != NULL)
331 		*sess_idp = NULL;
332 	if ((b = sshbuf_fromb(msg)) == NULL)
333 		fatal_f("sshbuf_fromb");
334 
335 	/* SSH userauth request */
336 	if ((r = sshbuf_froms(b, &sess_id)) != 0)
337 		goto out;
338 	if (sshbuf_len(sess_id) == 0) {
339 		r = SSH_ERR_INVALID_FORMAT;
340 		goto out;
341 	}
342 	if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
343 	    (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
344 	    (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
345 	    (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
346 	    (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
347 	    (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
348 	    (r = sshkey_froms(b, &mkey)) != 0) /* key */
349 		goto out;
350 	if (t != SSH2_MSG_USERAUTH_REQUEST ||
351 	    sig_follows != 1 ||
352 	    strcmp(service, "ssh-connection") != 0 ||
353 	    !sshkey_equal(expected_key, mkey) ||
354 	    sshkey_type_from_name(pkalg) != expected_key->type) {
355 		r = SSH_ERR_INVALID_FORMAT;
356 		goto out;
357 	}
358 	if (strcmp(method, "publickey") != 0) {
359 		r = SSH_ERR_INVALID_FORMAT;
360 		goto out;
361 	}
362 	if (sshbuf_len(b) != 0) {
363 		r = SSH_ERR_INVALID_FORMAT;
364 		goto out;
365 	}
366 	/* success */
367 	r = 0;
368 	debug3_f("well formed userauth");
369 	if (userp != NULL) {
370 		*userp = user;
371 		user = NULL;
372 	}
373 	if (sess_idp != NULL) {
374 		*sess_idp = sess_id;
375 		sess_id = NULL;
376 	}
377  out:
378 	sshbuf_free(b);
379 	sshbuf_free(sess_id);
380 	free(user);
381 	free(service);
382 	free(method);
383 	free(pkalg);
384 	sshkey_free(mkey);
385 	return r;
386 }
387 
388 /*
389  * Attempt to parse the contents of a buffer as a SSHSIG signature request.
390  * Note: does not modify buffer.
391  */
392 static int
parse_sshsig_request(struct sshbuf * msg)393 parse_sshsig_request(struct sshbuf *msg)
394 {
395 	int r;
396 	struct sshbuf *b;
397 
398 	if ((b = sshbuf_fromb(msg)) == NULL)
399 		fatal_f("sshbuf_fromb");
400 
401 	if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
402 	    (r = sshbuf_consume(b, 6)) != 0 ||
403 	    (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
404 	    (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
405 	    (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
406 	    (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
407 		goto out;
408 	if (sshbuf_len(b) != 0) {
409 		r = SSH_ERR_INVALID_FORMAT;
410 		goto out;
411 	}
412 	/* success */
413 	r = 0;
414  out:
415 	sshbuf_free(b);
416 	return r;
417 }
418 
419 /*
420  * This function inspects a message to be signed by a FIDO key that has a
421  * web-like application string (i.e. one that does not begin with "ssh:".
422  * It checks that the message is one of those expected for SSH operations
423  * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
424  * for the web.
425  */
426 static int
check_websafe_message_contents(struct sshkey * key,struct sshbuf * data)427 check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
428 {
429 	if (parse_userauth_request(data, key, NULL, NULL) == 0) {
430 		debug_f("signed data matches public key userauth request");
431 		return 1;
432 	}
433 	if (parse_sshsig_request(data) == 0) {
434 		debug_f("signed data matches SSHSIG signature request");
435 		return 1;
436 	}
437 
438 	/* XXX check CA signature operation */
439 
440 	error("web-origin key attempting to sign non-SSH message");
441 	return 0;
442 }
443 
444 /* ssh2 only */
445 static void
process_sign_request2(SocketEntry * e)446 process_sign_request2(SocketEntry *e)
447 {
448 	u_char *signature = NULL;
449 	size_t slen = 0;
450 	u_int compat = 0, flags;
451 	int r, ok = -1;
452 	char *fp = NULL;
453 	struct sshbuf *msg = NULL, *data = NULL;
454 	struct sshkey *key = NULL;
455 	struct identity *id;
456 	struct notifier_ctx *notifier = NULL;
457 
458 	debug_f("entering");
459 
460 	if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
461 		fatal_f("sshbuf_new failed");
462 	if ((r = sshkey_froms(e->request, &key)) != 0 ||
463 	    (r = sshbuf_get_stringb(e->request, data)) != 0 ||
464 	    (r = sshbuf_get_u32(e->request, &flags)) != 0) {
465 		error_fr(r, "parse");
466 		goto send;
467 	}
468 
469 	if ((id = lookup_identity(key)) == NULL) {
470 		verbose_f("%s key not found", sshkey_type(key));
471 		goto send;
472 	}
473 	if (id->confirm && confirm_key(id, NULL) != 0) {
474 		verbose_f("user refused key");
475 		goto send;
476 	}
477 	if (sshkey_is_sk(id->key)) {
478 		if (strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
479 		    !check_websafe_message_contents(key, data)) {
480 			/* error already logged */
481 			goto send;
482 		}
483 		if ((id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
484 			if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
485 			    SSH_FP_DEFAULT)) == NULL)
486 				fatal_f("fingerprint failed");
487 			notifier = notify_start(0,
488 			    "Confirm user presence for key %s %s",
489 			    sshkey_type(id->key), fp);
490 		}
491 	}
492 	/* XXX support PIN required FIDO keys */
493 	if ((r = sshkey_sign(id->key, &signature, &slen,
494 	    sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
495 	    id->sk_provider, NULL, compat)) != 0) {
496 		error_fr(r, "sshkey_sign");
497 		goto send;
498 	}
499 	/* Success */
500 	ok = 0;
501  send:
502 	notify_complete(notifier, "User presence confirmed");
503 
504 	if (ok == 0) {
505 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
506 		    (r = sshbuf_put_string(msg, signature, slen)) != 0)
507 			fatal_fr(r, "compose");
508 	} else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
509 		fatal_fr(r, "compose failure");
510 
511 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
512 		fatal_fr(r, "enqueue");
513 
514 	sshbuf_free(data);
515 	sshbuf_free(msg);
516 	sshkey_free(key);
517 	free(fp);
518 	free(signature);
519 }
520 
521 /* shared */
522 static void
process_remove_identity(SocketEntry * e)523 process_remove_identity(SocketEntry *e)
524 {
525 	int r, success = 0;
526 	struct sshkey *key = NULL;
527 	Identity *id;
528 
529 	debug2_f("entering");
530 	if ((r = sshkey_froms(e->request, &key)) != 0) {
531 		error_fr(r, "parse key");
532 		goto done;
533 	}
534 	if ((id = lookup_identity(key)) == NULL) {
535 		debug_f("key not found");
536 		goto done;
537 	}
538 	/* We have this key, free it. */
539 	if (idtab->nentries < 1)
540 		fatal_f("internal error: nentries %d", idtab->nentries);
541 	TAILQ_REMOVE(&idtab->idlist, id, next);
542 	free_identity(id);
543 	idtab->nentries--;
544 	success = 1;
545  done:
546 	sshkey_free(key);
547 	send_status(e, success);
548 }
549 
550 static void
process_remove_all_identities(SocketEntry * e)551 process_remove_all_identities(SocketEntry *e)
552 {
553 	Identity *id;
554 
555 	debug2_f("entering");
556 	/* Loop over all identities and clear the keys. */
557 	for (id = TAILQ_FIRST(&idtab->idlist); id;
558 	    id = TAILQ_FIRST(&idtab->idlist)) {
559 		TAILQ_REMOVE(&idtab->idlist, id, next);
560 		free_identity(id);
561 	}
562 
563 	/* Mark that there are no identities. */
564 	idtab->nentries = 0;
565 
566 	/* Send success. */
567 	send_status(e, 1);
568 }
569 
570 /* removes expired keys and returns number of seconds until the next expiry */
571 static time_t
reaper(void)572 reaper(void)
573 {
574 	time_t deadline = 0, now = monotime();
575 	Identity *id, *nxt;
576 
577 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
578 		nxt = TAILQ_NEXT(id, next);
579 		if (id->death == 0)
580 			continue;
581 		if (now >= id->death) {
582 			debug("expiring key '%s'", id->comment);
583 			TAILQ_REMOVE(&idtab->idlist, id, next);
584 			free_identity(id);
585 			idtab->nentries--;
586 		} else
587 			deadline = (deadline == 0) ? id->death :
588 			    MINIMUM(deadline, id->death);
589 	}
590 	if (deadline == 0 || deadline <= now)
591 		return 0;
592 	else
593 		return (deadline - now);
594 }
595 
596 static int
parse_key_constraint_extension(struct sshbuf * m,char ** sk_providerp)597 parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp)
598 {
599 	char *ext_name = NULL;
600 	int r;
601 
602 	if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
603 		error_fr(r, "parse constraint extension");
604 		goto out;
605 	}
606 	debug_f("constraint ext %s", ext_name);
607 	if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
608 		if (sk_providerp == NULL) {
609 			error_f("%s not valid here", ext_name);
610 			r = SSH_ERR_INVALID_FORMAT;
611 			goto out;
612 		}
613 		if (*sk_providerp != NULL) {
614 			error_f("%s already set", ext_name);
615 			r = SSH_ERR_INVALID_FORMAT;
616 			goto out;
617 		}
618 		if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
619 			error_fr(r, "parse %s", ext_name);
620 			goto out;
621 		}
622 	} else {
623 		error_f("unsupported constraint \"%s\"", ext_name);
624 		r = SSH_ERR_FEATURE_UNSUPPORTED;
625 		goto out;
626 	}
627 	/* success */
628 	r = 0;
629  out:
630 	free(ext_name);
631 	return r;
632 }
633 
634 static int
parse_key_constraints(struct sshbuf * m,struct sshkey * k,time_t * deathp,u_int * secondsp,int * confirmp,char ** sk_providerp)635 parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
636     u_int *secondsp, int *confirmp, char **sk_providerp)
637 {
638 	u_char ctype;
639 	int r;
640 	u_int seconds, maxsign = 0;
641 
642 	while (sshbuf_len(m)) {
643 		if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
644 			error_fr(r, "parse constraint type");
645 			goto out;
646 		}
647 		switch (ctype) {
648 		case SSH_AGENT_CONSTRAIN_LIFETIME:
649 			if (*deathp != 0) {
650 				error_f("lifetime already set");
651 				r = SSH_ERR_INVALID_FORMAT;
652 				goto out;
653 			}
654 			if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
655 				error_fr(r, "parse lifetime constraint");
656 				goto out;
657 			}
658 			*deathp = monotime() + seconds;
659 			*secondsp = seconds;
660 			break;
661 		case SSH_AGENT_CONSTRAIN_CONFIRM:
662 			if (*confirmp != 0) {
663 				error_f("confirm already set");
664 				r = SSH_ERR_INVALID_FORMAT;
665 				goto out;
666 			}
667 			*confirmp = 1;
668 			break;
669 		case SSH_AGENT_CONSTRAIN_MAXSIGN:
670 			if (k == NULL) {
671 				error_f("maxsign not valid here");
672 				r = SSH_ERR_INVALID_FORMAT;
673 				goto out;
674 			}
675 			if (maxsign != 0) {
676 				error_f("maxsign already set");
677 				r = SSH_ERR_INVALID_FORMAT;
678 				goto out;
679 			}
680 			if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
681 				error_fr(r, "parse maxsign constraint");
682 				goto out;
683 			}
684 			if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
685 				error_fr(r, "enable maxsign");
686 				goto out;
687 			}
688 			break;
689 		case SSH_AGENT_CONSTRAIN_EXTENSION:
690 			if ((r = parse_key_constraint_extension(m,
691 			    sk_providerp)) != 0)
692 				goto out; /* error already logged */
693 			break;
694 		default:
695 			error_f("Unknown constraint %d", ctype);
696 			r = SSH_ERR_FEATURE_UNSUPPORTED;
697 			goto out;
698 		}
699 	}
700 	/* success */
701 	r = 0;
702  out:
703 	return r;
704 }
705 
706 static void
process_add_identity(SocketEntry * e)707 process_add_identity(SocketEntry *e)
708 {
709 	Identity *id;
710 	int success = 0, confirm = 0;
711 	char *fp, *comment = NULL, *sk_provider = NULL;
712 	char canonical_provider[PATH_MAX];
713 	time_t death = 0;
714 	u_int seconds = 0;
715 	struct sshkey *k = NULL;
716 	int r = SSH_ERR_INTERNAL_ERROR;
717 
718 	debug2_f("entering");
719 	if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
720 	    k == NULL ||
721 	    (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
722 		error_fr(r, "parse");
723 		goto out;
724 	}
725 	if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
726 	    &sk_provider) != 0) {
727 		error_f("failed to parse constraints");
728 		sshbuf_reset(e->request);
729 		goto out;
730 	}
731 
732 	if (sk_provider != NULL) {
733 		if (!sshkey_is_sk(k)) {
734 			error("Cannot add provider: %s is not an "
735 			    "authenticator-hosted key", sshkey_type(k));
736 			goto out;
737 		}
738 		if (strcasecmp(sk_provider, "internal") == 0) {
739 			debug_f("internal provider");
740 		} else {
741 			if (realpath(sk_provider, canonical_provider) == NULL) {
742 				verbose("failed provider \"%.100s\": "
743 				    "realpath: %s", sk_provider,
744 				    strerror(errno));
745 				goto out;
746 			}
747 			free(sk_provider);
748 			sk_provider = xstrdup(canonical_provider);
749 			if (match_pattern_list(sk_provider,
750 			    allowed_providers, 0) != 1) {
751 				error("Refusing add key: "
752 				    "provider %s not allowed", sk_provider);
753 				goto out;
754 			}
755 		}
756 	}
757 	if ((r = sshkey_shield_private(k)) != 0) {
758 		error_fr(r, "shield private");
759 		goto out;
760 	}
761 	if (lifetime && !death)
762 		death = monotime() + lifetime;
763 	if ((id = lookup_identity(k)) == NULL) {
764 		id = xcalloc(1, sizeof(Identity));
765 		TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
766 		/* Increment the number of identities. */
767 		idtab->nentries++;
768 	} else {
769 		/* key state might have been updated */
770 		sshkey_free(id->key);
771 		free(id->comment);
772 		free(id->sk_provider);
773 	}
774 	/* success */
775 	id->key = k;
776 	id->comment = comment;
777 	id->death = death;
778 	id->confirm = confirm;
779 	id->sk_provider = sk_provider;
780 
781 	if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
782 	    SSH_FP_DEFAULT)) == NULL)
783 		fatal_f("sshkey_fingerprint failed");
784 	debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
785 	    "(provider: %s)", sshkey_ssh_name(k), fp, comment, seconds,
786 	    confirm, sk_provider == NULL ? "none" : sk_provider);
787 	free(fp);
788 	/* transferred */
789 	k = NULL;
790 	comment = NULL;
791 	sk_provider = NULL;
792 	success = 1;
793  out:
794 	free(sk_provider);
795 	free(comment);
796 	sshkey_free(k);
797 	send_status(e, success);
798 }
799 
800 /* XXX todo: encrypt sensitive data with passphrase */
801 static void
process_lock_agent(SocketEntry * e,int lock)802 process_lock_agent(SocketEntry *e, int lock)
803 {
804 	int r, success = 0, delay;
805 	char *passwd;
806 	u_char passwdhash[LOCK_SIZE];
807 	static u_int fail_count = 0;
808 	size_t pwlen;
809 
810 	debug2_f("entering");
811 	/*
812 	 * This is deliberately fatal: the user has requested that we lock,
813 	 * but we can't parse their request properly. The only safe thing to
814 	 * do is abort.
815 	 */
816 	if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
817 		fatal_fr(r, "parse");
818 	if (pwlen == 0) {
819 		debug("empty password not supported");
820 	} else if (locked && !lock) {
821 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
822 		    passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
823 			fatal("bcrypt_pbkdf");
824 		if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
825 			debug("agent unlocked");
826 			locked = 0;
827 			fail_count = 0;
828 			explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
829 			success = 1;
830 		} else {
831 			/* delay in 0.1s increments up to 10s */
832 			if (fail_count < 100)
833 				fail_count++;
834 			delay = 100000 * fail_count;
835 			debug("unlock failed, delaying %0.1lf seconds",
836 			    (double)delay/1000000);
837 			usleep(delay);
838 		}
839 		explicit_bzero(passwdhash, sizeof(passwdhash));
840 	} else if (!locked && lock) {
841 		debug("agent locked");
842 		locked = 1;
843 		arc4random_buf(lock_salt, sizeof(lock_salt));
844 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
845 		    lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
846 			fatal("bcrypt_pbkdf");
847 		success = 1;
848 	}
849 	freezero(passwd, pwlen);
850 	send_status(e, success);
851 }
852 
853 static void
no_identities(SocketEntry * e)854 no_identities(SocketEntry *e)
855 {
856 	struct sshbuf *msg;
857 	int r;
858 
859 	if ((msg = sshbuf_new()) == NULL)
860 		fatal_f("sshbuf_new failed");
861 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
862 	    (r = sshbuf_put_u32(msg, 0)) != 0 ||
863 	    (r = sshbuf_put_stringb(e->output, msg)) != 0)
864 		fatal_fr(r, "compose");
865 	sshbuf_free(msg);
866 }
867 
868 #ifdef ENABLE_PKCS11
869 static void
process_add_smartcard_key(SocketEntry * e)870 process_add_smartcard_key(SocketEntry *e)
871 {
872 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
873 	char **comments = NULL;
874 	int r, i, count = 0, success = 0, confirm = 0;
875 	u_int seconds = 0;
876 	time_t death = 0;
877 	struct sshkey **keys = NULL, *k;
878 	Identity *id;
879 
880 	debug2_f("entering");
881 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
882 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
883 		error_fr(r, "parse");
884 		goto send;
885 	}
886 	if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
887 	    NULL) != 0) {
888 		error_f("failed to parse constraints");
889 		goto send;
890 	}
891 	if (realpath(provider, canonical_provider) == NULL) {
892 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
893 		    provider, strerror(errno));
894 		goto send;
895 	}
896 	if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
897 		verbose("refusing PKCS#11 add of \"%.100s\": "
898 		    "provider not allowed", canonical_provider);
899 		goto send;
900 	}
901 	debug_f("add %.100s", canonical_provider);
902 	if (lifetime && !death)
903 		death = monotime() + lifetime;
904 
905 	count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
906 	for (i = 0; i < count; i++) {
907 		k = keys[i];
908 		if (lookup_identity(k) == NULL) {
909 			id = xcalloc(1, sizeof(Identity));
910 			id->key = k;
911 			keys[i] = NULL; /* transferred */
912 			id->provider = xstrdup(canonical_provider);
913 			if (*comments[i] != '\0') {
914 				id->comment = comments[i];
915 				comments[i] = NULL; /* transferred */
916 			} else {
917 				id->comment = xstrdup(canonical_provider);
918 			}
919 			id->death = death;
920 			id->confirm = confirm;
921 			TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
922 			idtab->nentries++;
923 			success = 1;
924 		}
925 		/* XXX update constraints for existing keys */
926 		sshkey_free(keys[i]);
927 		free(comments[i]);
928 	}
929 send:
930 	free(pin);
931 	free(provider);
932 	free(keys);
933 	free(comments);
934 	send_status(e, success);
935 }
936 
937 static void
process_remove_smartcard_key(SocketEntry * e)938 process_remove_smartcard_key(SocketEntry *e)
939 {
940 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
941 	int r, success = 0;
942 	Identity *id, *nxt;
943 
944 	debug2_f("entering");
945 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
946 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
947 		error_fr(r, "parse");
948 		goto send;
949 	}
950 	free(pin);
951 
952 	if (realpath(provider, canonical_provider) == NULL) {
953 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
954 		    provider, strerror(errno));
955 		goto send;
956 	}
957 
958 	debug_f("remove %.100s", canonical_provider);
959 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
960 		nxt = TAILQ_NEXT(id, next);
961 		/* Skip file--based keys */
962 		if (id->provider == NULL)
963 			continue;
964 		if (!strcmp(canonical_provider, id->provider)) {
965 			TAILQ_REMOVE(&idtab->idlist, id, next);
966 			free_identity(id);
967 			idtab->nentries--;
968 		}
969 	}
970 	if (pkcs11_del_provider(canonical_provider) == 0)
971 		success = 1;
972 	else
973 		error_f("pkcs11_del_provider failed");
974 send:
975 	free(provider);
976 	send_status(e, success);
977 }
978 #endif /* ENABLE_PKCS11 */
979 
980 /*
981  * dispatch incoming message.
982  * returns 1 on success, 0 for incomplete messages or -1 on error.
983  */
984 static int
process_message(u_int socknum)985 process_message(u_int socknum)
986 {
987 	u_int msg_len;
988 	u_char type;
989 	const u_char *cp;
990 	int r;
991 	SocketEntry *e;
992 
993 	if (socknum >= sockets_alloc)
994 		fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
995 	e = &sockets[socknum];
996 
997 	if (sshbuf_len(e->input) < 5)
998 		return 0;		/* Incomplete message header. */
999 	cp = sshbuf_ptr(e->input);
1000 	msg_len = PEEK_U32(cp);
1001 	if (msg_len > AGENT_MAX_LEN) {
1002 		debug_f("socket %u (fd=%d) message too long %u > %u",
1003 		    socknum, e->fd, msg_len, AGENT_MAX_LEN);
1004 		return -1;
1005 	}
1006 	if (sshbuf_len(e->input) < msg_len + 4)
1007 		return 0;		/* Incomplete message body. */
1008 
1009 	/* move the current input to e->request */
1010 	sshbuf_reset(e->request);
1011 	if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1012 	    (r = sshbuf_get_u8(e->request, &type)) != 0) {
1013 		if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1014 		    r == SSH_ERR_STRING_TOO_LARGE) {
1015 			error_fr(r, "parse");
1016 			return -1;
1017 		}
1018 		fatal_fr(r, "parse");
1019 	}
1020 
1021 	debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1022 
1023 	/* check whether agent is locked */
1024 	if (locked && type != SSH_AGENTC_UNLOCK) {
1025 		sshbuf_reset(e->request);
1026 		switch (type) {
1027 		case SSH2_AGENTC_REQUEST_IDENTITIES:
1028 			/* send empty lists */
1029 			no_identities(e);
1030 			break;
1031 		default:
1032 			/* send a fail message for all other request types */
1033 			send_status(e, 0);
1034 		}
1035 		return 1;
1036 	}
1037 
1038 	switch (type) {
1039 	case SSH_AGENTC_LOCK:
1040 	case SSH_AGENTC_UNLOCK:
1041 		process_lock_agent(e, type == SSH_AGENTC_LOCK);
1042 		break;
1043 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1044 		process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1045 		break;
1046 	/* ssh2 */
1047 	case SSH2_AGENTC_SIGN_REQUEST:
1048 		process_sign_request2(e);
1049 		break;
1050 	case SSH2_AGENTC_REQUEST_IDENTITIES:
1051 		process_request_identities(e);
1052 		break;
1053 	case SSH2_AGENTC_ADD_IDENTITY:
1054 	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1055 		process_add_identity(e);
1056 		break;
1057 	case SSH2_AGENTC_REMOVE_IDENTITY:
1058 		process_remove_identity(e);
1059 		break;
1060 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1061 		process_remove_all_identities(e);
1062 		break;
1063 #ifdef ENABLE_PKCS11
1064 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
1065 	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1066 		process_add_smartcard_key(e);
1067 		break;
1068 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1069 		process_remove_smartcard_key(e);
1070 		break;
1071 #endif /* ENABLE_PKCS11 */
1072 	default:
1073 		/* Unknown message.  Respond with failure. */
1074 		error("Unknown message %d", type);
1075 		sshbuf_reset(e->request);
1076 		send_status(e, 0);
1077 		break;
1078 	}
1079 	return 1;
1080 }
1081 
1082 static void
new_socket(sock_type type,int fd)1083 new_socket(sock_type type, int fd)
1084 {
1085 	u_int i, old_alloc, new_alloc;
1086 
1087 	debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1088 	    (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1089 	if (type == AUTH_CONNECTION) {
1090 		debug("xcount %d -> %d", xcount, xcount + 1);
1091 		++xcount;
1092 	}
1093 	set_nonblock(fd);
1094 
1095 	if (fd > max_fd)
1096 		max_fd = fd;
1097 
1098 	for (i = 0; i < sockets_alloc; i++)
1099 		if (sockets[i].type == AUTH_UNUSED) {
1100 			sockets[i].fd = fd;
1101 			if ((sockets[i].input = sshbuf_new()) == NULL ||
1102 			    (sockets[i].output = sshbuf_new()) == NULL ||
1103 			    (sockets[i].request = sshbuf_new()) == NULL)
1104 				fatal_f("sshbuf_new failed");
1105 			sockets[i].type = type;
1106 			return;
1107 		}
1108 	old_alloc = sockets_alloc;
1109 	new_alloc = sockets_alloc + 10;
1110 	sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1111 	    sizeof(sockets[0]));
1112 	for (i = old_alloc; i < new_alloc; i++)
1113 		sockets[i].type = AUTH_UNUSED;
1114 	sockets_alloc = new_alloc;
1115 	sockets[old_alloc].fd = fd;
1116 	if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1117 	    (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1118 	    (sockets[old_alloc].request = sshbuf_new()) == NULL)
1119 		fatal_f("sshbuf_new failed");
1120 	sockets[old_alloc].type = type;
1121 }
1122 
1123 static int
handle_socket_read(u_int socknum)1124 handle_socket_read(u_int socknum)
1125 {
1126 	struct sockaddr_un sunaddr;
1127 	socklen_t slen;
1128 	uid_t euid;
1129 	gid_t egid;
1130 	int fd;
1131 
1132 	slen = sizeof(sunaddr);
1133 	fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1134 	if (fd == -1) {
1135 		error("accept from AUTH_SOCKET: %s", strerror(errno));
1136 		return -1;
1137 	}
1138 	if (getpeereid(fd, &euid, &egid) == -1) {
1139 		error("getpeereid %d failed: %s", fd, strerror(errno));
1140 		close(fd);
1141 		return -1;
1142 	}
1143 	if ((euid != 0) && (getuid() != euid)) {
1144 		error("uid mismatch: peer euid %u != uid %u",
1145 		    (u_int) euid, (u_int) getuid());
1146 		close(fd);
1147 		return -1;
1148 	}
1149 	new_socket(AUTH_CONNECTION, fd);
1150 	return 0;
1151 }
1152 
1153 static int
handle_conn_read(u_int socknum)1154 handle_conn_read(u_int socknum)
1155 {
1156 	char buf[AGENT_RBUF_LEN];
1157 	ssize_t len;
1158 	int r;
1159 
1160 	if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1161 		if (len == -1) {
1162 			if (errno == EAGAIN || errno == EINTR)
1163 				return 0;
1164 			error_f("read error on socket %u (fd %d): %s",
1165 			    socknum, sockets[socknum].fd, strerror(errno));
1166 		}
1167 		return -1;
1168 	}
1169 	if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1170 		fatal_fr(r, "compose");
1171 	explicit_bzero(buf, sizeof(buf));
1172 	for (;;) {
1173 		if ((r = process_message(socknum)) == -1)
1174 			return -1;
1175 		else if (r == 0)
1176 			break;
1177 	}
1178 	return 0;
1179 }
1180 
1181 static int
handle_conn_write(u_int socknum)1182 handle_conn_write(u_int socknum)
1183 {
1184 	ssize_t len;
1185 	int r;
1186 
1187 	if (sshbuf_len(sockets[socknum].output) == 0)
1188 		return 0; /* shouldn't happen */
1189 	if ((len = write(sockets[socknum].fd,
1190 	    sshbuf_ptr(sockets[socknum].output),
1191 	    sshbuf_len(sockets[socknum].output))) <= 0) {
1192 		if (len == -1) {
1193 			if (errno == EAGAIN || errno == EINTR)
1194 				return 0;
1195 			error_f("read error on socket %u (fd %d): %s",
1196 			    socknum, sockets[socknum].fd, strerror(errno));
1197 		}
1198 		return -1;
1199 	}
1200 	if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
1201 		fatal_fr(r, "consume");
1202 	return 0;
1203 }
1204 
1205 static void
after_poll(struct pollfd * pfd,size_t npfd,u_int maxfds)1206 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
1207 {
1208 	size_t i;
1209 	u_int socknum, activefds = npfd;
1210 
1211 	for (i = 0; i < npfd; i++) {
1212 		if (pfd[i].revents == 0)
1213 			continue;
1214 		/* Find sockets entry */
1215 		for (socknum = 0; socknum < sockets_alloc; socknum++) {
1216 			if (sockets[socknum].type != AUTH_SOCKET &&
1217 			    sockets[socknum].type != AUTH_CONNECTION)
1218 				continue;
1219 			if (pfd[i].fd == sockets[socknum].fd)
1220 				break;
1221 		}
1222 		if (socknum >= sockets_alloc) {
1223 			error_f("no socket for fd %d", pfd[i].fd);
1224 			continue;
1225 		}
1226 		/* Process events */
1227 		switch (sockets[socknum].type) {
1228 		case AUTH_SOCKET:
1229 			if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
1230 				break;
1231 			if (npfd > maxfds) {
1232 				debug3("out of fds (active %u >= limit %u); "
1233 				    "skipping accept", activefds, maxfds);
1234 				break;
1235 			}
1236 			if (handle_socket_read(socknum) == 0)
1237 				activefds++;
1238 			break;
1239 		case AUTH_CONNECTION:
1240 			if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
1241 			    handle_conn_read(socknum) != 0) {
1242 				goto close_sock;
1243 			}
1244 			if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
1245 			    handle_conn_write(socknum) != 0) {
1246  close_sock:
1247 				if (activefds == 0)
1248 					fatal("activefds == 0 at close_sock");
1249 				close_socket(&sockets[socknum]);
1250 				activefds--;
1251 				break;
1252 			}
1253 			break;
1254 		default:
1255 			break;
1256 		}
1257 	}
1258 }
1259 
1260 static int
prepare_poll(struct pollfd ** pfdp,size_t * npfdp,int * timeoutp,u_int maxfds)1261 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1262 {
1263 	struct pollfd *pfd = *pfdp;
1264 	size_t i, j, npfd = 0;
1265 	time_t deadline;
1266 	int r;
1267 
1268 	/* Count active sockets */
1269 	for (i = 0; i < sockets_alloc; i++) {
1270 		switch (sockets[i].type) {
1271 		case AUTH_SOCKET:
1272 		case AUTH_CONNECTION:
1273 			npfd++;
1274 			break;
1275 		case AUTH_UNUSED:
1276 			break;
1277 		default:
1278 			fatal("Unknown socket type %d", sockets[i].type);
1279 			break;
1280 		}
1281 	}
1282 	if (npfd != *npfdp &&
1283 	    (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1284 		fatal_f("recallocarray failed");
1285 	*pfdp = pfd;
1286 	*npfdp = npfd;
1287 
1288 	for (i = j = 0; i < sockets_alloc; i++) {
1289 		switch (sockets[i].type) {
1290 		case AUTH_SOCKET:
1291 			if (npfd > maxfds) {
1292 				debug3("out of fds (active %zu >= limit %u); "
1293 				    "skipping arming listener", npfd, maxfds);
1294 				break;
1295 			}
1296 			pfd[j].fd = sockets[i].fd;
1297 			pfd[j].revents = 0;
1298 			pfd[j].events = POLLIN;
1299 			j++;
1300 			break;
1301 		case AUTH_CONNECTION:
1302 			pfd[j].fd = sockets[i].fd;
1303 			pfd[j].revents = 0;
1304 			/*
1305 			 * Only prepare to read if we can handle a full-size
1306 			 * input read buffer and enqueue a max size reply..
1307 			 */
1308 			if ((r = sshbuf_check_reserve(sockets[i].input,
1309 			    AGENT_RBUF_LEN)) == 0 &&
1310 			    (r = sshbuf_check_reserve(sockets[i].output,
1311 			    AGENT_MAX_LEN)) == 0)
1312 				pfd[j].events = POLLIN;
1313 			else if (r != SSH_ERR_NO_BUFFER_SPACE)
1314 				fatal_fr(r, "reserve");
1315 			if (sshbuf_len(sockets[i].output) > 0)
1316 				pfd[j].events |= POLLOUT;
1317 			j++;
1318 			break;
1319 		default:
1320 			break;
1321 		}
1322 	}
1323 	deadline = reaper();
1324 	if (parent_alive_interval != 0)
1325 		deadline = (deadline == 0) ? parent_alive_interval :
1326 		    MINIMUM(deadline, parent_alive_interval);
1327 	if (deadline == 0) {
1328 		*timeoutp = -1; /* INFTIM */
1329 	} else {
1330 		if (deadline > INT_MAX / 1000)
1331 			*timeoutp = INT_MAX / 1000;
1332 		else
1333 			*timeoutp = deadline * 1000;
1334 	}
1335 	return (1);
1336 }
1337 
1338 static void
cleanup_socket(void)1339 cleanup_socket(void)
1340 {
1341 	if (cleanup_pid != 0 && getpid() != cleanup_pid)
1342 		return;
1343 	debug_f("cleanup");
1344 	if (socket_name[0])
1345 		unlink(socket_name);
1346 	if (socket_dir[0])
1347 		rmdir(socket_dir);
1348 }
1349 
1350 void
cleanup_exit(int i)1351 cleanup_exit(int i)
1352 {
1353 	cleanup_socket();
1354 	_exit(i);
1355 }
1356 
1357 /*ARGSUSED*/
1358 static void
cleanup_handler(int sig)1359 cleanup_handler(int sig)
1360 {
1361 	cleanup_socket();
1362 #ifdef ENABLE_PKCS11
1363 	pkcs11_terminate();
1364 #endif
1365 	_exit(2);
1366 }
1367 
1368 static void
check_parent_exists(void)1369 check_parent_exists(void)
1370 {
1371 	/*
1372 	 * If our parent has exited then getppid() will return (pid_t)1,
1373 	 * so testing for that should be safe.
1374 	 */
1375 	if (parent_pid != -1 && getppid() != parent_pid) {
1376 		/* printf("Parent has died - Authentication agent exiting.\n"); */
1377 		cleanup_socket();
1378 		_exit(2);
1379 	}
1380 }
1381 
1382 static void
usage(void)1383 usage(void)
1384 {
1385 	fprintf(stderr,
1386 	    "usage: ssh-agent [-c | -s] [-Ddx] [-a bind_address] [-E fingerprint_hash]\n"
1387 	    "                 [-P allowed_providers] [-t life]\n"
1388 	    "       ssh-agent [-a bind_address] [-E fingerprint_hash] [-P allowed_providers]\n"
1389 	    "                 [-t life] command [arg ...]\n"
1390 	    "       ssh-agent [-c | -s] -k\n");
1391 	exit(1);
1392 }
1393 
1394 int
main(int ac,char ** av)1395 main(int ac, char **av)
1396 {
1397 	int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1398 	int sock, ch, result, saved_errno;
1399 	char *shell, *format, *pidstr, *agentsocket = NULL;
1400 #ifdef HAVE_SETRLIMIT
1401 	struct rlimit rlim;
1402 #endif
1403 	extern int optind;
1404 	extern char *optarg;
1405 	pid_t pid;
1406 	char pidstrbuf[1 + 3 * sizeof pid];
1407 	size_t len;
1408 	mode_t prev_mask;
1409 	int timeout = -1; /* INFTIM */
1410 	struct pollfd *pfd = NULL;
1411 	size_t npfd = 0;
1412 	u_int maxfds;
1413 
1414 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1415 	sanitise_stdfd();
1416 
1417 	/* drop */
1418 	setegid(getgid());
1419 	setgid(getgid());
1420 	setuid(geteuid());
1421 
1422 	platform_disable_tracing(0);	/* strict=no */
1423 
1424 #ifdef RLIMIT_NOFILE
1425 	if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
1426 		fatal("%s: getrlimit: %s", __progname, strerror(errno));
1427 #endif
1428 
1429 	__progname = ssh_get_progname(av[0]);
1430 	seed_rng();
1431 
1432 	while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:x")) != -1) {
1433 		switch (ch) {
1434 		case 'E':
1435 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
1436 			if (fingerprint_hash == -1)
1437 				fatal("Invalid hash algorithm \"%s\"", optarg);
1438 			break;
1439 		case 'c':
1440 			if (s_flag)
1441 				usage();
1442 			c_flag++;
1443 			break;
1444 		case 'k':
1445 			k_flag++;
1446 			break;
1447 		case 'O':
1448 			if (strcmp(optarg, "no-restrict-websafe") == 0)
1449 				restrict_websafe  = 0;
1450 			else
1451 				fatal("Unknown -O option");
1452 			break;
1453 		case 'P':
1454 			if (allowed_providers != NULL)
1455 				fatal("-P option already specified");
1456 			allowed_providers = xstrdup(optarg);
1457 			break;
1458 		case 's':
1459 			if (c_flag)
1460 				usage();
1461 			s_flag++;
1462 			break;
1463 		case 'd':
1464 			if (d_flag || D_flag)
1465 				usage();
1466 			d_flag++;
1467 			break;
1468 		case 'D':
1469 			if (d_flag || D_flag)
1470 				usage();
1471 			D_flag++;
1472 			break;
1473 		case 'a':
1474 			agentsocket = optarg;
1475 			break;
1476 		case 't':
1477 			if ((lifetime = convtime(optarg)) == -1) {
1478 				fprintf(stderr, "Invalid lifetime\n");
1479 				usage();
1480 			}
1481 			break;
1482 		case 'x':
1483 			xcount = 0;
1484 			break;
1485 		default:
1486 			usage();
1487 		}
1488 	}
1489 	ac -= optind;
1490 	av += optind;
1491 
1492 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1493 		usage();
1494 
1495 	if (allowed_providers == NULL)
1496 		allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
1497 
1498 	if (ac == 0 && !c_flag && !s_flag) {
1499 		shell = getenv("SHELL");
1500 		if (shell != NULL && (len = strlen(shell)) > 2 &&
1501 		    strncmp(shell + len - 3, "csh", 3) == 0)
1502 			c_flag = 1;
1503 	}
1504 	if (k_flag) {
1505 		const char *errstr = NULL;
1506 
1507 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1508 		if (pidstr == NULL) {
1509 			fprintf(stderr, "%s not set, cannot kill agent\n",
1510 			    SSH_AGENTPID_ENV_NAME);
1511 			exit(1);
1512 		}
1513 		pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1514 		if (errstr) {
1515 			fprintf(stderr,
1516 			    "%s=\"%s\", which is not a good PID: %s\n",
1517 			    SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1518 			exit(1);
1519 		}
1520 		if (kill(pid, SIGTERM) == -1) {
1521 			perror("kill");
1522 			exit(1);
1523 		}
1524 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1525 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
1526 		printf(format, SSH_AGENTPID_ENV_NAME);
1527 		printf("echo Agent pid %ld killed;\n", (long)pid);
1528 		exit(0);
1529 	}
1530 
1531 	/*
1532 	 * Minimum file descriptors:
1533 	 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
1534 	 * a few spare for libc / stack protectors / sanitisers, etc.
1535 	 */
1536 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
1537 	if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1538 		fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
1539 		    __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
1540 	maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
1541 
1542 	parent_pid = getpid();
1543 
1544 	if (agentsocket == NULL) {
1545 		/* Create private directory for agent socket */
1546 		mktemp_proto(socket_dir, sizeof(socket_dir));
1547 		if (mkdtemp(socket_dir) == NULL) {
1548 			perror("mkdtemp: private socket dir");
1549 			exit(1);
1550 		}
1551 		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1552 		    (long)parent_pid);
1553 	} else {
1554 		/* Try to use specified agent socket */
1555 		socket_dir[0] = '\0';
1556 		strlcpy(socket_name, agentsocket, sizeof socket_name);
1557 	}
1558 
1559 	/*
1560 	 * Create socket early so it will exist before command gets run from
1561 	 * the parent.
1562 	 */
1563 	prev_mask = umask(0177);
1564 	sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1565 	if (sock < 0) {
1566 		/* XXX - unix_listener() calls error() not perror() */
1567 		*socket_name = '\0'; /* Don't unlink any existing file */
1568 		cleanup_exit(1);
1569 	}
1570 	umask(prev_mask);
1571 
1572 	/*
1573 	 * Fork, and have the parent execute the command, if any, or present
1574 	 * the socket data.  The child continues as the authentication agent.
1575 	 */
1576 	if (D_flag || d_flag) {
1577 		log_init(__progname,
1578 		    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1579 		    SYSLOG_FACILITY_AUTH, 1);
1580 		format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1581 		printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1582 		    SSH_AUTHSOCKET_ENV_NAME);
1583 		printf("echo Agent pid %ld;\n", (long)parent_pid);
1584 		fflush(stdout);
1585 		goto skip;
1586 	}
1587 	pid = fork();
1588 	if (pid == -1) {
1589 		perror("fork");
1590 		cleanup_exit(1);
1591 	}
1592 	if (pid != 0) {		/* Parent - execute the given command. */
1593 		close(sock);
1594 		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1595 		if (ac == 0) {
1596 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1597 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1598 			    SSH_AUTHSOCKET_ENV_NAME);
1599 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1600 			    SSH_AGENTPID_ENV_NAME);
1601 			printf("echo Agent pid %ld;\n", (long)pid);
1602 			exit(0);
1603 		}
1604 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1605 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1606 			perror("setenv");
1607 			exit(1);
1608 		}
1609 		execvp(av[0], av);
1610 		perror(av[0]);
1611 		exit(1);
1612 	}
1613 	/* child */
1614 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1615 
1616 	if (setsid() == -1) {
1617 		error("setsid: %s", strerror(errno));
1618 		cleanup_exit(1);
1619 	}
1620 
1621 	(void)chdir("/");
1622 	if (stdfd_devnull(1, 1, 1) == -1)
1623 		error_f("stdfd_devnull failed");
1624 
1625 #ifdef HAVE_SETRLIMIT
1626 	/* deny core dumps, since memory contains unencrypted private keys */
1627 	rlim.rlim_cur = rlim.rlim_max = 0;
1628 	if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
1629 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1630 		cleanup_exit(1);
1631 	}
1632 #endif
1633 
1634 skip:
1635 
1636 	cleanup_pid = getpid();
1637 
1638 #ifdef ENABLE_PKCS11
1639 	pkcs11_init(0);
1640 #endif
1641 	new_socket(AUTH_SOCKET, sock);
1642 	if (ac > 0)
1643 		parent_alive_interval = 10;
1644 	idtab_init();
1645 	ssh_signal(SIGPIPE, SIG_IGN);
1646 	ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1647 	ssh_signal(SIGHUP, cleanup_handler);
1648 	ssh_signal(SIGTERM, cleanup_handler);
1649 
1650 	if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1651 		fatal("%s: pledge: %s", __progname, strerror(errno));
1652 	platform_pledge_agent();
1653 
1654 	while (1) {
1655 		prepare_poll(&pfd, &npfd, &timeout, maxfds);
1656 		result = poll(pfd, npfd, timeout);
1657 		saved_errno = errno;
1658 		if (parent_alive_interval != 0)
1659 			check_parent_exists();
1660 		(void) reaper();	/* remove expired keys */
1661 		if (result == -1) {
1662 			if (saved_errno == EINTR)
1663 				continue;
1664 			fatal("poll: %s", strerror(saved_errno));
1665 		} else if (result > 0)
1666 			after_poll(pfd, npfd, maxfds);
1667 	}
1668 	/* NOTREACHED */
1669 }
1670