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