xref: /titanic_41/usr/src/cmd/ssh/ssh-agent/ssh-agent.c (revision bdb9230ac765cb7af3fc1f4119caf2c5720dceb3)
1 /*
2  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*
7  * Author: Tatu Ylonen <ylo@cs.hut.fi>
8  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
9  *                    All rights reserved
10  * The authentication agent program.
11  *
12  * As far as I am concerned, the code I have written for this software
13  * can be used freely for any purpose.  Any derived versions of this
14  * software must be clearly marked as such, and if the derived work is
15  * incompatible with the protocol description in the RFC file, it must be
16  * called by a name other than "ssh" or "Secure Shell".
17  *
18  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39  */
40 
41 #include "includes.h"
42 #include "sys-queue.h"
43 RCSID("$OpenBSD: ssh-agent.c,v 1.105 2002/10/01 20:34:12 markus Exp $");
44 
45 #ifdef HAVE_SOLARIS_PRIVILEGE
46 #include <priv.h>
47 #endif /* HAVE_SOLARIS_PRIVILEGE */
48 
49 #include <openssl/evp.h>
50 #include <openssl/md5.h>
51 
52 #include "ssh.h"
53 #include "rsa.h"
54 #include "buffer.h"
55 #include "bufaux.h"
56 #include "xmalloc.h"
57 #include "getput.h"
58 #include "key.h"
59 #include "authfd.h"
60 #include "compat.h"
61 #include "log.h"
62 
63 typedef enum {
64 	AUTH_UNUSED,
65 	AUTH_SOCKET,
66 	AUTH_CONNECTION
67 } sock_type;
68 
69 typedef struct {
70 	int fd;
71 	sock_type type;
72 	Buffer input;
73 	Buffer output;
74 	Buffer request;
75 } SocketEntry;
76 
77 u_int sockets_alloc = 0;
78 SocketEntry *sockets = NULL;
79 
80 typedef struct identity {
81 	TAILQ_ENTRY(identity) next;
82 	Key *key;
83 	char *comment;
84 	u_int death;
85 } Identity;
86 
87 typedef struct {
88 	int nentries;
89 	TAILQ_HEAD(idqueue, identity) idlist;
90 } Idtab;
91 
92 /* private key table, one per protocol version */
93 Idtab idtable[3];
94 
95 int max_fd = 0;
96 
97 /* pid of shell == parent of agent */
98 pid_t parent_pid = -1;
99 
100 /* pathname and directory for AUTH_SOCKET */
101 char socket_name[1024];
102 char socket_dir[1024];
103 
104 /* locking */
105 int locked = 0;
106 char *lock_passwd = NULL;
107 
108 #ifdef HAVE___PROGNAME
109 extern char *__progname;
110 #else
111 char *__progname;
112 #endif
113 
114 static void
115 close_socket(SocketEntry *e)
116 {
117 	close(e->fd);
118 	e->fd = -1;
119 	e->type = AUTH_UNUSED;
120 	buffer_free(&e->input);
121 	buffer_free(&e->output);
122 	buffer_free(&e->request);
123 }
124 
125 static void
126 idtab_init(void)
127 {
128 	int i;
129 
130 	for (i = 0; i <=2; i++) {
131 		TAILQ_INIT(&idtable[i].idlist);
132 		idtable[i].nentries = 0;
133 	}
134 }
135 
136 /* return private key table for requested protocol version */
137 static Idtab *
138 idtab_lookup(int version)
139 {
140 	if (version < 1 || version > 2)
141 		fatal("internal error, bad protocol version %d", version);
142 	return &idtable[version];
143 }
144 
145 static void
146 free_identity(Identity *id)
147 {
148 	key_free(id->key);
149 	xfree(id->comment);
150 	xfree(id);
151 }
152 
153 /* return matching private key for given public key */
154 static Identity *
155 lookup_identity(Key *key, int version)
156 {
157 	Identity *id;
158 
159 	Idtab *tab = idtab_lookup(version);
160 	TAILQ_FOREACH(id, &tab->idlist, next) {
161 		if (key_equal(key, id->key))
162 			return (id);
163 	}
164 	return (NULL);
165 }
166 
167 /* send list of supported public keys to 'client' */
168 static void
169 process_request_identities(SocketEntry *e, int version)
170 {
171 	Idtab *tab = idtab_lookup(version);
172 	Identity *id;
173 	Buffer msg;
174 
175 	buffer_init(&msg);
176 	buffer_put_char(&msg, (version == 1) ?
177 	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
178 	buffer_put_int(&msg, tab->nentries);
179 	TAILQ_FOREACH(id, &tab->idlist, next) {
180 		if (id->key->type == KEY_RSA1) {
181 			buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
182 			buffer_put_bignum(&msg, id->key->rsa->e);
183 			buffer_put_bignum(&msg, id->key->rsa->n);
184 		} else {
185 			u_char *blob;
186 			u_int blen;
187 			key_to_blob(id->key, &blob, &blen);
188 			buffer_put_string(&msg, blob, blen);
189 			xfree(blob);
190 		}
191 		buffer_put_cstring(&msg, id->comment);
192 	}
193 	buffer_put_int(&e->output, buffer_len(&msg));
194 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
195 	buffer_free(&msg);
196 }
197 
198 /* ssh1 only */
199 static void
200 process_authentication_challenge1(SocketEntry *e)
201 {
202 	u_char buf[32], mdbuf[16], session_id[16];
203 	u_int response_type;
204 	BIGNUM *challenge;
205 	Identity *id;
206 	int i, len;
207 	Buffer msg;
208 	MD5_CTX md;
209 	Key *key;
210 
211 	buffer_init(&msg);
212 	key = key_new(KEY_RSA1);
213 	if ((challenge = BN_new()) == NULL)
214 		fatal("process_authentication_challenge1: BN_new failed");
215 
216 	(void) buffer_get_int(&e->request);			/* ignored */
217 	buffer_get_bignum(&e->request, key->rsa->e);
218 	buffer_get_bignum(&e->request, key->rsa->n);
219 	buffer_get_bignum(&e->request, challenge);
220 
221 	/* Only protocol 1.1 is supported */
222 	if (buffer_len(&e->request) == 0)
223 		goto failure;
224 	buffer_get(&e->request, session_id, 16);
225 	response_type = buffer_get_int(&e->request);
226 	if (response_type != 1)
227 		goto failure;
228 
229 	id = lookup_identity(key, 1);
230 	if (id != NULL) {
231 		Key *private = id->key;
232 		/* Decrypt the challenge using the private key. */
233 		if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
234 			goto failure;
235 
236 		/* The response is MD5 of decrypted challenge plus session id. */
237 		len = BN_num_bytes(challenge);
238 		if (len <= 0 || len > 32) {
239 			log("process_authentication_challenge: bad challenge length %d", len);
240 			goto failure;
241 		}
242 		memset(buf, 0, 32);
243 		BN_bn2bin(challenge, buf + 32 - len);
244 		MD5_Init(&md);
245 		MD5_Update(&md, buf, 32);
246 		MD5_Update(&md, session_id, 16);
247 		MD5_Final(mdbuf, &md);
248 
249 		/* Send the response. */
250 		buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
251 		for (i = 0; i < 16; i++)
252 			buffer_put_char(&msg, mdbuf[i]);
253 		goto send;
254 	}
255 
256 failure:
257 	/* Unknown identity or protocol error.  Send failure. */
258 	buffer_put_char(&msg, SSH_AGENT_FAILURE);
259 send:
260 	buffer_put_int(&e->output, buffer_len(&msg));
261 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
262 	key_free(key);
263 	BN_clear_free(challenge);
264 	buffer_free(&msg);
265 }
266 
267 /* ssh2 only */
268 static void
269 process_sign_request2(SocketEntry *e)
270 {
271 	u_char *blob, *data, *signature = NULL;
272 	u_int blen, dlen, slen = 0;
273 	int ok = -1, flags;
274 	Buffer msg;
275 	Key *key;
276 
277 	datafellows = 0;
278 
279 	blob = buffer_get_string(&e->request, &blen);
280 	data = buffer_get_string(&e->request, &dlen);
281 
282 	flags = buffer_get_int(&e->request);
283 	if (flags & SSH_AGENT_OLD_SIGNATURE)
284 		datafellows = SSH_BUG_SIGBLOB;
285 
286 	key = key_from_blob(blob, blen);
287 	if (key != NULL) {
288 		Identity *id = lookup_identity(key, 2);
289 		if (id != NULL)
290 			ok = key_sign(id->key, &signature, &slen, data, dlen);
291 	}
292 	key_free(key);
293 	buffer_init(&msg);
294 	if (ok == 0) {
295 		buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
296 		buffer_put_string(&msg, signature, slen);
297 	} else {
298 		buffer_put_char(&msg, SSH_AGENT_FAILURE);
299 	}
300 	buffer_put_int(&e->output, buffer_len(&msg));
301 	buffer_append(&e->output, buffer_ptr(&msg),
302 	    buffer_len(&msg));
303 	buffer_free(&msg);
304 	xfree(data);
305 	xfree(blob);
306 	if (signature != NULL)
307 		xfree(signature);
308 }
309 
310 /* shared */
311 static void
312 process_remove_identity(SocketEntry *e, int version)
313 {
314 	u_int blen, bits;
315 	int success = 0;
316 	Key *key = NULL;
317 	u_char *blob;
318 
319 	switch (version) {
320 	case 1:
321 		key = key_new(KEY_RSA1);
322 		bits = buffer_get_int(&e->request);
323 		buffer_get_bignum(&e->request, key->rsa->e);
324 		buffer_get_bignum(&e->request, key->rsa->n);
325 
326 		if (bits != key_size(key))
327 			log("Warning: identity keysize mismatch: actual %u, announced %u",
328 			    key_size(key), bits);
329 		break;
330 	case 2:
331 		blob = buffer_get_string(&e->request, &blen);
332 		key = key_from_blob(blob, blen);
333 		xfree(blob);
334 		break;
335 	}
336 	if (key != NULL) {
337 		Identity *id = lookup_identity(key, version);
338 		if (id != NULL) {
339 			/*
340 			 * We have this key.  Free the old key.  Since we
341 			 * don\'t want to leave empty slots in the middle of
342 			 * the array, we actually free the key there and move
343 			 * all the entries between the empty slot and the end
344 			 * of the array.
345 			 */
346 			Idtab *tab = idtab_lookup(version);
347 			if (tab->nentries < 1)
348 				fatal("process_remove_identity: "
349 				    "internal error: tab->nentries %d",
350 				    tab->nentries);
351 			TAILQ_REMOVE(&tab->idlist, id, next);
352 			free_identity(id);
353 			tab->nentries--;
354 			success = 1;
355 		}
356 		key_free(key);
357 	}
358 	buffer_put_int(&e->output, 1);
359 	buffer_put_char(&e->output,
360 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
361 }
362 
363 static void
364 process_remove_all_identities(SocketEntry *e, int version)
365 {
366 	Idtab *tab = idtab_lookup(version);
367 	Identity *id;
368 
369 	/* Loop over all identities and clear the keys. */
370 	for (id = TAILQ_FIRST(&tab->idlist); id;
371 	    id = TAILQ_FIRST(&tab->idlist)) {
372 		TAILQ_REMOVE(&tab->idlist, id, next);
373 		free_identity(id);
374 	}
375 
376 	/* Mark that there are no identities. */
377 	tab->nentries = 0;
378 
379 	/* Send success. */
380 	buffer_put_int(&e->output, 1);
381 	buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
382 }
383 
384 static void
385 reaper(void)
386 {
387 	u_int now = time(NULL);
388 	Identity *id, *nxt;
389 	int version;
390 	Idtab *tab;
391 
392 	for (version = 1; version < 3; version++) {
393 		tab = idtab_lookup(version);
394 		for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
395 			nxt = TAILQ_NEXT(id, next);
396 			if (id->death != 0 && now >= id->death) {
397 				TAILQ_REMOVE(&tab->idlist, id, next);
398 				free_identity(id);
399 				tab->nentries--;
400 			}
401 		}
402 	}
403 }
404 
405 static void
406 process_add_identity(SocketEntry *e, int version)
407 {
408 	Idtab *tab = idtab_lookup(version);
409 	int type, success = 0, death = 0;
410 	char *type_name, *comment;
411 	Key *k = NULL;
412 
413 	switch (version) {
414 	case 1:
415 		k = key_new_private(KEY_RSA1);
416 		(void) buffer_get_int(&e->request);		/* ignored */
417 		buffer_get_bignum(&e->request, k->rsa->n);
418 		buffer_get_bignum(&e->request, k->rsa->e);
419 		buffer_get_bignum(&e->request, k->rsa->d);
420 		buffer_get_bignum(&e->request, k->rsa->iqmp);
421 
422 		/* SSH and SSL have p and q swapped */
423 		buffer_get_bignum(&e->request, k->rsa->q);	/* p */
424 		buffer_get_bignum(&e->request, k->rsa->p);	/* q */
425 
426 		/* Generate additional parameters */
427 		rsa_generate_additional_parameters(k->rsa);
428 		break;
429 	case 2:
430 		type_name = buffer_get_string(&e->request, NULL);
431 		type = key_type_from_name(type_name);
432 		xfree(type_name);
433 		switch (type) {
434 		case KEY_DSA:
435 			k = key_new_private(type);
436 			buffer_get_bignum2(&e->request, k->dsa->p);
437 			buffer_get_bignum2(&e->request, k->dsa->q);
438 			buffer_get_bignum2(&e->request, k->dsa->g);
439 			buffer_get_bignum2(&e->request, k->dsa->pub_key);
440 			buffer_get_bignum2(&e->request, k->dsa->priv_key);
441 			break;
442 		case KEY_RSA:
443 			k = key_new_private(type);
444 			buffer_get_bignum2(&e->request, k->rsa->n);
445 			buffer_get_bignum2(&e->request, k->rsa->e);
446 			buffer_get_bignum2(&e->request, k->rsa->d);
447 			buffer_get_bignum2(&e->request, k->rsa->iqmp);
448 			buffer_get_bignum2(&e->request, k->rsa->p);
449 			buffer_get_bignum2(&e->request, k->rsa->q);
450 
451 			/* Generate additional parameters */
452 			rsa_generate_additional_parameters(k->rsa);
453 			break;
454 		default:
455 			buffer_clear(&e->request);
456 			goto send;
457 		}
458 		break;
459 	}
460 	comment = buffer_get_string(&e->request, NULL);
461 	if (k == NULL) {
462 		xfree(comment);
463 		goto send;
464 	}
465 	success = 1;
466 	while (buffer_len(&e->request)) {
467 		switch (buffer_get_char(&e->request)) {
468 		case SSH_AGENT_CONSTRAIN_LIFETIME:
469 			death = time(NULL) + buffer_get_int(&e->request);
470 			break;
471 		default:
472 			break;
473 		}
474 	}
475 	if (lookup_identity(k, version) == NULL) {
476 		Identity *id = xmalloc(sizeof(Identity));
477 		id->key = k;
478 		id->comment = comment;
479 		id->death = death;
480 		TAILQ_INSERT_TAIL(&tab->idlist, id, next);
481 		/* Increment the number of identities. */
482 		tab->nentries++;
483 	} else {
484 		key_free(k);
485 		xfree(comment);
486 	}
487 send:
488 	buffer_put_int(&e->output, 1);
489 	buffer_put_char(&e->output,
490 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
491 }
492 
493 /* XXX todo: encrypt sensitive data with passphrase */
494 static void
495 process_lock_agent(SocketEntry *e, int lock)
496 {
497 	int success = 0;
498 	char *passwd;
499 
500 	passwd = buffer_get_string(&e->request, NULL);
501 	if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
502 		locked = 0;
503 		memset(lock_passwd, 0, strlen(lock_passwd));
504 		xfree(lock_passwd);
505 		lock_passwd = NULL;
506 		success = 1;
507 	} else if (!locked && lock) {
508 		locked = 1;
509 		lock_passwd = xstrdup(passwd);
510 		success = 1;
511 	}
512 	memset(passwd, 0, strlen(passwd));
513 	xfree(passwd);
514 
515 	buffer_put_int(&e->output, 1);
516 	buffer_put_char(&e->output,
517 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
518 }
519 
520 static void
521 no_identities(SocketEntry *e, u_int type)
522 {
523 	Buffer msg;
524 
525 	buffer_init(&msg);
526 	buffer_put_char(&msg,
527 	    (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
528 	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
529 	buffer_put_int(&msg, 0);
530 	buffer_put_int(&e->output, buffer_len(&msg));
531 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
532 	buffer_free(&msg);
533 }
534 
535 /* dispatch incoming messages */
536 
537 static void
538 process_message(SocketEntry *e)
539 {
540 	u_int msg_len, type;
541 	u_char *cp;
542 
543 	/* kill dead keys */
544 	reaper();
545 
546 	if (buffer_len(&e->input) < 5)
547 		return;		/* Incomplete message. */
548 	cp = buffer_ptr(&e->input);
549 	msg_len = GET_32BIT(cp);
550 	if (msg_len > 256 * 1024) {
551 		close_socket(e);
552 		return;
553 	}
554 	if (buffer_len(&e->input) < msg_len + 4)
555 		return;
556 
557 	/* move the current input to e->request */
558 	buffer_consume(&e->input, 4);
559 	buffer_clear(&e->request);
560 	buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
561 	buffer_consume(&e->input, msg_len);
562 	type = buffer_get_char(&e->request);
563 
564 	/* check wheter agent is locked */
565 	if (locked && type != SSH_AGENTC_UNLOCK) {
566 		buffer_clear(&e->request);
567 		switch (type) {
568 		case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
569 		case SSH2_AGENTC_REQUEST_IDENTITIES:
570 			/* send empty lists */
571 			no_identities(e, type);
572 			break;
573 		default:
574 			/* send a fail message for all other request types */
575 			buffer_put_int(&e->output, 1);
576 			buffer_put_char(&e->output, SSH_AGENT_FAILURE);
577 		}
578 		return;
579 	}
580 
581 	debug("type %d", type);
582 	switch (type) {
583 	case SSH_AGENTC_LOCK:
584 	case SSH_AGENTC_UNLOCK:
585 		process_lock_agent(e, type == SSH_AGENTC_LOCK);
586 		break;
587 	/* ssh1 */
588 	case SSH_AGENTC_RSA_CHALLENGE:
589 		process_authentication_challenge1(e);
590 		break;
591 	case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
592 		process_request_identities(e, 1);
593 		break;
594 	case SSH_AGENTC_ADD_RSA_IDENTITY:
595 	case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
596 		process_add_identity(e, 1);
597 		break;
598 	case SSH_AGENTC_REMOVE_RSA_IDENTITY:
599 		process_remove_identity(e, 1);
600 		break;
601 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
602 		process_remove_all_identities(e, 1);
603 		break;
604 	/* ssh2 */
605 	case SSH2_AGENTC_SIGN_REQUEST:
606 		process_sign_request2(e);
607 		break;
608 	case SSH2_AGENTC_REQUEST_IDENTITIES:
609 		process_request_identities(e, 2);
610 		break;
611 	case SSH2_AGENTC_ADD_IDENTITY:
612 	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
613 		process_add_identity(e, 2);
614 		break;
615 	case SSH2_AGENTC_REMOVE_IDENTITY:
616 		process_remove_identity(e, 2);
617 		break;
618 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
619 		process_remove_all_identities(e, 2);
620 		break;
621 	default:
622 		/* Unknown message.  Respond with failure. */
623 		error("Unknown message %d", type);
624 		buffer_clear(&e->request);
625 		buffer_put_int(&e->output, 1);
626 		buffer_put_char(&e->output, SSH_AGENT_FAILURE);
627 		break;
628 	}
629 }
630 
631 static void
632 new_socket(sock_type type, int fd)
633 {
634 	u_int i, old_alloc;
635 
636 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
637 		error("fcntl O_NONBLOCK: %s", strerror(errno));
638 
639 	if (fd > max_fd)
640 		max_fd = fd;
641 
642 	for (i = 0; i < sockets_alloc; i++)
643 		if (sockets[i].type == AUTH_UNUSED) {
644 			sockets[i].fd = fd;
645 			sockets[i].type = type;
646 			buffer_init(&sockets[i].input);
647 			buffer_init(&sockets[i].output);
648 			buffer_init(&sockets[i].request);
649 			return;
650 		}
651 	old_alloc = sockets_alloc;
652 	sockets_alloc += 10;
653 	if (sockets)
654 		sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
655 	else
656 		sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
657 	for (i = old_alloc; i < sockets_alloc; i++)
658 		sockets[i].type = AUTH_UNUSED;
659 	sockets[old_alloc].type = type;
660 	sockets[old_alloc].fd = fd;
661 	buffer_init(&sockets[old_alloc].input);
662 	buffer_init(&sockets[old_alloc].output);
663 	buffer_init(&sockets[old_alloc].request);
664 }
665 
666 static int
667 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, int *nallocp)
668 {
669 	u_int i, sz;
670 	int n = 0;
671 
672 	for (i = 0; i < sockets_alloc; i++) {
673 		switch (sockets[i].type) {
674 		case AUTH_SOCKET:
675 		case AUTH_CONNECTION:
676 			n = MAX(n, sockets[i].fd);
677 			break;
678 		case AUTH_UNUSED:
679 			break;
680 		default:
681 			fatal("Unknown socket type %d", sockets[i].type);
682 			break;
683 		}
684 	}
685 
686 	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
687 	if (*fdrp == NULL || sz > *nallocp) {
688 		if (*fdrp)
689 			xfree(*fdrp);
690 		if (*fdwp)
691 			xfree(*fdwp);
692 		*fdrp = xmalloc(sz);
693 		*fdwp = xmalloc(sz);
694 		*nallocp = sz;
695 	}
696 	if (n < *fdl)
697 		debug("XXX shrink: %d < %d", n, *fdl);
698 	*fdl = n;
699 	memset(*fdrp, 0, sz);
700 	memset(*fdwp, 0, sz);
701 
702 	for (i = 0; i < sockets_alloc; i++) {
703 		switch (sockets[i].type) {
704 		case AUTH_SOCKET:
705 		case AUTH_CONNECTION:
706 			FD_SET(sockets[i].fd, *fdrp);
707 			if (buffer_len(&sockets[i].output) > 0)
708 				FD_SET(sockets[i].fd, *fdwp);
709 			break;
710 		default:
711 			break;
712 		}
713 	}
714 	return (1);
715 }
716 
717 static void
718 after_select(fd_set *readset, fd_set *writeset)
719 {
720 	struct sockaddr_un sunaddr;
721 	socklen_t slen;
722 	char buf[1024];
723 	int len, sock;
724 	u_int i;
725 	uid_t euid;
726 	gid_t egid;
727 
728 	for (i = 0; i < sockets_alloc; i++)
729 		switch (sockets[i].type) {
730 		case AUTH_UNUSED:
731 			break;
732 		case AUTH_SOCKET:
733 			if (FD_ISSET(sockets[i].fd, readset)) {
734 				slen = sizeof(sunaddr);
735 				sock = accept(sockets[i].fd,
736 				    (struct sockaddr *) &sunaddr, &slen);
737 				if (sock < 0) {
738 					error("accept from AUTH_SOCKET: %s",
739 					    strerror(errno));
740 					break;
741 				}
742 				if (getpeereid(sock, &euid, &egid) < 0) {
743 					error("getpeereid %d failed: %s",
744 					    sock, strerror(errno));
745 					close(sock);
746 					break;
747 				}
748 				if ((euid != 0) && (getuid() != euid)) {
749 					error("uid mismatch: "
750 					    "peer euid %u != uid %u",
751 					    (u_int) euid, (u_int) getuid());
752 					close(sock);
753 					break;
754 				}
755 				new_socket(AUTH_CONNECTION, sock);
756 			}
757 			break;
758 		case AUTH_CONNECTION:
759 			if (buffer_len(&sockets[i].output) > 0 &&
760 			    FD_ISSET(sockets[i].fd, writeset)) {
761 				do {
762 					len = write(sockets[i].fd,
763 					    buffer_ptr(&sockets[i].output),
764 					    buffer_len(&sockets[i].output));
765 					if (len == -1 && (errno == EAGAIN ||
766 					    errno == EINTR))
767 						continue;
768 					break;
769 				} while (1);
770 				if (len <= 0) {
771 					close_socket(&sockets[i]);
772 					break;
773 				}
774 				buffer_consume(&sockets[i].output, len);
775 			}
776 			if (FD_ISSET(sockets[i].fd, readset)) {
777 				do {
778 					len = read(sockets[i].fd, buf, sizeof(buf));
779 					if (len == -1 && (errno == EAGAIN ||
780 					    errno == EINTR))
781 						continue;
782 					break;
783 				} while (1);
784 				if (len <= 0) {
785 					close_socket(&sockets[i]);
786 					break;
787 				}
788 				buffer_append(&sockets[i].input, buf, len);
789 				process_message(&sockets[i]);
790 			}
791 			break;
792 		default:
793 			fatal("Unknown type %d", sockets[i].type);
794 		}
795 }
796 
797 static void
798 cleanup_socket(void *p)
799 {
800 	if (socket_name[0])
801 		unlink(socket_name);
802 	if (socket_dir[0])
803 		rmdir(socket_dir);
804 }
805 
806 static void
807 cleanup_exit(int i)
808 {
809 	cleanup_socket(NULL);
810 	exit(i);
811 }
812 
813 static void
814 cleanup_handler(int sig)
815 {
816 	cleanup_socket(NULL);
817 	_exit(2);
818 }
819 
820 static void
821 check_parent_exists(int sig)
822 {
823 	int save_errno = errno;
824 
825 	if (parent_pid != -1 && getppid() != parent_pid) {
826 		/* printf("Parent has died - Authentication agent exiting.\n"); */
827 		cleanup_handler(sig); /* safe */
828 	}
829 	signal(SIGALRM, check_parent_exists);
830 	alarm(10);
831 	errno = save_errno;
832 }
833 
834 static void
835 usage(void)
836 {
837 	fprintf(stderr,
838 		gettext("Usage: %s [options] [command [args ...]]\n"
839 		    "Options:\n"
840 		    "  -c          Generate C-shell commands on stdout.\n"
841 		    "  -s          Generate Bourne shell commands on stdout.\n"
842 		    "  -k          Kill the current agent.\n"
843 		    "  -d          Debug mode.\n"
844 		    "  -a socket   Bind agent socket to given name.\n"),
845 		__progname);
846 	exit(1);
847 }
848 
849 int
850 main(int ac, char **av)
851 {
852 	int sock, c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0, ch, nalloc;
853 	char *shell, *pidstr, *agentsocket = NULL;
854 	const char *format;
855 	fd_set *readsetp = NULL, *writesetp = NULL;
856 	struct sockaddr_un sunaddr;
857 #ifdef HAVE_SETRLIMIT
858 	struct rlimit rlim;
859 #endif
860 #ifdef HAVE_CYGWIN
861 	int prev_mask;
862 #endif
863 	extern int optind;
864 	extern char *optarg;
865 	pid_t pid;
866 	char pidstrbuf[1 + 3 * sizeof pid];
867 #ifdef HAVE_SOLARIS_PRIVILEGE
868 	priv_set_t *myprivs;
869 #endif /* HAVE_SOLARIS_PRIVILEGE */
870 
871 	/* drop */
872 	setegid(getgid());
873 	setgid(getgid());
874 
875 	(void) g11n_setlocale(LC_ALL, "");
876 
877 	SSLeay_add_all_algorithms();
878 
879 	__progname = get_progname(av[0]);
880 	init_rng();
881 	seed_rng();
882 
883 	while ((ch = getopt(ac, av, "cdksa:")) != -1) {
884 		switch (ch) {
885 		case 'c':
886 			if (s_flag)
887 				usage();
888 			c_flag++;
889 			break;
890 		case 'k':
891 			k_flag++;
892 			break;
893 		case 's':
894 			if (c_flag)
895 				usage();
896 			s_flag++;
897 			break;
898 		case 'd':
899 			if (d_flag)
900 				usage();
901 			d_flag++;
902 			break;
903 		case 'a':
904 			agentsocket = optarg;
905 			break;
906 		default:
907 			usage();
908 		}
909 	}
910 	ac -= optind;
911 	av += optind;
912 
913 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
914 		usage();
915 
916 	if (ac == 0 && !c_flag && !s_flag) {
917 		shell = getenv("SHELL");
918 		if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
919 			c_flag = 1;
920 	}
921 	if (k_flag) {
922 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
923 		if (pidstr == NULL) {
924 			fprintf(stderr,
925 				gettext("%s not set, cannot kill agent\n"),
926 				SSH_AGENTPID_ENV_NAME);
927 			exit(1);
928 		}
929 		pid = atoi(pidstr);
930 		if (pid < 1) {
931 			fprintf(stderr,
932 			    gettext("%s=\")%s\", which is not a good PID\n"),
933 			    SSH_AGENTPID_ENV_NAME, pidstr);
934 			exit(1);
935 		}
936 		if (kill(pid, SIGTERM) == -1) {
937 			perror("kill");
938 			exit(1);
939 		}
940 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
941 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
942 		printf(format, SSH_AGENTPID_ENV_NAME);
943 		printf("echo ");
944 		printf(gettext("Agent pid %ld killed;\n"), (long)pid);
945 		exit(0);
946 	}
947 	parent_pid = getpid();
948 
949 	if (agentsocket == NULL) {
950 		/* Create private directory for agent socket */
951 		strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
952 		if (mkdtemp(socket_dir) == NULL) {
953 			perror("mkdtemp: private socket dir");
954 			exit(1);
955 		}
956 		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
957 		    (long)parent_pid);
958 	} else {
959 		/* Try to use specified agent socket */
960 		socket_dir[0] = '\0';
961 		strlcpy(socket_name, agentsocket, sizeof socket_name);
962 	}
963 
964 	/*
965 	 * Create socket early so it will exist before command gets run from
966 	 * the parent.
967 	 */
968 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
969 	if (sock < 0) {
970 		perror("socket");
971 		cleanup_exit(1);
972 	}
973 	memset(&sunaddr, 0, sizeof(sunaddr));
974 	sunaddr.sun_family = AF_UNIX;
975 	strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
976 #ifdef HAVE_CYGWIN
977 	prev_mask = umask(0177);
978 #endif
979 	if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
980 		perror("bind");
981 #ifdef HAVE_CYGWIN
982 		umask(prev_mask);
983 #endif
984 		cleanup_exit(1);
985 	}
986 #ifdef HAVE_CYGWIN
987 	umask(prev_mask);
988 #endif
989 	if (listen(sock, 128) < 0) {
990 		perror("listen");
991 		cleanup_exit(1);
992 	}
993 
994 	/*
995 	 * Fork, and have the parent execute the command, if any, or present
996 	 * the socket data.  The child continues as the authentication agent.
997 	 */
998 	if (d_flag) {
999 		log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1000 		format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1001 		printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1002 		    SSH_AUTHSOCKET_ENV_NAME);
1003 		printf("echo ");
1004 		printf(gettext("Agent pid %ld;\n"), (long)parent_pid);
1005 		goto skip;
1006 	}
1007 	pid = fork();
1008 	if (pid == -1) {
1009 		perror("fork");
1010 		cleanup_exit(1);
1011 	}
1012 	if (pid != 0) {		/* Parent - execute the given command. */
1013 		close(sock);
1014 		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1015 		if (ac == 0) {
1016 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1017 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1018 			    SSH_AUTHSOCKET_ENV_NAME);
1019 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1020 			    SSH_AGENTPID_ENV_NAME);
1021 			printf("echo ");
1022 			printf(gettext("Agent pid %ld;\n"), (long)pid);
1023 			exit(0);
1024 		}
1025 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1026 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1027 			perror("setenv");
1028 			exit(1);
1029 		}
1030 		execvp(av[0], av);
1031 		perror(av[0]);
1032 		exit(1);
1033 	}
1034 	/* child */
1035 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1036 
1037 #ifdef HAVE_SOLARIS_PRIVILEGE
1038 	/*
1039 	 * Drop unneeded privs, including basic ones like fork/exec.
1040 	 *
1041 	 * Idiom: remove from 'basic' privs we know we don't want,
1042 	 * invert the result and remove the resulting set from P.
1043 	 *
1044 	 * None of the priv_delset() calls below, nor the setppriv call
1045 	 * below can fail, so their return values are not checked.
1046 	 */
1047 	if ((myprivs = priv_str_to_set("basic", ",", NULL)) == NULL)
1048 		fatal("priv_str_to_set failed: %m");
1049 	(void) priv_delset(myprivs, PRIV_PROC_EXEC);
1050 	(void) priv_delset(myprivs, PRIV_PROC_FORK);
1051 	(void) priv_delset(myprivs, PRIV_FILE_LINK_ANY);
1052 	(void) priv_delset(myprivs, PRIV_PROC_INFO);
1053 	(void) priv_delset(myprivs, PRIV_PROC_SESSION);
1054 	priv_inverse(myprivs);
1055 	(void) setppriv(PRIV_OFF, PRIV_PERMITTED, myprivs);
1056 	(void) priv_freeset(myprivs);
1057 #endif /* HAVE_SOLARIS_PRIVILEGE */
1058 
1059 	if (setsid() == -1) {
1060 		error("setsid: %s", strerror(errno));
1061 		cleanup_exit(1);
1062 	}
1063 
1064 	(void)chdir("/");
1065 	close(0);
1066 	close(1);
1067 	close(2);
1068 
1069 #ifdef HAVE_SETRLIMIT
1070 	/* deny core dumps, since memory contains unencrypted private keys */
1071 	rlim.rlim_cur = rlim.rlim_max = 0;
1072 	if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1073 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1074 		cleanup_exit(1);
1075 	}
1076 #endif
1077 
1078 skip:
1079 	fatal_add_cleanup(cleanup_socket, NULL);
1080 	new_socket(AUTH_SOCKET, sock);
1081 	if (ac > 0) {
1082 		signal(SIGALRM, check_parent_exists);
1083 		alarm(10);
1084 	}
1085 	idtab_init();
1086 	if (!d_flag)
1087 		signal(SIGINT, SIG_IGN);
1088 	signal(SIGPIPE, SIG_IGN);
1089 	signal(SIGHUP, cleanup_handler);
1090 	signal(SIGTERM, cleanup_handler);
1091 	nalloc = 0;
1092 
1093 	while (1) {
1094 		prepare_select(&readsetp, &writesetp, &max_fd, &nalloc);
1095 		if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
1096 			if (errno == EINTR)
1097 				continue;
1098 			fatal("select: %s", strerror(errno));
1099 		}
1100 		after_select(readsetp, writesetp);
1101 	}
1102 	/* NOTREACHED */
1103 	return (0);	/* keep lint happy */
1104 }
1105