xref: /openbsd-src/usr.bin/ssh/ssh-agent.c (revision f763167468dba5339ed4b14b7ecaca2a397ab0f6)
1 /* $OpenBSD: ssh-agent.c,v 1.224 2017/07/24 04:34:28 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 <sys/types.h>
38 #include <sys/time.h>
39 #include <sys/queue.h>
40 #include <sys/resource.h>
41 #include <sys/socket.h>
42 #include <sys/stat.h>
43 #include <sys/un.h>
44 
45 #ifdef WITH_OPENSSL
46 #include <openssl/evp.h>
47 #endif
48 
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <paths.h>
52 #include <poll.h>
53 #include <signal.h>
54 #include <stdlib.h>
55 #include <stdio.h>
56 #include <string.h>
57 #include <limits.h>
58 #include <time.h>
59 #include <unistd.h>
60 #include <util.h>
61 
62 #include "xmalloc.h"
63 #include "ssh.h"
64 #include "sshbuf.h"
65 #include "sshkey.h"
66 #include "authfd.h"
67 #include "compat.h"
68 #include "log.h"
69 #include "misc.h"
70 #include "digest.h"
71 #include "ssherr.h"
72 #include "match.h"
73 
74 #ifdef ENABLE_PKCS11
75 #include "ssh-pkcs11.h"
76 #endif
77 
78 #ifndef DEFAULT_PKCS11_WHITELIST
79 # define DEFAULT_PKCS11_WHITELIST "/usr/lib*/*,/usr/local/lib*/*"
80 #endif
81 
82 /* Maximum accepted message length */
83 #define AGENT_MAX_LEN	(256*1024)
84 
85 typedef enum {
86 	AUTH_UNUSED,
87 	AUTH_SOCKET,
88 	AUTH_CONNECTION
89 } sock_type;
90 
91 typedef struct {
92 	int fd;
93 	sock_type type;
94 	struct sshbuf *input;
95 	struct sshbuf *output;
96 	struct sshbuf *request;
97 } SocketEntry;
98 
99 u_int sockets_alloc = 0;
100 SocketEntry *sockets = NULL;
101 
102 typedef struct identity {
103 	TAILQ_ENTRY(identity) next;
104 	struct sshkey *key;
105 	char *comment;
106 	char *provider;
107 	time_t death;
108 	u_int confirm;
109 } Identity;
110 
111 struct idtable {
112 	int nentries;
113 	TAILQ_HEAD(idqueue, identity) idlist;
114 };
115 
116 /* private key table */
117 struct idtable *idtab;
118 
119 int max_fd = 0;
120 
121 /* pid of shell == parent of agent */
122 pid_t parent_pid = -1;
123 time_t parent_alive_interval = 0;
124 
125 /* pid of process for which cleanup_socket is applicable */
126 pid_t cleanup_pid = 0;
127 
128 /* pathname and directory for AUTH_SOCKET */
129 char socket_name[PATH_MAX];
130 char socket_dir[PATH_MAX];
131 
132 /* PKCS#11 path whitelist */
133 static char *pkcs11_whitelist;
134 
135 /* locking */
136 #define LOCK_SIZE	32
137 #define LOCK_SALT_SIZE	16
138 #define LOCK_ROUNDS	1
139 int locked = 0;
140 u_char lock_pwhash[LOCK_SIZE];
141 u_char lock_salt[LOCK_SALT_SIZE];
142 
143 extern char *__progname;
144 
145 /* Default lifetime in seconds (0 == forever) */
146 static long lifetime = 0;
147 
148 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
149 
150 static void
151 close_socket(SocketEntry *e)
152 {
153 	close(e->fd);
154 	e->fd = -1;
155 	e->type = AUTH_UNUSED;
156 	sshbuf_free(e->input);
157 	sshbuf_free(e->output);
158 	sshbuf_free(e->request);
159 }
160 
161 static void
162 idtab_init(void)
163 {
164 	idtab = xcalloc(1, sizeof(*idtab));
165 	TAILQ_INIT(&idtab->idlist);
166 	idtab->nentries = 0;
167 }
168 
169 static void
170 free_identity(Identity *id)
171 {
172 	sshkey_free(id->key);
173 	free(id->provider);
174 	free(id->comment);
175 	free(id);
176 }
177 
178 /* return matching private key for given public key */
179 static Identity *
180 lookup_identity(struct sshkey *key)
181 {
182 	Identity *id;
183 
184 	TAILQ_FOREACH(id, &idtab->idlist, next) {
185 		if (sshkey_equal(key, id->key))
186 			return (id);
187 	}
188 	return (NULL);
189 }
190 
191 /* Check confirmation of keysign request */
192 static int
193 confirm_key(Identity *id)
194 {
195 	char *p;
196 	int ret = -1;
197 
198 	p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
199 	if (p != NULL &&
200 	    ask_permission("Allow use of key %s?\nKey fingerprint %s.",
201 	    id->comment, p))
202 		ret = 0;
203 	free(p);
204 
205 	return (ret);
206 }
207 
208 static void
209 send_status(SocketEntry *e, int success)
210 {
211 	int r;
212 
213 	if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
214 	    (r = sshbuf_put_u8(e->output, success ?
215 	    SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
216 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
217 }
218 
219 /* send list of supported public keys to 'client' */
220 static void
221 process_request_identities(SocketEntry *e)
222 {
223 	Identity *id;
224 	struct sshbuf *msg;
225 	int r;
226 
227 	if ((msg = sshbuf_new()) == NULL)
228 		fatal("%s: sshbuf_new failed", __func__);
229 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
230 	    (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
231 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
232 	TAILQ_FOREACH(id, &idtab->idlist, next) {
233 		if ((r = sshkey_puts(id->key, msg)) != 0 ||
234 		    (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
235 			error("%s: put key/comment: %s", __func__,
236 			    ssh_err(r));
237 			continue;
238 		}
239 	}
240 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
241 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
242 	sshbuf_free(msg);
243 }
244 
245 
246 static char *
247 agent_decode_alg(struct sshkey *key, u_int flags)
248 {
249 	if (key->type == KEY_RSA) {
250 		if (flags & SSH_AGENT_RSA_SHA2_256)
251 			return "rsa-sha2-256";
252 		else if (flags & SSH_AGENT_RSA_SHA2_512)
253 			return "rsa-sha2-512";
254 	}
255 	return NULL;
256 }
257 
258 /* ssh2 only */
259 static void
260 process_sign_request2(SocketEntry *e)
261 {
262 	const u_char *data;
263 	u_char *signature = NULL;
264 	size_t dlen, slen = 0;
265 	u_int compat = 0, flags;
266 	int r, ok = -1;
267 	struct sshbuf *msg;
268 	struct sshkey *key = NULL;
269 	struct identity *id;
270 
271 	if ((msg = sshbuf_new()) == NULL)
272 		fatal("%s: sshbuf_new failed", __func__);
273 	if ((r = sshkey_froms(e->request, &key)) != 0 ||
274 	    (r = sshbuf_get_string_direct(e->request, &data, &dlen)) != 0 ||
275 	    (r = sshbuf_get_u32(e->request, &flags)) != 0)
276 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
277 	if (flags & SSH_AGENT_OLD_SIGNATURE)
278 		compat = SSH_BUG_SIGBLOB;
279 	if ((id = lookup_identity(key)) == NULL) {
280 		verbose("%s: %s key not found", __func__, sshkey_type(key));
281 		goto send;
282 	}
283 	if (id->confirm && confirm_key(id) != 0) {
284 		verbose("%s: user refused key", __func__);
285 		goto send;
286 	}
287 	if ((r = sshkey_sign(id->key, &signature, &slen,
288 	    data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
289 		error("%s: sshkey_sign: %s", __func__, ssh_err(r));
290 		goto send;
291 	}
292 	/* Success */
293 	ok = 0;
294  send:
295 	sshkey_free(key);
296 	if (ok == 0) {
297 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
298 		    (r = sshbuf_put_string(msg, signature, slen)) != 0)
299 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
300 	} else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
301 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
302 
303 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
304 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
305 
306 	sshbuf_free(msg);
307 	free(signature);
308 }
309 
310 /* shared */
311 static void
312 process_remove_identity(SocketEntry *e)
313 {
314 	int r, success = 0;
315 	struct sshkey *key = NULL;
316 	Identity *id;
317 
318 	if ((r = sshkey_froms(e->request, &key)) != 0) {
319 		error("%s: get key: %s", __func__, ssh_err(r));
320 		goto done;
321 	}
322 	if ((id = lookup_identity(key)) == NULL) {
323 		debug("%s: key not found", __func__);
324 		goto done;
325 	}
326 	/* We have this key, free it. */
327 	if (idtab->nentries < 1)
328 		fatal("%s: internal error: nentries %d",
329 		    __func__, idtab->nentries);
330 	TAILQ_REMOVE(&idtab->idlist, id, next);
331 	free_identity(id);
332 	idtab->nentries--;
333 	sshkey_free(key);
334 	success = 1;
335  done:
336 	send_status(e, success);
337 }
338 
339 static void
340 process_remove_all_identities(SocketEntry *e)
341 {
342 	Identity *id;
343 
344 	/* Loop over all identities and clear the keys. */
345 	for (id = TAILQ_FIRST(&idtab->idlist); id;
346 	    id = TAILQ_FIRST(&idtab->idlist)) {
347 		TAILQ_REMOVE(&idtab->idlist, id, next);
348 		free_identity(id);
349 	}
350 
351 	/* Mark that there are no identities. */
352 	idtab->nentries = 0;
353 
354 	/* Send success. */
355 	send_status(e, 1);
356 }
357 
358 /* removes expired keys and returns number of seconds until the next expiry */
359 static time_t
360 reaper(void)
361 {
362 	time_t deadline = 0, now = monotime();
363 	Identity *id, *nxt;
364 
365 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
366 		nxt = TAILQ_NEXT(id, next);
367 		if (id->death == 0)
368 			continue;
369 		if (now >= id->death) {
370 			debug("expiring key '%s'", id->comment);
371 			TAILQ_REMOVE(&idtab->idlist, id, next);
372 			free_identity(id);
373 			idtab->nentries--;
374 		} else
375 			deadline = (deadline == 0) ? id->death :
376 			    MINIMUM(deadline, id->death);
377 	}
378 	if (deadline == 0 || deadline <= now)
379 		return 0;
380 	else
381 		return (deadline - now);
382 }
383 
384 static void
385 process_add_identity(SocketEntry *e)
386 {
387 	Identity *id;
388 	int success = 0, confirm = 0;
389 	u_int seconds;
390 	char *comment = NULL;
391 	time_t death = 0;
392 	struct sshkey *k = NULL;
393 	u_char ctype;
394 	int r = SSH_ERR_INTERNAL_ERROR;
395 
396 	if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
397 	    k == NULL ||
398 	    (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
399 		error("%s: decode private key: %s", __func__, ssh_err(r));
400 		goto err;
401 	}
402 
403 	while (sshbuf_len(e->request)) {
404 		if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
405 			error("%s: buffer error: %s", __func__, ssh_err(r));
406 			goto err;
407 		}
408 		switch (ctype) {
409 		case SSH_AGENT_CONSTRAIN_LIFETIME:
410 			if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
411 				error("%s: bad lifetime constraint: %s",
412 				    __func__, ssh_err(r));
413 				goto err;
414 			}
415 			death = monotime() + seconds;
416 			break;
417 		case SSH_AGENT_CONSTRAIN_CONFIRM:
418 			confirm = 1;
419 			break;
420 		default:
421 			error("%s: Unknown constraint %d", __func__, ctype);
422  err:
423 			sshbuf_reset(e->request);
424 			free(comment);
425 			sshkey_free(k);
426 			goto send;
427 		}
428 	}
429 
430 	success = 1;
431 	if (lifetime && !death)
432 		death = monotime() + lifetime;
433 	if ((id = lookup_identity(k)) == NULL) {
434 		id = xcalloc(1, sizeof(Identity));
435 		id->key = k;
436 		TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
437 		/* Increment the number of identities. */
438 		idtab->nentries++;
439 	} else {
440 		sshkey_free(k);
441 		free(id->comment);
442 	}
443 	id->comment = comment;
444 	id->death = death;
445 	id->confirm = confirm;
446 send:
447 	send_status(e, success);
448 }
449 
450 /* XXX todo: encrypt sensitive data with passphrase */
451 static void
452 process_lock_agent(SocketEntry *e, int lock)
453 {
454 	int r, success = 0, delay;
455 	char *passwd;
456 	u_char passwdhash[LOCK_SIZE];
457 	static u_int fail_count = 0;
458 	size_t pwlen;
459 
460 	if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
461 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
462 	if (pwlen == 0) {
463 		debug("empty password not supported");
464 	} else if (locked && !lock) {
465 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
466 		    passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
467 			fatal("bcrypt_pbkdf");
468 		if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
469 			debug("agent unlocked");
470 			locked = 0;
471 			fail_count = 0;
472 			explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
473 			success = 1;
474 		} else {
475 			/* delay in 0.1s increments up to 10s */
476 			if (fail_count < 100)
477 				fail_count++;
478 			delay = 100000 * fail_count;
479 			debug("unlock failed, delaying %0.1lf seconds",
480 			    (double)delay/1000000);
481 			usleep(delay);
482 		}
483 		explicit_bzero(passwdhash, sizeof(passwdhash));
484 	} else if (!locked && lock) {
485 		debug("agent locked");
486 		locked = 1;
487 		arc4random_buf(lock_salt, sizeof(lock_salt));
488 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
489 		    lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
490 			fatal("bcrypt_pbkdf");
491 		success = 1;
492 	}
493 	explicit_bzero(passwd, pwlen);
494 	free(passwd);
495 	send_status(e, success);
496 }
497 
498 static void
499 no_identities(SocketEntry *e)
500 {
501 	struct sshbuf *msg;
502 	int r;
503 
504 	if ((msg = sshbuf_new()) == NULL)
505 		fatal("%s: sshbuf_new failed", __func__);
506 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
507 	    (r = sshbuf_put_u32(msg, 0)) != 0 ||
508 	    (r = sshbuf_put_stringb(e->output, msg)) != 0)
509 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
510 	sshbuf_free(msg);
511 }
512 
513 #ifdef ENABLE_PKCS11
514 static void
515 process_add_smartcard_key(SocketEntry *e)
516 {
517 	char *provider = NULL, *pin, canonical_provider[PATH_MAX];
518 	int r, i, count = 0, success = 0, confirm = 0;
519 	u_int seconds;
520 	time_t death = 0;
521 	u_char type;
522 	struct sshkey **keys = NULL, *k;
523 	Identity *id;
524 
525 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
526 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
527 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
528 
529 	while (sshbuf_len(e->request)) {
530 		if ((r = sshbuf_get_u8(e->request, &type)) != 0)
531 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
532 		switch (type) {
533 		case SSH_AGENT_CONSTRAIN_LIFETIME:
534 			if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
535 				fatal("%s: buffer error: %s",
536 				    __func__, ssh_err(r));
537 			death = monotime() + seconds;
538 			break;
539 		case SSH_AGENT_CONSTRAIN_CONFIRM:
540 			confirm = 1;
541 			break;
542 		default:
543 			error("%s: Unknown constraint type %d", __func__, type);
544 			goto send;
545 		}
546 	}
547 	if (realpath(provider, canonical_provider) == NULL) {
548 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
549 		    provider, strerror(errno));
550 		goto send;
551 	}
552 	if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
553 		verbose("refusing PKCS#11 add of \"%.100s\": "
554 		    "provider not whitelisted", canonical_provider);
555 		goto send;
556 	}
557 	debug("%s: add %.100s", __func__, canonical_provider);
558 	if (lifetime && !death)
559 		death = monotime() + lifetime;
560 
561 	count = pkcs11_add_provider(canonical_provider, pin, &keys);
562 	for (i = 0; i < count; i++) {
563 		k = keys[i];
564 		if (lookup_identity(k) == NULL) {
565 			id = xcalloc(1, sizeof(Identity));
566 			id->key = k;
567 			id->provider = xstrdup(canonical_provider);
568 			id->comment = xstrdup(canonical_provider); /* XXX */
569 			id->death = death;
570 			id->confirm = confirm;
571 			TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
572 			idtab->nentries++;
573 			success = 1;
574 		} else {
575 			sshkey_free(k);
576 		}
577 		keys[i] = NULL;
578 	}
579 send:
580 	free(pin);
581 	free(provider);
582 	free(keys);
583 	send_status(e, success);
584 }
585 
586 static void
587 process_remove_smartcard_key(SocketEntry *e)
588 {
589 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
590 	int r, success = 0;
591 	Identity *id, *nxt;
592 
593 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
594 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
595 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
596 	free(pin);
597 
598 	if (realpath(provider, canonical_provider) == NULL) {
599 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
600 		    provider, strerror(errno));
601 		goto send;
602 	}
603 
604 	debug("%s: remove %.100s", __func__, canonical_provider);
605 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
606 		nxt = TAILQ_NEXT(id, next);
607 		/* Skip file--based keys */
608 		if (id->provider == NULL)
609 			continue;
610 		if (!strcmp(canonical_provider, id->provider)) {
611 			TAILQ_REMOVE(&idtab->idlist, id, next);
612 			free_identity(id);
613 			idtab->nentries--;
614 		}
615 	}
616 	if (pkcs11_del_provider(canonical_provider) == 0)
617 		success = 1;
618 	else
619 		error("%s: pkcs11_del_provider failed", __func__);
620 send:
621 	free(provider);
622 	send_status(e, success);
623 }
624 #endif /* ENABLE_PKCS11 */
625 
626 /* dispatch incoming messages */
627 
628 static int
629 process_message(u_int socknum)
630 {
631 	u_int msg_len;
632 	u_char type;
633 	const u_char *cp;
634 	int r;
635 	SocketEntry *e;
636 
637 	if (socknum >= sockets_alloc) {
638 		fatal("%s: socket number %u >= allocated %u",
639 		    __func__, socknum, sockets_alloc);
640 	}
641 	e = &sockets[socknum];
642 
643 	if (sshbuf_len(e->input) < 5)
644 		return 0;		/* Incomplete message header. */
645 	cp = sshbuf_ptr(e->input);
646 	msg_len = PEEK_U32(cp);
647 	if (msg_len > AGENT_MAX_LEN) {
648 		debug("%s: socket %u (fd=%d) message too long %u > %u",
649 		    __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN);
650 		return -1;
651 	}
652 	if (sshbuf_len(e->input) < msg_len + 4)
653 		return 0;		/* Incomplete message body. */
654 
655 	/* move the current input to e->request */
656 	sshbuf_reset(e->request);
657 	if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
658 	    (r = sshbuf_get_u8(e->request, &type)) != 0) {
659 		if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
660 		    r == SSH_ERR_STRING_TOO_LARGE) {
661 			debug("%s: buffer error: %s", __func__, ssh_err(r));
662 			return -1;
663 		}
664 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
665 	}
666 
667 	debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type);
668 
669 	/* check wheter agent is locked */
670 	if (locked && type != SSH_AGENTC_UNLOCK) {
671 		sshbuf_reset(e->request);
672 		switch (type) {
673 		case SSH2_AGENTC_REQUEST_IDENTITIES:
674 			/* send empty lists */
675 			no_identities(e);
676 			break;
677 		default:
678 			/* send a fail message for all other request types */
679 			send_status(e, 0);
680 		}
681 		return 0;
682 	}
683 
684 	switch (type) {
685 	case SSH_AGENTC_LOCK:
686 	case SSH_AGENTC_UNLOCK:
687 		process_lock_agent(e, type == SSH_AGENTC_LOCK);
688 		break;
689 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
690 		process_remove_all_identities(e); /* safe for !WITH_SSH1 */
691 		break;
692 	/* ssh2 */
693 	case SSH2_AGENTC_SIGN_REQUEST:
694 		process_sign_request2(e);
695 		break;
696 	case SSH2_AGENTC_REQUEST_IDENTITIES:
697 		process_request_identities(e);
698 		break;
699 	case SSH2_AGENTC_ADD_IDENTITY:
700 	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
701 		process_add_identity(e);
702 		break;
703 	case SSH2_AGENTC_REMOVE_IDENTITY:
704 		process_remove_identity(e);
705 		break;
706 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
707 		process_remove_all_identities(e);
708 		break;
709 #ifdef ENABLE_PKCS11
710 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
711 	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
712 		process_add_smartcard_key(e);
713 		break;
714 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
715 		process_remove_smartcard_key(e);
716 		break;
717 #endif /* ENABLE_PKCS11 */
718 	default:
719 		/* Unknown message.  Respond with failure. */
720 		error("Unknown message %d", type);
721 		sshbuf_reset(e->request);
722 		send_status(e, 0);
723 		break;
724 	}
725 	return 0;
726 }
727 
728 static void
729 new_socket(sock_type type, int fd)
730 {
731 	u_int i, old_alloc, new_alloc;
732 
733 	set_nonblock(fd);
734 
735 	if (fd > max_fd)
736 		max_fd = fd;
737 
738 	for (i = 0; i < sockets_alloc; i++)
739 		if (sockets[i].type == AUTH_UNUSED) {
740 			sockets[i].fd = fd;
741 			if ((sockets[i].input = sshbuf_new()) == NULL)
742 				fatal("%s: sshbuf_new failed", __func__);
743 			if ((sockets[i].output = sshbuf_new()) == NULL)
744 				fatal("%s: sshbuf_new failed", __func__);
745 			if ((sockets[i].request = sshbuf_new()) == NULL)
746 				fatal("%s: sshbuf_new failed", __func__);
747 			sockets[i].type = type;
748 			return;
749 		}
750 	old_alloc = sockets_alloc;
751 	new_alloc = sockets_alloc + 10;
752 	sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
753 	for (i = old_alloc; i < new_alloc; i++)
754 		sockets[i].type = AUTH_UNUSED;
755 	sockets_alloc = new_alloc;
756 	sockets[old_alloc].fd = fd;
757 	if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
758 		fatal("%s: sshbuf_new failed", __func__);
759 	if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
760 		fatal("%s: sshbuf_new failed", __func__);
761 	if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
762 		fatal("%s: sshbuf_new failed", __func__);
763 	sockets[old_alloc].type = type;
764 }
765 
766 static int
767 handle_socket_read(u_int socknum)
768 {
769 	struct sockaddr_un sunaddr;
770 	socklen_t slen;
771 	uid_t euid;
772 	gid_t egid;
773 	int fd;
774 
775 	slen = sizeof(sunaddr);
776 	fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
777 	if (fd < 0) {
778 		error("accept from AUTH_SOCKET: %s", strerror(errno));
779 		return -1;
780 	}
781 	if (getpeereid(fd, &euid, &egid) < 0) {
782 		error("getpeereid %d failed: %s", fd, strerror(errno));
783 		close(fd);
784 		return -1;
785 	}
786 	if ((euid != 0) && (getuid() != euid)) {
787 		error("uid mismatch: peer euid %u != uid %u",
788 		    (u_int) euid, (u_int) getuid());
789 		close(fd);
790 		return -1;
791 	}
792 	new_socket(AUTH_CONNECTION, fd);
793 	return 0;
794 }
795 
796 static int
797 handle_conn_read(u_int socknum)
798 {
799 	char buf[1024];
800 	ssize_t len;
801 	int r;
802 
803 	if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
804 		if (len == -1) {
805 			if (errno == EAGAIN || errno == EINTR)
806 				return 0;
807 			error("%s: read error on socket %u (fd %d): %s",
808 			    __func__, socknum, sockets[socknum].fd,
809 			    strerror(errno));
810 		}
811 		return -1;
812 	}
813 	if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
814 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
815 	explicit_bzero(buf, sizeof(buf));
816 	process_message(socknum);
817 	return 0;
818 }
819 
820 static int
821 handle_conn_write(u_int socknum)
822 {
823 	ssize_t len;
824 	int r;
825 
826 	if (sshbuf_len(sockets[socknum].output) == 0)
827 		return 0; /* shouldn't happen */
828 	if ((len = write(sockets[socknum].fd,
829 	    sshbuf_ptr(sockets[socknum].output),
830 	    sshbuf_len(sockets[socknum].output))) <= 0) {
831 		if (len == -1) {
832 			if (errno == EAGAIN || errno == EINTR)
833 				return 0;
834 			error("%s: read error on socket %u (fd %d): %s",
835 			    __func__, socknum, sockets[socknum].fd,
836 			    strerror(errno));
837 		}
838 		return -1;
839 	}
840 	if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
841 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
842 	return 0;
843 }
844 
845 static void
846 after_poll(struct pollfd *pfd, size_t npfd)
847 {
848 	size_t i;
849 	u_int socknum;
850 
851 	for (i = 0; i < npfd; i++) {
852 		if (pfd[i].revents == 0)
853 			continue;
854 		/* Find sockets entry */
855 		for (socknum = 0; socknum < sockets_alloc; socknum++) {
856 			if (sockets[socknum].type != AUTH_SOCKET &&
857 			    sockets[socknum].type != AUTH_CONNECTION)
858 				continue;
859 			if (pfd[i].fd == sockets[socknum].fd)
860 				break;
861 		}
862 		if (socknum >= sockets_alloc) {
863 			error("%s: no socket for fd %d", __func__, pfd[i].fd);
864 			continue;
865 		}
866 		/* Process events */
867 		switch (sockets[socknum].type) {
868 		case AUTH_SOCKET:
869 			if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
870 			    handle_socket_read(socknum) != 0)
871 				close_socket(&sockets[socknum]);
872 			break;
873 		case AUTH_CONNECTION:
874 			if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
875 			    handle_conn_read(socknum) != 0) {
876 				close_socket(&sockets[socknum]);
877 				break;
878 			}
879 			if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
880 			    handle_conn_write(socknum) != 0)
881 				close_socket(&sockets[socknum]);
882 			break;
883 		default:
884 			break;
885 		}
886 	}
887 }
888 
889 static int
890 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp)
891 {
892 	struct pollfd *pfd = *pfdp;
893 	size_t i, j, npfd = 0;
894 	time_t deadline;
895 
896 	/* Count active sockets */
897 	for (i = 0; i < sockets_alloc; i++) {
898 		switch (sockets[i].type) {
899 		case AUTH_SOCKET:
900 		case AUTH_CONNECTION:
901 			npfd++;
902 			break;
903 		case AUTH_UNUSED:
904 			break;
905 		default:
906 			fatal("Unknown socket type %d", sockets[i].type);
907 			break;
908 		}
909 	}
910 	if (npfd != *npfdp &&
911 	    (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
912 		fatal("%s: recallocarray failed", __func__);
913 	*pfdp = pfd;
914 	*npfdp = npfd;
915 
916 	for (i = j = 0; i < sockets_alloc; i++) {
917 		switch (sockets[i].type) {
918 		case AUTH_SOCKET:
919 		case AUTH_CONNECTION:
920 			pfd[j].fd = sockets[i].fd;
921 			pfd[j].revents = 0;
922 			/* XXX backoff when input buffer full */
923 			pfd[j].events = POLLIN;
924 			if (sshbuf_len(sockets[i].output) > 0)
925 				pfd[j].events |= POLLOUT;
926 			j++;
927 			break;
928 		default:
929 			break;
930 		}
931 	}
932 	deadline = reaper();
933 	if (parent_alive_interval != 0)
934 		deadline = (deadline == 0) ? parent_alive_interval :
935 		    MINIMUM(deadline, parent_alive_interval);
936 	if (deadline == 0) {
937 		*timeoutp = -1; /* INFTIM */
938 	} else {
939 		if (deadline > INT_MAX / 1000)
940 			*timeoutp = INT_MAX / 1000;
941 		else
942 			*timeoutp = deadline * 1000;
943 	}
944 	return (1);
945 }
946 
947 static void
948 cleanup_socket(void)
949 {
950 	if (cleanup_pid != 0 && getpid() != cleanup_pid)
951 		return;
952 	debug("%s: cleanup", __func__);
953 	if (socket_name[0])
954 		unlink(socket_name);
955 	if (socket_dir[0])
956 		rmdir(socket_dir);
957 }
958 
959 void
960 cleanup_exit(int i)
961 {
962 	cleanup_socket();
963 	_exit(i);
964 }
965 
966 /*ARGSUSED*/
967 static void
968 cleanup_handler(int sig)
969 {
970 	cleanup_socket();
971 #ifdef ENABLE_PKCS11
972 	pkcs11_terminate();
973 #endif
974 	_exit(2);
975 }
976 
977 static void
978 check_parent_exists(void)
979 {
980 	/*
981 	 * If our parent has exited then getppid() will return (pid_t)1,
982 	 * so testing for that should be safe.
983 	 */
984 	if (parent_pid != -1 && getppid() != parent_pid) {
985 		/* printf("Parent has died - Authentication agent exiting.\n"); */
986 		cleanup_socket();
987 		_exit(2);
988 	}
989 }
990 
991 static void
992 usage(void)
993 {
994 	fprintf(stderr,
995 	    "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
996 	    "                 [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
997 	    "       ssh-agent [-c | -s] -k\n");
998 	exit(1);
999 }
1000 
1001 int
1002 main(int ac, char **av)
1003 {
1004 	int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1005 	int sock, fd, ch, result, saved_errno;
1006 	char *shell, *format, *pidstr, *agentsocket = NULL;
1007 	struct rlimit rlim;
1008 	extern int optind;
1009 	extern char *optarg;
1010 	pid_t pid;
1011 	char pidstrbuf[1 + 3 * sizeof pid];
1012 	size_t len;
1013 	mode_t prev_mask;
1014 	int timeout = -1; /* INFTIM */
1015 	struct pollfd *pfd = NULL;
1016 	size_t npfd = 0;
1017 
1018 	ssh_malloc_init();	/* must be called before any mallocs */
1019 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1020 	sanitise_stdfd();
1021 
1022 	/* drop */
1023 	setegid(getgid());
1024 	setgid(getgid());
1025 
1026 #ifdef WITH_OPENSSL
1027 	OpenSSL_add_all_algorithms();
1028 #endif
1029 
1030 	while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) {
1031 		switch (ch) {
1032 		case 'E':
1033 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
1034 			if (fingerprint_hash == -1)
1035 				fatal("Invalid hash algorithm \"%s\"", optarg);
1036 			break;
1037 		case 'c':
1038 			if (s_flag)
1039 				usage();
1040 			c_flag++;
1041 			break;
1042 		case 'k':
1043 			k_flag++;
1044 			break;
1045 		case 'P':
1046 			if (pkcs11_whitelist != NULL)
1047 				fatal("-P option already specified");
1048 			pkcs11_whitelist = xstrdup(optarg);
1049 			break;
1050 		case 's':
1051 			if (c_flag)
1052 				usage();
1053 			s_flag++;
1054 			break;
1055 		case 'd':
1056 			if (d_flag || D_flag)
1057 				usage();
1058 			d_flag++;
1059 			break;
1060 		case 'D':
1061 			if (d_flag || D_flag)
1062 				usage();
1063 			D_flag++;
1064 			break;
1065 		case 'a':
1066 			agentsocket = optarg;
1067 			break;
1068 		case 't':
1069 			if ((lifetime = convtime(optarg)) == -1) {
1070 				fprintf(stderr, "Invalid lifetime\n");
1071 				usage();
1072 			}
1073 			break;
1074 		default:
1075 			usage();
1076 		}
1077 	}
1078 	ac -= optind;
1079 	av += optind;
1080 
1081 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1082 		usage();
1083 
1084 	if (pkcs11_whitelist == NULL)
1085 		pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
1086 
1087 	if (ac == 0 && !c_flag && !s_flag) {
1088 		shell = getenv("SHELL");
1089 		if (shell != NULL && (len = strlen(shell)) > 2 &&
1090 		    strncmp(shell + len - 3, "csh", 3) == 0)
1091 			c_flag = 1;
1092 	}
1093 	if (k_flag) {
1094 		const char *errstr = NULL;
1095 
1096 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1097 		if (pidstr == NULL) {
1098 			fprintf(stderr, "%s not set, cannot kill agent\n",
1099 			    SSH_AGENTPID_ENV_NAME);
1100 			exit(1);
1101 		}
1102 		pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1103 		if (errstr) {
1104 			fprintf(stderr,
1105 			    "%s=\"%s\", which is not a good PID: %s\n",
1106 			    SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1107 			exit(1);
1108 		}
1109 		if (kill(pid, SIGTERM) == -1) {
1110 			perror("kill");
1111 			exit(1);
1112 		}
1113 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1114 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
1115 		printf(format, SSH_AGENTPID_ENV_NAME);
1116 		printf("echo Agent pid %ld killed;\n", (long)pid);
1117 		exit(0);
1118 	}
1119 	parent_pid = getpid();
1120 
1121 	if (agentsocket == NULL) {
1122 		/* Create private directory for agent socket */
1123 		mktemp_proto(socket_dir, sizeof(socket_dir));
1124 		if (mkdtemp(socket_dir) == NULL) {
1125 			perror("mkdtemp: private socket dir");
1126 			exit(1);
1127 		}
1128 		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1129 		    (long)parent_pid);
1130 	} else {
1131 		/* Try to use specified agent socket */
1132 		socket_dir[0] = '\0';
1133 		strlcpy(socket_name, agentsocket, sizeof socket_name);
1134 	}
1135 
1136 	/*
1137 	 * Create socket early so it will exist before command gets run from
1138 	 * the parent.
1139 	 */
1140 	prev_mask = umask(0177);
1141 	sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1142 	if (sock < 0) {
1143 		/* XXX - unix_listener() calls error() not perror() */
1144 		*socket_name = '\0'; /* Don't unlink any existing file */
1145 		cleanup_exit(1);
1146 	}
1147 	umask(prev_mask);
1148 
1149 	/*
1150 	 * Fork, and have the parent execute the command, if any, or present
1151 	 * the socket data.  The child continues as the authentication agent.
1152 	 */
1153 	if (D_flag || d_flag) {
1154 		log_init(__progname,
1155 		    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1156 		    SYSLOG_FACILITY_AUTH, 1);
1157 		format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1158 		printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1159 		    SSH_AUTHSOCKET_ENV_NAME);
1160 		printf("echo Agent pid %ld;\n", (long)parent_pid);
1161 		fflush(stdout);
1162 		goto skip;
1163 	}
1164 	pid = fork();
1165 	if (pid == -1) {
1166 		perror("fork");
1167 		cleanup_exit(1);
1168 	}
1169 	if (pid != 0) {		/* Parent - execute the given command. */
1170 		close(sock);
1171 		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1172 		if (ac == 0) {
1173 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1174 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1175 			    SSH_AUTHSOCKET_ENV_NAME);
1176 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1177 			    SSH_AGENTPID_ENV_NAME);
1178 			printf("echo Agent pid %ld;\n", (long)pid);
1179 			exit(0);
1180 		}
1181 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1182 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1183 			perror("setenv");
1184 			exit(1);
1185 		}
1186 		execvp(av[0], av);
1187 		perror(av[0]);
1188 		exit(1);
1189 	}
1190 	/* child */
1191 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1192 
1193 	if (setsid() == -1) {
1194 		error("setsid: %s", strerror(errno));
1195 		cleanup_exit(1);
1196 	}
1197 
1198 	(void)chdir("/");
1199 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1200 		/* XXX might close listen socket */
1201 		(void)dup2(fd, STDIN_FILENO);
1202 		(void)dup2(fd, STDOUT_FILENO);
1203 		(void)dup2(fd, STDERR_FILENO);
1204 		if (fd > 2)
1205 			close(fd);
1206 	}
1207 
1208 	/* deny core dumps, since memory contains unencrypted private keys */
1209 	rlim.rlim_cur = rlim.rlim_max = 0;
1210 	if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1211 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1212 		cleanup_exit(1);
1213 	}
1214 
1215 skip:
1216 
1217 	cleanup_pid = getpid();
1218 
1219 #ifdef ENABLE_PKCS11
1220 	pkcs11_init(0);
1221 #endif
1222 	new_socket(AUTH_SOCKET, sock);
1223 	if (ac > 0)
1224 		parent_alive_interval = 10;
1225 	idtab_init();
1226 	signal(SIGPIPE, SIG_IGN);
1227 	signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1228 	signal(SIGHUP, cleanup_handler);
1229 	signal(SIGTERM, cleanup_handler);
1230 
1231 	if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1232 		fatal("%s: pledge: %s", __progname, strerror(errno));
1233 
1234 	while (1) {
1235 		prepare_poll(&pfd, &npfd, &timeout);
1236 		result = poll(pfd, npfd, timeout);
1237 		saved_errno = errno;
1238 		if (parent_alive_interval != 0)
1239 			check_parent_exists();
1240 		(void) reaper();	/* remove expired keys */
1241 		if (result < 0) {
1242 			if (saved_errno == EINTR)
1243 				continue;
1244 			fatal("poll: %s", strerror(saved_errno));
1245 		} else if (result > 0)
1246 			after_poll(pfd, npfd);
1247 	}
1248 	/* NOTREACHED */
1249 }
1250