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