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