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