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