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