ssh-agent.c revision 323136
1/* $OpenBSD: ssh-agent.c,v 1.218 2017/03/15 03:52:30 deraadt 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: stable/11/crypto/openssh/ssh-agent.c 323136 2017-09-02 23:39:51Z des $");
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#include <signal.h>
65#include <stdarg.h>
66#include <stdio.h>
67#include <stdlib.h>
68#include <time.h>
69#include <string.h>
70#include <unistd.h>
71#ifdef HAVE_UTIL_H
72# include <util.h>
73#endif
74
75#include "xmalloc.h"
76#include "ssh.h"
77#include "rsa.h"
78#include "sshbuf.h"
79#include "sshkey.h"
80#include "authfd.h"
81#include "compat.h"
82#include "log.h"
83#include "misc.h"
84#include "digest.h"
85#include "ssherr.h"
86#include "match.h"
87
88#ifdef ENABLE_PKCS11
89#include "ssh-pkcs11.h"
90#endif
91
92#ifndef DEFAULT_PKCS11_WHITELIST
93# define DEFAULT_PKCS11_WHITELIST "/usr/lib*/*,/usr/local/lib*/*"
94#endif
95
96typedef enum {
97	AUTH_UNUSED,
98	AUTH_SOCKET,
99	AUTH_CONNECTION
100} sock_type;
101
102typedef struct {
103	int fd;
104	sock_type type;
105	struct sshbuf *input;
106	struct sshbuf *output;
107	struct sshbuf *request;
108} SocketEntry;
109
110u_int sockets_alloc = 0;
111SocketEntry *sockets = NULL;
112
113typedef struct identity {
114	TAILQ_ENTRY(identity) next;
115	struct sshkey *key;
116	char *comment;
117	char *provider;
118	time_t death;
119	u_int confirm;
120} Identity;
121
122typedef struct {
123	int nentries;
124	TAILQ_HEAD(idqueue, identity) idlist;
125} Idtab;
126
127/* private key table, one per protocol version */
128Idtab idtable[3];
129
130int max_fd = 0;
131
132/* pid of shell == parent of agent */
133pid_t parent_pid = -1;
134time_t parent_alive_interval = 0;
135
136/* pid of process for which cleanup_socket is applicable */
137pid_t cleanup_pid = 0;
138
139/* pathname and directory for AUTH_SOCKET */
140char socket_name[PATH_MAX];
141char socket_dir[PATH_MAX];
142
143/* PKCS#11 path whitelist */
144static char *pkcs11_whitelist;
145
146/* locking */
147#define LOCK_SIZE	32
148#define LOCK_SALT_SIZE	16
149#define LOCK_ROUNDS	1
150int locked = 0;
151u_char lock_pwhash[LOCK_SIZE];
152u_char lock_salt[LOCK_SALT_SIZE];
153
154extern char *__progname;
155
156/* Default lifetime in seconds (0 == forever) */
157static long lifetime = 0;
158
159static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
160
161/*
162 * Client connection count; incremented in new_socket() and decremented in
163 * close_socket().  When it reaches 0, ssh-agent will exit.  Since it is
164 * normally initialized to 1, it will never reach 0.  However, if the -x
165 * option is specified, it is initialized to 0 in main(); in that case,
166 * ssh-agent will exit as soon as it has had at least one client but no
167 * longer has any.
168 */
169static int xcount = 1;
170
171static void
172close_socket(SocketEntry *e)
173{
174	int last = 0;
175
176	if (e->type == AUTH_CONNECTION) {
177		debug("xcount %d -> %d", xcount, xcount - 1);
178		if (--xcount == 0)
179			last = 1;
180	}
181	close(e->fd);
182	e->fd = -1;
183	e->type = AUTH_UNUSED;
184	sshbuf_free(e->input);
185	sshbuf_free(e->output);
186	sshbuf_free(e->request);
187	if (last)
188		cleanup_exit(0);
189}
190
191static void
192idtab_init(void)
193{
194	int i;
195
196	for (i = 0; i <=2; i++) {
197		TAILQ_INIT(&idtable[i].idlist);
198		idtable[i].nentries = 0;
199	}
200}
201
202/* return private key table for requested protocol version */
203static Idtab *
204idtab_lookup(int version)
205{
206	if (version < 1 || version > 2)
207		fatal("internal error, bad protocol version %d", version);
208	return &idtable[version];
209}
210
211static void
212free_identity(Identity *id)
213{
214	sshkey_free(id->key);
215	free(id->provider);
216	free(id->comment);
217	free(id);
218}
219
220/* return matching private key for given public key */
221static Identity *
222lookup_identity(struct sshkey *key, int version)
223{
224	Identity *id;
225
226	Idtab *tab = idtab_lookup(version);
227	TAILQ_FOREACH(id, &tab->idlist, next) {
228		if (sshkey_equal(key, id->key))
229			return (id);
230	}
231	return (NULL);
232}
233
234/* Check confirmation of keysign request */
235static int
236confirm_key(Identity *id)
237{
238	char *p;
239	int ret = -1;
240
241	p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
242	if (p != NULL &&
243	    ask_permission("Allow use of key %s?\nKey fingerprint %s.",
244	    id->comment, p))
245		ret = 0;
246	free(p);
247
248	return (ret);
249}
250
251static void
252send_status(SocketEntry *e, int success)
253{
254	int r;
255
256	if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
257	    (r = sshbuf_put_u8(e->output, success ?
258	    SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
259		fatal("%s: buffer error: %s", __func__, ssh_err(r));
260}
261
262/* send list of supported public keys to 'client' */
263static void
264process_request_identities(SocketEntry *e, int version)
265{
266	Idtab *tab = idtab_lookup(version);
267	Identity *id;
268	struct sshbuf *msg;
269	int r;
270
271	if ((msg = sshbuf_new()) == NULL)
272		fatal("%s: sshbuf_new failed", __func__);
273	if ((r = sshbuf_put_u8(msg, (version == 1) ?
274	    SSH_AGENT_RSA_IDENTITIES_ANSWER :
275	    SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
276	    (r = sshbuf_put_u32(msg, tab->nentries)) != 0)
277		fatal("%s: buffer error: %s", __func__, ssh_err(r));
278	TAILQ_FOREACH(id, &tab->idlist, next) {
279		if (id->key->type == KEY_RSA1) {
280#ifdef WITH_SSH1
281			if ((r = sshbuf_put_u32(msg,
282			    BN_num_bits(id->key->rsa->n))) != 0 ||
283			    (r = sshbuf_put_bignum1(msg,
284			    id->key->rsa->e)) != 0 ||
285			    (r = sshbuf_put_bignum1(msg,
286			    id->key->rsa->n)) != 0)
287				fatal("%s: buffer error: %s",
288				    __func__, ssh_err(r));
289#endif
290		} else {
291			u_char *blob;
292			size_t blen;
293
294			if ((r = sshkey_to_blob(id->key, &blob, &blen)) != 0) {
295				error("%s: sshkey_to_blob: %s", __func__,
296				    ssh_err(r));
297				continue;
298			}
299			if ((r = sshbuf_put_string(msg, blob, blen)) != 0)
300				fatal("%s: buffer error: %s",
301				    __func__, ssh_err(r));
302			free(blob);
303		}
304		if ((r = sshbuf_put_cstring(msg, id->comment)) != 0)
305			fatal("%s: buffer error: %s", __func__, ssh_err(r));
306	}
307	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
308		fatal("%s: buffer error: %s", __func__, ssh_err(r));
309	sshbuf_free(msg);
310}
311
312#ifdef WITH_SSH1
313/* ssh1 only */
314static void
315process_authentication_challenge1(SocketEntry *e)
316{
317	u_char buf[32], mdbuf[16], session_id[16];
318	u_int response_type;
319	BIGNUM *challenge;
320	Identity *id;
321	int r, len;
322	struct sshbuf *msg;
323	struct ssh_digest_ctx *md;
324	struct sshkey *key;
325
326	if ((msg = sshbuf_new()) == NULL)
327		fatal("%s: sshbuf_new failed", __func__);
328	if ((key = sshkey_new(KEY_RSA1)) == NULL)
329		fatal("%s: sshkey_new failed", __func__);
330	if ((challenge = BN_new()) == NULL)
331		fatal("%s: BN_new failed", __func__);
332
333	if ((r = sshbuf_get_u32(e->request, NULL)) != 0 || /* ignored */
334	    (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
335	    (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0 ||
336	    (r = sshbuf_get_bignum1(e->request, challenge)))
337		fatal("%s: buffer error: %s", __func__, ssh_err(r));
338
339	/* Only protocol 1.1 is supported */
340	if (sshbuf_len(e->request) == 0)
341		goto failure;
342	if ((r = sshbuf_get(e->request, session_id, sizeof(session_id))) != 0 ||
343	    (r = sshbuf_get_u32(e->request, &response_type)) != 0)
344		fatal("%s: buffer error: %s", __func__, ssh_err(r));
345	if (response_type != 1)
346		goto failure;
347
348	id = lookup_identity(key, 1);
349	if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
350		struct sshkey *private = id->key;
351		/* Decrypt the challenge using the private key. */
352		if ((r = rsa_private_decrypt(challenge, challenge,
353		    private->rsa) != 0)) {
354			fatal("%s: rsa_public_encrypt: %s", __func__,
355			    ssh_err(r));
356			goto failure;	/* XXX ? */
357		}
358
359		/* The response is MD5 of decrypted challenge plus session id */
360		len = BN_num_bytes(challenge);
361		if (len <= 0 || len > 32) {
362			logit("%s: bad challenge length %d", __func__, len);
363			goto failure;
364		}
365		memset(buf, 0, 32);
366		BN_bn2bin(challenge, buf + 32 - len);
367		if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
368		    ssh_digest_update(md, buf, 32) < 0 ||
369		    ssh_digest_update(md, session_id, 16) < 0 ||
370		    ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
371			fatal("%s: md5 failed", __func__);
372		ssh_digest_free(md);
373
374		/* Send the response. */
375		if ((r = sshbuf_put_u8(msg, SSH_AGENT_RSA_RESPONSE)) != 0 ||
376		    (r = sshbuf_put(msg, mdbuf, sizeof(mdbuf))) != 0)
377			fatal("%s: buffer error: %s", __func__, ssh_err(r));
378		goto send;
379	}
380
381 failure:
382	/* Unknown identity or protocol error.  Send failure. */
383	if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
384		fatal("%s: buffer error: %s", __func__, ssh_err(r));
385 send:
386	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
387		fatal("%s: buffer error: %s", __func__, ssh_err(r));
388	sshkey_free(key);
389	BN_clear_free(challenge);
390	sshbuf_free(msg);
391}
392#endif
393
394static char *
395agent_decode_alg(struct sshkey *key, u_int flags)
396{
397	if (key->type == KEY_RSA) {
398		if (flags & SSH_AGENT_RSA_SHA2_256)
399			return "rsa-sha2-256";
400		else if (flags & SSH_AGENT_RSA_SHA2_512)
401			return "rsa-sha2-512";
402	}
403	return NULL;
404}
405
406/* ssh2 only */
407static void
408process_sign_request2(SocketEntry *e)
409{
410	u_char *blob, *data, *signature = NULL;
411	size_t blen, dlen, slen = 0;
412	u_int compat = 0, flags;
413	int r, ok = -1;
414	struct sshbuf *msg;
415	struct sshkey *key;
416	struct identity *id;
417
418	if ((msg = sshbuf_new()) == NULL)
419		fatal("%s: sshbuf_new failed", __func__);
420	if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
421	    (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
422	    (r = sshbuf_get_u32(e->request, &flags)) != 0)
423		fatal("%s: buffer error: %s", __func__, ssh_err(r));
424	if (flags & SSH_AGENT_OLD_SIGNATURE)
425		compat = SSH_BUG_SIGBLOB;
426	if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
427		error("%s: cannot parse key blob: %s", __func__, ssh_err(r));
428		goto send;
429	}
430	if ((id = lookup_identity(key, 2)) == NULL) {
431		verbose("%s: %s key not found", __func__, sshkey_type(key));
432		goto send;
433	}
434	if (id->confirm && confirm_key(id) != 0) {
435		verbose("%s: user refused key", __func__);
436		goto send;
437	}
438	if ((r = sshkey_sign(id->key, &signature, &slen,
439	    data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
440		error("%s: sshkey_sign: %s", __func__, ssh_err(r));
441		goto send;
442	}
443	/* Success */
444	ok = 0;
445 send:
446	sshkey_free(key);
447	if (ok == 0) {
448		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
449		    (r = sshbuf_put_string(msg, signature, slen)) != 0)
450			fatal("%s: buffer error: %s", __func__, ssh_err(r));
451	} else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
452		fatal("%s: buffer error: %s", __func__, ssh_err(r));
453
454	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
455		fatal("%s: buffer error: %s", __func__, ssh_err(r));
456
457	sshbuf_free(msg);
458	free(data);
459	free(blob);
460	free(signature);
461}
462
463/* shared */
464static void
465process_remove_identity(SocketEntry *e, int version)
466{
467	size_t blen;
468	int r, success = 0;
469	struct sshkey *key = NULL;
470	u_char *blob;
471#ifdef WITH_SSH1
472	u_int bits;
473#endif /* WITH_SSH1 */
474
475	switch (version) {
476#ifdef WITH_SSH1
477	case 1:
478		if ((key = sshkey_new(KEY_RSA1)) == NULL) {
479			error("%s: sshkey_new failed", __func__);
480			return;
481		}
482		if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
483		    (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
484		    (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
485			fatal("%s: buffer error: %s", __func__, ssh_err(r));
486
487		if (bits != sshkey_size(key))
488			logit("Warning: identity keysize mismatch: "
489			    "actual %u, announced %u",
490			    sshkey_size(key), bits);
491		break;
492#endif /* WITH_SSH1 */
493	case 2:
494		if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
495			fatal("%s: buffer error: %s", __func__, ssh_err(r));
496		if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
497			error("%s: sshkey_from_blob failed: %s",
498			    __func__, ssh_err(r));
499		free(blob);
500		break;
501	}
502	if (key != NULL) {
503		Identity *id = lookup_identity(key, version);
504		if (id != NULL) {
505			/*
506			 * We have this key.  Free the old key.  Since we
507			 * don't want to leave empty slots in the middle of
508			 * the array, we actually free the key there and move
509			 * all the entries between the empty slot and the end
510			 * of the array.
511			 */
512			Idtab *tab = idtab_lookup(version);
513			if (tab->nentries < 1)
514				fatal("process_remove_identity: "
515				    "internal error: tab->nentries %d",
516				    tab->nentries);
517			TAILQ_REMOVE(&tab->idlist, id, next);
518			free_identity(id);
519			tab->nentries--;
520			success = 1;
521		}
522		sshkey_free(key);
523	}
524	send_status(e, success);
525}
526
527static void
528process_remove_all_identities(SocketEntry *e, int version)
529{
530	Idtab *tab = idtab_lookup(version);
531	Identity *id;
532
533	/* Loop over all identities and clear the keys. */
534	for (id = TAILQ_FIRST(&tab->idlist); id;
535	    id = TAILQ_FIRST(&tab->idlist)) {
536		TAILQ_REMOVE(&tab->idlist, id, next);
537		free_identity(id);
538	}
539
540	/* Mark that there are no identities. */
541	tab->nentries = 0;
542
543	/* Send success. */
544	send_status(e, 1);
545}
546
547/* removes expired keys and returns number of seconds until the next expiry */
548static time_t
549reaper(void)
550{
551	time_t deadline = 0, now = monotime();
552	Identity *id, *nxt;
553	int version;
554	Idtab *tab;
555
556	for (version = 1; version < 3; version++) {
557		tab = idtab_lookup(version);
558		for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
559			nxt = TAILQ_NEXT(id, next);
560			if (id->death == 0)
561				continue;
562			if (now >= id->death) {
563				debug("expiring key '%s'", id->comment);
564				TAILQ_REMOVE(&tab->idlist, id, next);
565				free_identity(id);
566				tab->nentries--;
567			} else
568				deadline = (deadline == 0) ? id->death :
569				    MINIMUM(deadline, id->death);
570		}
571	}
572	if (deadline == 0 || deadline <= now)
573		return 0;
574	else
575		return (deadline - now);
576}
577
578/*
579 * XXX this and the corresponding serialisation function probably belongs
580 * in key.c
581 */
582#ifdef WITH_SSH1
583static int
584agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
585{
586	struct sshkey *k = NULL;
587	int r = SSH_ERR_INTERNAL_ERROR;
588
589	*kp = NULL;
590	if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
591		return SSH_ERR_ALLOC_FAIL;
592
593	if ((r = sshbuf_get_u32(m, NULL)) != 0 ||		/* ignored */
594	    (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
595	    (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
596	    (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
597	    (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
598	    /* SSH1 and SSL have p and q swapped */
599	    (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 ||	/* p */
600	    (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) 	/* q */
601		goto out;
602
603	/* Generate additional parameters */
604	if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
605		goto out;
606	/* enable blinding */
607	if (RSA_blinding_on(k->rsa, NULL) != 1) {
608		r = SSH_ERR_LIBCRYPTO_ERROR;
609		goto out;
610	}
611
612	r = 0; /* success */
613 out:
614	if (r == 0)
615		*kp = k;
616	else
617		sshkey_free(k);
618	return r;
619}
620#endif /* WITH_SSH1 */
621
622static void
623process_add_identity(SocketEntry *e, int version)
624{
625	Idtab *tab = idtab_lookup(version);
626	Identity *id;
627	int success = 0, confirm = 0;
628	u_int seconds;
629	char *comment = NULL;
630	time_t death = 0;
631	struct sshkey *k = NULL;
632	u_char ctype;
633	int r = SSH_ERR_INTERNAL_ERROR;
634
635	switch (version) {
636#ifdef WITH_SSH1
637	case 1:
638		r = agent_decode_rsa1(e->request, &k);
639		break;
640#endif /* WITH_SSH1 */
641	case 2:
642		r = sshkey_private_deserialize(e->request, &k);
643		break;
644	}
645	if (r != 0 || k == NULL ||
646	    (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
647		error("%s: decode private key: %s", __func__, ssh_err(r));
648		goto err;
649	}
650
651	while (sshbuf_len(e->request)) {
652		if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
653			error("%s: buffer error: %s", __func__, ssh_err(r));
654			goto err;
655		}
656		switch (ctype) {
657		case SSH_AGENT_CONSTRAIN_LIFETIME:
658			if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
659				error("%s: bad lifetime constraint: %s",
660				    __func__, ssh_err(r));
661				goto err;
662			}
663			death = monotime() + seconds;
664			break;
665		case SSH_AGENT_CONSTRAIN_CONFIRM:
666			confirm = 1;
667			break;
668		default:
669			error("%s: Unknown constraint %d", __func__, ctype);
670 err:
671			sshbuf_reset(e->request);
672			free(comment);
673			sshkey_free(k);
674			goto send;
675		}
676	}
677
678	success = 1;
679	if (lifetime && !death)
680		death = monotime() + lifetime;
681	if ((id = lookup_identity(k, version)) == NULL) {
682		id = xcalloc(1, sizeof(Identity));
683		id->key = k;
684		TAILQ_INSERT_TAIL(&tab->idlist, id, next);
685		/* Increment the number of identities. */
686		tab->nentries++;
687	} else {
688		sshkey_free(k);
689		free(id->comment);
690	}
691	id->comment = comment;
692	id->death = death;
693	id->confirm = confirm;
694send:
695	send_status(e, success);
696}
697
698/* XXX todo: encrypt sensitive data with passphrase */
699static void
700process_lock_agent(SocketEntry *e, int lock)
701{
702	int r, success = 0, delay;
703	char *passwd;
704	u_char passwdhash[LOCK_SIZE];
705	static u_int fail_count = 0;
706	size_t pwlen;
707
708	if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
709		fatal("%s: buffer error: %s", __func__, ssh_err(r));
710	if (pwlen == 0) {
711		debug("empty password not supported");
712	} else if (locked && !lock) {
713		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
714		    passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
715			fatal("bcrypt_pbkdf");
716		if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
717			debug("agent unlocked");
718			locked = 0;
719			fail_count = 0;
720			explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
721			success = 1;
722		} else {
723			/* delay in 0.1s increments up to 10s */
724			if (fail_count < 100)
725				fail_count++;
726			delay = 100000 * fail_count;
727			debug("unlock failed, delaying %0.1lf seconds",
728			    (double)delay/1000000);
729			usleep(delay);
730		}
731		explicit_bzero(passwdhash, sizeof(passwdhash));
732	} else if (!locked && lock) {
733		debug("agent locked");
734		locked = 1;
735		arc4random_buf(lock_salt, sizeof(lock_salt));
736		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
737		    lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
738			fatal("bcrypt_pbkdf");
739		success = 1;
740	}
741	explicit_bzero(passwd, pwlen);
742	free(passwd);
743	send_status(e, success);
744}
745
746static void
747no_identities(SocketEntry *e, u_int type)
748{
749	struct sshbuf *msg;
750	int r;
751
752	if ((msg = sshbuf_new()) == NULL)
753		fatal("%s: sshbuf_new failed", __func__);
754	if ((r = sshbuf_put_u8(msg,
755	    (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
756	    SSH_AGENT_RSA_IDENTITIES_ANSWER :
757	    SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
758	    (r = sshbuf_put_u32(msg, 0)) != 0 ||
759	    (r = sshbuf_put_stringb(e->output, msg)) != 0)
760		fatal("%s: buffer error: %s", __func__, ssh_err(r));
761	sshbuf_free(msg);
762}
763
764#ifdef ENABLE_PKCS11
765static void
766process_add_smartcard_key(SocketEntry *e)
767{
768	char *provider = NULL, *pin, canonical_provider[PATH_MAX];
769	int r, i, version, count = 0, success = 0, confirm = 0;
770	u_int seconds;
771	time_t death = 0;
772	u_char type;
773	struct sshkey **keys = NULL, *k;
774	Identity *id;
775	Idtab *tab;
776
777	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
778	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
779		fatal("%s: buffer error: %s", __func__, ssh_err(r));
780
781	while (sshbuf_len(e->request)) {
782		if ((r = sshbuf_get_u8(e->request, &type)) != 0)
783			fatal("%s: buffer error: %s", __func__, ssh_err(r));
784		switch (type) {
785		case SSH_AGENT_CONSTRAIN_LIFETIME:
786			if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
787				fatal("%s: buffer error: %s",
788				    __func__, ssh_err(r));
789			death = monotime() + seconds;
790			break;
791		case SSH_AGENT_CONSTRAIN_CONFIRM:
792			confirm = 1;
793			break;
794		default:
795			error("process_add_smartcard_key: "
796			    "Unknown constraint type %d", type);
797			goto send;
798		}
799	}
800	if (realpath(provider, canonical_provider) == NULL) {
801		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
802		    provider, strerror(errno));
803		goto send;
804	}
805	if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
806		verbose("refusing PKCS#11 add of \"%.100s\": "
807		    "provider not whitelisted", canonical_provider);
808		goto send;
809	}
810	debug("%s: add %.100s", __func__, canonical_provider);
811	if (lifetime && !death)
812		death = monotime() + lifetime;
813
814	count = pkcs11_add_provider(canonical_provider, pin, &keys);
815	for (i = 0; i < count; i++) {
816		k = keys[i];
817		version = k->type == KEY_RSA1 ? 1 : 2;
818		tab = idtab_lookup(version);
819		if (lookup_identity(k, version) == NULL) {
820			id = xcalloc(1, sizeof(Identity));
821			id->key = k;
822			id->provider = xstrdup(canonical_provider);
823			id->comment = xstrdup(canonical_provider); /* XXX */
824			id->death = death;
825			id->confirm = confirm;
826			TAILQ_INSERT_TAIL(&tab->idlist, id, next);
827			tab->nentries++;
828			success = 1;
829		} else {
830			sshkey_free(k);
831		}
832		keys[i] = NULL;
833	}
834send:
835	free(pin);
836	free(provider);
837	free(keys);
838	send_status(e, success);
839}
840
841static void
842process_remove_smartcard_key(SocketEntry *e)
843{
844	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
845	int r, version, success = 0;
846	Identity *id, *nxt;
847	Idtab *tab;
848
849	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
850	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
851		fatal("%s: buffer error: %s", __func__, ssh_err(r));
852	free(pin);
853
854	if (realpath(provider, canonical_provider) == NULL) {
855		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
856		    provider, strerror(errno));
857		goto send;
858	}
859
860	debug("%s: remove %.100s", __func__, canonical_provider);
861	for (version = 1; version < 3; version++) {
862		tab = idtab_lookup(version);
863		for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
864			nxt = TAILQ_NEXT(id, next);
865			/* Skip file--based keys */
866			if (id->provider == NULL)
867				continue;
868			if (!strcmp(canonical_provider, id->provider)) {
869				TAILQ_REMOVE(&tab->idlist, id, next);
870				free_identity(id);
871				tab->nentries--;
872			}
873		}
874	}
875	if (pkcs11_del_provider(canonical_provider) == 0)
876		success = 1;
877	else
878		error("process_remove_smartcard_key:"
879		    " pkcs11_del_provider failed");
880send:
881	free(provider);
882	send_status(e, success);
883}
884#endif /* ENABLE_PKCS11 */
885
886/* dispatch incoming messages */
887
888static void
889process_message(SocketEntry *e)
890{
891	u_int msg_len;
892	u_char type;
893	const u_char *cp;
894	int r;
895
896	if (sshbuf_len(e->input) < 5)
897		return;		/* Incomplete message. */
898	cp = sshbuf_ptr(e->input);
899	msg_len = PEEK_U32(cp);
900	if (msg_len > 256 * 1024) {
901		close_socket(e);
902		return;
903	}
904	if (sshbuf_len(e->input) < msg_len + 4)
905		return;
906
907	/* move the current input to e->request */
908	sshbuf_reset(e->request);
909	if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
910	    (r = sshbuf_get_u8(e->request, &type)) != 0)
911		fatal("%s: buffer error: %s", __func__, ssh_err(r));
912
913	/* check wheter agent is locked */
914	if (locked && type != SSH_AGENTC_UNLOCK) {
915		sshbuf_reset(e->request);
916		switch (type) {
917		case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
918		case SSH2_AGENTC_REQUEST_IDENTITIES:
919			/* send empty lists */
920			no_identities(e, type);
921			break;
922		default:
923			/* send a fail message for all other request types */
924			send_status(e, 0);
925		}
926		return;
927	}
928
929	debug("type %d", type);
930	switch (type) {
931	case SSH_AGENTC_LOCK:
932	case SSH_AGENTC_UNLOCK:
933		process_lock_agent(e, type == SSH_AGENTC_LOCK);
934		break;
935#ifdef WITH_SSH1
936	/* ssh1 */
937	case SSH_AGENTC_RSA_CHALLENGE:
938		process_authentication_challenge1(e);
939		break;
940	case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
941		process_request_identities(e, 1);
942		break;
943	case SSH_AGENTC_ADD_RSA_IDENTITY:
944	case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
945		process_add_identity(e, 1);
946		break;
947	case SSH_AGENTC_REMOVE_RSA_IDENTITY:
948		process_remove_identity(e, 1);
949		break;
950#endif
951	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
952		process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
953		break;
954	/* ssh2 */
955	case SSH2_AGENTC_SIGN_REQUEST:
956		process_sign_request2(e);
957		break;
958	case SSH2_AGENTC_REQUEST_IDENTITIES:
959		process_request_identities(e, 2);
960		break;
961	case SSH2_AGENTC_ADD_IDENTITY:
962	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
963		process_add_identity(e, 2);
964		break;
965	case SSH2_AGENTC_REMOVE_IDENTITY:
966		process_remove_identity(e, 2);
967		break;
968	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
969		process_remove_all_identities(e, 2);
970		break;
971#ifdef ENABLE_PKCS11
972	case SSH_AGENTC_ADD_SMARTCARD_KEY:
973	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
974		process_add_smartcard_key(e);
975		break;
976	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
977		process_remove_smartcard_key(e);
978		break;
979#endif /* ENABLE_PKCS11 */
980	default:
981		/* Unknown message.  Respond with failure. */
982		error("Unknown message %d", type);
983		sshbuf_reset(e->request);
984		send_status(e, 0);
985		break;
986	}
987}
988
989static void
990new_socket(sock_type type, int fd)
991{
992	u_int i, old_alloc, new_alloc;
993
994	if (type == AUTH_CONNECTION) {
995		debug("xcount %d -> %d", xcount, xcount + 1);
996		++xcount;
997	}
998	set_nonblock(fd);
999
1000	if (fd > max_fd)
1001		max_fd = fd;
1002
1003	for (i = 0; i < sockets_alloc; i++)
1004		if (sockets[i].type == AUTH_UNUSED) {
1005			sockets[i].fd = fd;
1006			if ((sockets[i].input = sshbuf_new()) == NULL)
1007				fatal("%s: sshbuf_new failed", __func__);
1008			if ((sockets[i].output = sshbuf_new()) == NULL)
1009				fatal("%s: sshbuf_new failed", __func__);
1010			if ((sockets[i].request = sshbuf_new()) == NULL)
1011				fatal("%s: sshbuf_new failed", __func__);
1012			sockets[i].type = type;
1013			return;
1014		}
1015	old_alloc = sockets_alloc;
1016	new_alloc = sockets_alloc + 10;
1017	sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
1018	for (i = old_alloc; i < new_alloc; i++)
1019		sockets[i].type = AUTH_UNUSED;
1020	sockets_alloc = new_alloc;
1021	sockets[old_alloc].fd = fd;
1022	if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
1023		fatal("%s: sshbuf_new failed", __func__);
1024	if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
1025		fatal("%s: sshbuf_new failed", __func__);
1026	if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
1027		fatal("%s: sshbuf_new failed", __func__);
1028	sockets[old_alloc].type = type;
1029}
1030
1031static int
1032prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
1033    struct timeval **tvpp)
1034{
1035	u_int i, sz;
1036	int n = 0;
1037	static struct timeval tv;
1038	time_t deadline;
1039
1040	for (i = 0; i < sockets_alloc; i++) {
1041		switch (sockets[i].type) {
1042		case AUTH_SOCKET:
1043		case AUTH_CONNECTION:
1044			n = MAXIMUM(n, sockets[i].fd);
1045			break;
1046		case AUTH_UNUSED:
1047			break;
1048		default:
1049			fatal("Unknown socket type %d", sockets[i].type);
1050			break;
1051		}
1052	}
1053
1054	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1055	if (*fdrp == NULL || sz > *nallocp) {
1056		free(*fdrp);
1057		free(*fdwp);
1058		*fdrp = xmalloc(sz);
1059		*fdwp = xmalloc(sz);
1060		*nallocp = sz;
1061	}
1062	if (n < *fdl)
1063		debug("XXX shrink: %d < %d", n, *fdl);
1064	*fdl = n;
1065	memset(*fdrp, 0, sz);
1066	memset(*fdwp, 0, sz);
1067
1068	for (i = 0; i < sockets_alloc; i++) {
1069		switch (sockets[i].type) {
1070		case AUTH_SOCKET:
1071		case AUTH_CONNECTION:
1072			FD_SET(sockets[i].fd, *fdrp);
1073			if (sshbuf_len(sockets[i].output) > 0)
1074				FD_SET(sockets[i].fd, *fdwp);
1075			break;
1076		default:
1077			break;
1078		}
1079	}
1080	deadline = reaper();
1081	if (parent_alive_interval != 0)
1082		deadline = (deadline == 0) ? parent_alive_interval :
1083		    MINIMUM(deadline, parent_alive_interval);
1084	if (deadline == 0) {
1085		*tvpp = NULL;
1086	} else {
1087		tv.tv_sec = deadline;
1088		tv.tv_usec = 0;
1089		*tvpp = &tv;
1090	}
1091	return (1);
1092}
1093
1094static void
1095after_select(fd_set *readset, fd_set *writeset)
1096{
1097	struct sockaddr_un sunaddr;
1098	socklen_t slen;
1099	char buf[1024];
1100	int len, sock, r;
1101	u_int i, orig_alloc;
1102	uid_t euid;
1103	gid_t egid;
1104
1105	for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1106		switch (sockets[i].type) {
1107		case AUTH_UNUSED:
1108			break;
1109		case AUTH_SOCKET:
1110			if (FD_ISSET(sockets[i].fd, readset)) {
1111				slen = sizeof(sunaddr);
1112				sock = accept(sockets[i].fd,
1113				    (struct sockaddr *)&sunaddr, &slen);
1114				if (sock < 0) {
1115					error("accept from AUTH_SOCKET: %s",
1116					    strerror(errno));
1117					break;
1118				}
1119				if (getpeereid(sock, &euid, &egid) < 0) {
1120					error("getpeereid %d failed: %s",
1121					    sock, strerror(errno));
1122					close(sock);
1123					break;
1124				}
1125				if ((euid != 0) && (getuid() != euid)) {
1126					error("uid mismatch: "
1127					    "peer euid %u != uid %u",
1128					    (u_int) euid, (u_int) getuid());
1129					close(sock);
1130					break;
1131				}
1132				new_socket(AUTH_CONNECTION, sock);
1133			}
1134			break;
1135		case AUTH_CONNECTION:
1136			if (sshbuf_len(sockets[i].output) > 0 &&
1137			    FD_ISSET(sockets[i].fd, writeset)) {
1138				len = write(sockets[i].fd,
1139				    sshbuf_ptr(sockets[i].output),
1140				    sshbuf_len(sockets[i].output));
1141				if (len == -1 && (errno == EAGAIN ||
1142				    errno == EWOULDBLOCK ||
1143				    errno == EINTR))
1144					continue;
1145				if (len <= 0) {
1146					close_socket(&sockets[i]);
1147					break;
1148				}
1149				if ((r = sshbuf_consume(sockets[i].output,
1150				    len)) != 0)
1151					fatal("%s: buffer error: %s",
1152					    __func__, ssh_err(r));
1153			}
1154			if (FD_ISSET(sockets[i].fd, readset)) {
1155				len = read(sockets[i].fd, buf, sizeof(buf));
1156				if (len == -1 && (errno == EAGAIN ||
1157				    errno == EWOULDBLOCK ||
1158				    errno == EINTR))
1159					continue;
1160				if (len <= 0) {
1161					close_socket(&sockets[i]);
1162					break;
1163				}
1164				if ((r = sshbuf_put(sockets[i].input,
1165				    buf, len)) != 0)
1166					fatal("%s: buffer error: %s",
1167					    __func__, ssh_err(r));
1168				explicit_bzero(buf, sizeof(buf));
1169				process_message(&sockets[i]);
1170			}
1171			break;
1172		default:
1173			fatal("Unknown type %d", sockets[i].type);
1174		}
1175}
1176
1177static void
1178cleanup_socket(void)
1179{
1180	if (cleanup_pid != 0 && getpid() != cleanup_pid)
1181		return;
1182	debug("%s: cleanup", __func__);
1183	if (socket_name[0])
1184		unlink(socket_name);
1185	if (socket_dir[0])
1186		rmdir(socket_dir);
1187}
1188
1189void
1190cleanup_exit(int i)
1191{
1192	cleanup_socket();
1193	_exit(i);
1194}
1195
1196/*ARGSUSED*/
1197static void
1198cleanup_handler(int sig)
1199{
1200	cleanup_socket();
1201#ifdef ENABLE_PKCS11
1202	pkcs11_terminate();
1203#endif
1204	_exit(2);
1205}
1206
1207static void
1208check_parent_exists(void)
1209{
1210	/*
1211	 * If our parent has exited then getppid() will return (pid_t)1,
1212	 * so testing for that should be safe.
1213	 */
1214	if (parent_pid != -1 && getppid() != parent_pid) {
1215		/* printf("Parent has died - Authentication agent exiting.\n"); */
1216		cleanup_socket();
1217		_exit(2);
1218	}
1219}
1220
1221static void
1222usage(void)
1223{
1224	fprintf(stderr,
1225	    "usage: ssh-agent [-c | -s] [-Ddx] [-a bind_address] [-E fingerprint_hash]\n"
1226	    "                 [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1227	    "       ssh-agent [-c | -s] -k\n");
1228	exit(1);
1229}
1230
1231int
1232main(int ac, char **av)
1233{
1234	int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1235	int sock, fd, ch, result, saved_errno;
1236	u_int nalloc;
1237	char *shell, *format, *pidstr, *agentsocket = NULL;
1238	fd_set *readsetp = NULL, *writesetp = NULL;
1239#ifdef HAVE_SETRLIMIT
1240	struct rlimit rlim;
1241#endif
1242	extern int optind;
1243	extern char *optarg;
1244	pid_t pid;
1245	char pidstrbuf[1 + 3 * sizeof pid];
1246	struct timeval *tvp = NULL;
1247	size_t len;
1248	mode_t prev_mask;
1249
1250	ssh_malloc_init();	/* must be called before any mallocs */
1251	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1252	sanitise_stdfd();
1253
1254	/* drop */
1255	setegid(getgid());
1256	setgid(getgid());
1257	setuid(geteuid());
1258
1259	platform_disable_tracing(0);	/* strict=no */
1260
1261#ifdef WITH_OPENSSL
1262	OpenSSL_add_all_algorithms();
1263#endif
1264
1265	__progname = ssh_get_progname(av[0]);
1266	seed_rng();
1267
1268	while ((ch = getopt(ac, av, "cDdksE:a:P:t:x")) != -1) {
1269		switch (ch) {
1270		case 'E':
1271			fingerprint_hash = ssh_digest_alg_by_name(optarg);
1272			if (fingerprint_hash == -1)
1273				fatal("Invalid hash algorithm \"%s\"", optarg);
1274			break;
1275		case 'c':
1276			if (s_flag)
1277				usage();
1278			c_flag++;
1279			break;
1280		case 'k':
1281			k_flag++;
1282			break;
1283		case 'P':
1284			if (pkcs11_whitelist != NULL)
1285				fatal("-P option already specified");
1286			pkcs11_whitelist = xstrdup(optarg);
1287			break;
1288		case 's':
1289			if (c_flag)
1290				usage();
1291			s_flag++;
1292			break;
1293		case 'd':
1294			if (d_flag || D_flag)
1295				usage();
1296			d_flag++;
1297			break;
1298		case 'D':
1299			if (d_flag || D_flag)
1300				usage();
1301			D_flag++;
1302			break;
1303		case 'a':
1304			agentsocket = optarg;
1305			break;
1306		case 't':
1307			if ((lifetime = convtime(optarg)) == -1) {
1308				fprintf(stderr, "Invalid lifetime\n");
1309				usage();
1310			}
1311			break;
1312		case 'x':
1313			xcount = 0;
1314			break;
1315		default:
1316			usage();
1317		}
1318	}
1319	ac -= optind;
1320	av += optind;
1321
1322	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1323		usage();
1324
1325	if (pkcs11_whitelist == NULL)
1326		pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
1327
1328	if (ac == 0 && !c_flag && !s_flag) {
1329		shell = getenv("SHELL");
1330		if (shell != NULL && (len = strlen(shell)) > 2 &&
1331		    strncmp(shell + len - 3, "csh", 3) == 0)
1332			c_flag = 1;
1333	}
1334	if (k_flag) {
1335		const char *errstr = NULL;
1336
1337		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1338		if (pidstr == NULL) {
1339			fprintf(stderr, "%s not set, cannot kill agent\n",
1340			    SSH_AGENTPID_ENV_NAME);
1341			exit(1);
1342		}
1343		pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1344		if (errstr) {
1345			fprintf(stderr,
1346			    "%s=\"%s\", which is not a good PID: %s\n",
1347			    SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1348			exit(1);
1349		}
1350		if (kill(pid, SIGTERM) == -1) {
1351			perror("kill");
1352			exit(1);
1353		}
1354		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1355		printf(format, SSH_AUTHSOCKET_ENV_NAME);
1356		printf(format, SSH_AGENTPID_ENV_NAME);
1357		printf("echo Agent pid %ld killed;\n", (long)pid);
1358		exit(0);
1359	}
1360	parent_pid = getpid();
1361
1362	if (agentsocket == NULL) {
1363		/* Create private directory for agent socket */
1364		mktemp_proto(socket_dir, sizeof(socket_dir));
1365		if (mkdtemp(socket_dir) == NULL) {
1366			perror("mkdtemp: private socket dir");
1367			exit(1);
1368		}
1369		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1370		    (long)parent_pid);
1371	} else {
1372		/* Try to use specified agent socket */
1373		socket_dir[0] = '\0';
1374		strlcpy(socket_name, agentsocket, sizeof socket_name);
1375	}
1376
1377	/*
1378	 * Create socket early so it will exist before command gets run from
1379	 * the parent.
1380	 */
1381	prev_mask = umask(0177);
1382	sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1383	if (sock < 0) {
1384		/* XXX - unix_listener() calls error() not perror() */
1385		*socket_name = '\0'; /* Don't unlink any existing file */
1386		cleanup_exit(1);
1387	}
1388	umask(prev_mask);
1389
1390	/*
1391	 * Fork, and have the parent execute the command, if any, or present
1392	 * the socket data.  The child continues as the authentication agent.
1393	 */
1394	if (D_flag || d_flag) {
1395		log_init(__progname,
1396		    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1397		    SYSLOG_FACILITY_AUTH, 1);
1398		format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1399		printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1400		    SSH_AUTHSOCKET_ENV_NAME);
1401		printf("echo Agent pid %ld;\n", (long)parent_pid);
1402		fflush(stdout);
1403		goto skip;
1404	}
1405	pid = fork();
1406	if (pid == -1) {
1407		perror("fork");
1408		cleanup_exit(1);
1409	}
1410	if (pid != 0) {		/* Parent - execute the given command. */
1411		close(sock);
1412		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1413		if (ac == 0) {
1414			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1415			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1416			    SSH_AUTHSOCKET_ENV_NAME);
1417			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1418			    SSH_AGENTPID_ENV_NAME);
1419			printf("echo Agent pid %ld;\n", (long)pid);
1420			exit(0);
1421		}
1422		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1423		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1424			perror("setenv");
1425			exit(1);
1426		}
1427		execvp(av[0], av);
1428		perror(av[0]);
1429		exit(1);
1430	}
1431	/* child */
1432	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1433
1434	if (setsid() == -1) {
1435		error("setsid: %s", strerror(errno));
1436		cleanup_exit(1);
1437	}
1438
1439	(void)chdir("/");
1440	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1441		/* XXX might close listen socket */
1442		(void)dup2(fd, STDIN_FILENO);
1443		(void)dup2(fd, STDOUT_FILENO);
1444		(void)dup2(fd, STDERR_FILENO);
1445		if (fd > 2)
1446			close(fd);
1447	}
1448
1449#ifdef HAVE_SETRLIMIT
1450	/* deny core dumps, since memory contains unencrypted private keys */
1451	rlim.rlim_cur = rlim.rlim_max = 0;
1452	if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1453		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1454		cleanup_exit(1);
1455	}
1456#endif
1457
1458skip:
1459
1460	cleanup_pid = getpid();
1461
1462#ifdef ENABLE_PKCS11
1463	pkcs11_init(0);
1464#endif
1465	new_socket(AUTH_SOCKET, sock);
1466	if (ac > 0)
1467		parent_alive_interval = 10;
1468	idtab_init();
1469	signal(SIGPIPE, SIG_IGN);
1470	signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1471	signal(SIGHUP, cleanup_handler);
1472	signal(SIGTERM, cleanup_handler);
1473	nalloc = 0;
1474
1475	if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1476		fatal("%s: pledge: %s", __progname, strerror(errno));
1477	platform_pledge_agent();
1478
1479	while (1) {
1480		prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1481		result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1482		saved_errno = errno;
1483		if (parent_alive_interval != 0)
1484			check_parent_exists();
1485		(void) reaper();	/* remove expired keys */
1486		if (result < 0) {
1487			if (saved_errno == EINTR)
1488				continue;
1489			fatal("select: %s", strerror(saved_errno));
1490		} else if (result > 0)
1491			after_select(readsetp, writesetp);
1492	}
1493	/* NOTREACHED */
1494}
1495