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