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