xref: /titanic_41/usr/src/cmd/ssh/ssh-agent/ssh-agent.c (revision 2a8d6eba033e4713ab12b61178f0513f1f075482)
1 /*
2  * Copyright 2008 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 	extern int datafellows;
274 	int ok = -1, flags;
275 	Buffer msg;
276 	Key *key;
277 
278 	datafellows = 0;
279 
280 	blob = buffer_get_string(&e->request, &blen);
281 	data = buffer_get_string(&e->request, &dlen);
282 
283 	flags = buffer_get_int(&e->request);
284 	if (flags & SSH_AGENT_OLD_SIGNATURE)
285 		datafellows = SSH_BUG_SIGBLOB;
286 
287 	key = key_from_blob(blob, blen);
288 	if (key != NULL) {
289 		Identity *id = lookup_identity(key, 2);
290 		if (id != NULL)
291 			ok = key_sign(id->key, &signature, &slen, data, dlen);
292 	}
293 	key_free(key);
294 	buffer_init(&msg);
295 	if (ok == 0) {
296 		buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
297 		buffer_put_string(&msg, signature, slen);
298 	} else {
299 		buffer_put_char(&msg, SSH_AGENT_FAILURE);
300 	}
301 	buffer_put_int(&e->output, buffer_len(&msg));
302 	buffer_append(&e->output, buffer_ptr(&msg),
303 	    buffer_len(&msg));
304 	buffer_free(&msg);
305 	xfree(data);
306 	xfree(blob);
307 	if (signature != NULL)
308 		xfree(signature);
309 }
310 
311 /* shared */
312 static void
313 process_remove_identity(SocketEntry *e, int version)
314 {
315 	u_int blen, bits;
316 	int success = 0;
317 	Key *key = NULL;
318 	u_char *blob;
319 
320 	switch (version) {
321 	case 1:
322 		key = key_new(KEY_RSA1);
323 		bits = buffer_get_int(&e->request);
324 		buffer_get_bignum(&e->request, key->rsa->e);
325 		buffer_get_bignum(&e->request, key->rsa->n);
326 
327 		if (bits != key_size(key))
328 			log("Warning: identity keysize mismatch: actual %u, announced %u",
329 			    key_size(key), bits);
330 		break;
331 	case 2:
332 		blob = buffer_get_string(&e->request, &blen);
333 		key = key_from_blob(blob, blen);
334 		xfree(blob);
335 		break;
336 	}
337 	if (key != NULL) {
338 		Identity *id = lookup_identity(key, version);
339 		if (id != NULL) {
340 			/*
341 			 * We have this key.  Free the old key.  Since we
342 			 * don\'t want to leave empty slots in the middle of
343 			 * the array, we actually free the key there and move
344 			 * all the entries between the empty slot and the end
345 			 * of the array.
346 			 */
347 			Idtab *tab = idtab_lookup(version);
348 			if (tab->nentries < 1)
349 				fatal("process_remove_identity: "
350 				    "internal error: tab->nentries %d",
351 				    tab->nentries);
352 			TAILQ_REMOVE(&tab->idlist, id, next);
353 			free_identity(id);
354 			tab->nentries--;
355 			success = 1;
356 		}
357 		key_free(key);
358 	}
359 	buffer_put_int(&e->output, 1);
360 	buffer_put_char(&e->output,
361 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
362 }
363 
364 static void
365 process_remove_all_identities(SocketEntry *e, int version)
366 {
367 	Idtab *tab = idtab_lookup(version);
368 	Identity *id;
369 
370 	/* Loop over all identities and clear the keys. */
371 	for (id = TAILQ_FIRST(&tab->idlist); id;
372 	    id = TAILQ_FIRST(&tab->idlist)) {
373 		TAILQ_REMOVE(&tab->idlist, id, next);
374 		free_identity(id);
375 	}
376 
377 	/* Mark that there are no identities. */
378 	tab->nentries = 0;
379 
380 	/* Send success. */
381 	buffer_put_int(&e->output, 1);
382 	buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
383 }
384 
385 static void
386 reaper(void)
387 {
388 	u_int now = time(NULL);
389 	Identity *id, *nxt;
390 	int version;
391 	Idtab *tab;
392 
393 	for (version = 1; version < 3; version++) {
394 		tab = idtab_lookup(version);
395 		for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
396 			nxt = TAILQ_NEXT(id, next);
397 			if (id->death != 0 && now >= id->death) {
398 				TAILQ_REMOVE(&tab->idlist, id, next);
399 				free_identity(id);
400 				tab->nentries--;
401 			}
402 		}
403 	}
404 }
405 
406 static void
407 process_add_identity(SocketEntry *e, int version)
408 {
409 	Idtab *tab = idtab_lookup(version);
410 	int type, success = 0, death = 0;
411 	char *type_name, *comment;
412 	Key *k = NULL;
413 
414 	switch (version) {
415 	case 1:
416 		k = key_new_private(KEY_RSA1);
417 		(void) buffer_get_int(&e->request);		/* ignored */
418 		buffer_get_bignum(&e->request, k->rsa->n);
419 		buffer_get_bignum(&e->request, k->rsa->e);
420 		buffer_get_bignum(&e->request, k->rsa->d);
421 		buffer_get_bignum(&e->request, k->rsa->iqmp);
422 
423 		/* SSH and SSL have p and q swapped */
424 		buffer_get_bignum(&e->request, k->rsa->q);	/* p */
425 		buffer_get_bignum(&e->request, k->rsa->p);	/* q */
426 
427 		/* Generate additional parameters */
428 		rsa_generate_additional_parameters(k->rsa);
429 		break;
430 	case 2:
431 		type_name = buffer_get_string(&e->request, NULL);
432 		type = key_type_from_name(type_name);
433 		xfree(type_name);
434 		switch (type) {
435 		case KEY_DSA:
436 			k = key_new_private(type);
437 			buffer_get_bignum2(&e->request, k->dsa->p);
438 			buffer_get_bignum2(&e->request, k->dsa->q);
439 			buffer_get_bignum2(&e->request, k->dsa->g);
440 			buffer_get_bignum2(&e->request, k->dsa->pub_key);
441 			buffer_get_bignum2(&e->request, k->dsa->priv_key);
442 			break;
443 		case KEY_RSA:
444 			k = key_new_private(type);
445 			buffer_get_bignum2(&e->request, k->rsa->n);
446 			buffer_get_bignum2(&e->request, k->rsa->e);
447 			buffer_get_bignum2(&e->request, k->rsa->d);
448 			buffer_get_bignum2(&e->request, k->rsa->iqmp);
449 			buffer_get_bignum2(&e->request, k->rsa->p);
450 			buffer_get_bignum2(&e->request, k->rsa->q);
451 
452 			/* Generate additional parameters */
453 			rsa_generate_additional_parameters(k->rsa);
454 			break;
455 		default:
456 			buffer_clear(&e->request);
457 			goto send;
458 		}
459 		break;
460 	}
461 	comment = buffer_get_string(&e->request, NULL);
462 	if (k == NULL) {
463 		xfree(comment);
464 		goto send;
465 	}
466 	success = 1;
467 	while (buffer_len(&e->request)) {
468 		switch (buffer_get_char(&e->request)) {
469 		case SSH_AGENT_CONSTRAIN_LIFETIME:
470 			death = time(NULL) + buffer_get_int(&e->request);
471 			break;
472 		default:
473 			break;
474 		}
475 	}
476 	if (lookup_identity(k, version) == NULL) {
477 		Identity *id = xmalloc(sizeof(Identity));
478 		id->key = k;
479 		id->comment = comment;
480 		id->death = death;
481 		TAILQ_INSERT_TAIL(&tab->idlist, id, next);
482 		/* Increment the number of identities. */
483 		tab->nentries++;
484 	} else {
485 		key_free(k);
486 		xfree(comment);
487 	}
488 send:
489 	buffer_put_int(&e->output, 1);
490 	buffer_put_char(&e->output,
491 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
492 }
493 
494 /* XXX todo: encrypt sensitive data with passphrase */
495 static void
496 process_lock_agent(SocketEntry *e, int lock)
497 {
498 	int success = 0;
499 	char *passwd;
500 
501 	passwd = buffer_get_string(&e->request, NULL);
502 	if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
503 		locked = 0;
504 		memset(lock_passwd, 0, strlen(lock_passwd));
505 		xfree(lock_passwd);
506 		lock_passwd = NULL;
507 		success = 1;
508 	} else if (!locked && lock) {
509 		locked = 1;
510 		lock_passwd = xstrdup(passwd);
511 		success = 1;
512 	}
513 	memset(passwd, 0, strlen(passwd));
514 	xfree(passwd);
515 
516 	buffer_put_int(&e->output, 1);
517 	buffer_put_char(&e->output,
518 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
519 }
520 
521 static void
522 no_identities(SocketEntry *e, u_int type)
523 {
524 	Buffer msg;
525 
526 	buffer_init(&msg);
527 	buffer_put_char(&msg,
528 	    (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
529 	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
530 	buffer_put_int(&msg, 0);
531 	buffer_put_int(&e->output, buffer_len(&msg));
532 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
533 	buffer_free(&msg);
534 }
535 
536 /* dispatch incoming messages */
537 
538 static void
539 process_message(SocketEntry *e)
540 {
541 	u_int msg_len, type;
542 	u_char *cp;
543 
544 	/* kill dead keys */
545 	reaper();
546 
547 	if (buffer_len(&e->input) < 5)
548 		return;		/* Incomplete message. */
549 	cp = buffer_ptr(&e->input);
550 	msg_len = GET_32BIT(cp);
551 	if (msg_len > 256 * 1024) {
552 		close_socket(e);
553 		return;
554 	}
555 	if (buffer_len(&e->input) < msg_len + 4)
556 		return;
557 
558 	/* move the current input to e->request */
559 	buffer_consume(&e->input, 4);
560 	buffer_clear(&e->request);
561 	buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
562 	buffer_consume(&e->input, msg_len);
563 	type = buffer_get_char(&e->request);
564 
565 	/* check wheter agent is locked */
566 	if (locked && type != SSH_AGENTC_UNLOCK) {
567 		buffer_clear(&e->request);
568 		switch (type) {
569 		case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
570 		case SSH2_AGENTC_REQUEST_IDENTITIES:
571 			/* send empty lists */
572 			no_identities(e, type);
573 			break;
574 		default:
575 			/* send a fail message for all other request types */
576 			buffer_put_int(&e->output, 1);
577 			buffer_put_char(&e->output, SSH_AGENT_FAILURE);
578 		}
579 		return;
580 	}
581 
582 	debug("type %d", type);
583 	switch (type) {
584 	case SSH_AGENTC_LOCK:
585 	case SSH_AGENTC_UNLOCK:
586 		process_lock_agent(e, type == SSH_AGENTC_LOCK);
587 		break;
588 	/* ssh1 */
589 	case SSH_AGENTC_RSA_CHALLENGE:
590 		process_authentication_challenge1(e);
591 		break;
592 	case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
593 		process_request_identities(e, 1);
594 		break;
595 	case SSH_AGENTC_ADD_RSA_IDENTITY:
596 	case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
597 		process_add_identity(e, 1);
598 		break;
599 	case SSH_AGENTC_REMOVE_RSA_IDENTITY:
600 		process_remove_identity(e, 1);
601 		break;
602 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
603 		process_remove_all_identities(e, 1);
604 		break;
605 	/* ssh2 */
606 	case SSH2_AGENTC_SIGN_REQUEST:
607 		process_sign_request2(e);
608 		break;
609 	case SSH2_AGENTC_REQUEST_IDENTITIES:
610 		process_request_identities(e, 2);
611 		break;
612 	case SSH2_AGENTC_ADD_IDENTITY:
613 	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
614 		process_add_identity(e, 2);
615 		break;
616 	case SSH2_AGENTC_REMOVE_IDENTITY:
617 		process_remove_identity(e, 2);
618 		break;
619 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
620 		process_remove_all_identities(e, 2);
621 		break;
622 	default:
623 		/* Unknown message.  Respond with failure. */
624 		error("Unknown message %d", type);
625 		buffer_clear(&e->request);
626 		buffer_put_int(&e->output, 1);
627 		buffer_put_char(&e->output, SSH_AGENT_FAILURE);
628 		break;
629 	}
630 }
631 
632 static void
633 new_socket(sock_type type, int fd)
634 {
635 	u_int i, old_alloc;
636 
637 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
638 		error("fcntl O_NONBLOCK: %s", strerror(errno));
639 
640 	if (fd > max_fd)
641 		max_fd = fd;
642 
643 	for (i = 0; i < sockets_alloc; i++)
644 		if (sockets[i].type == AUTH_UNUSED) {
645 			sockets[i].fd = fd;
646 			sockets[i].type = type;
647 			buffer_init(&sockets[i].input);
648 			buffer_init(&sockets[i].output);
649 			buffer_init(&sockets[i].request);
650 			return;
651 		}
652 	old_alloc = sockets_alloc;
653 	sockets_alloc += 10;
654 	if (sockets)
655 		sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
656 	else
657 		sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
658 	for (i = old_alloc; i < sockets_alloc; i++)
659 		sockets[i].type = AUTH_UNUSED;
660 	sockets[old_alloc].type = type;
661 	sockets[old_alloc].fd = fd;
662 	buffer_init(&sockets[old_alloc].input);
663 	buffer_init(&sockets[old_alloc].output);
664 	buffer_init(&sockets[old_alloc].request);
665 }
666 
667 static int
668 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, int *nallocp)
669 {
670 	u_int i, sz;
671 	int n = 0;
672 
673 	for (i = 0; i < sockets_alloc; i++) {
674 		switch (sockets[i].type) {
675 		case AUTH_SOCKET:
676 		case AUTH_CONNECTION:
677 			n = MAX(n, sockets[i].fd);
678 			break;
679 		case AUTH_UNUSED:
680 			break;
681 		default:
682 			fatal("Unknown socket type %d", sockets[i].type);
683 			break;
684 		}
685 	}
686 
687 	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
688 	if (*fdrp == NULL || sz > *nallocp) {
689 		if (*fdrp)
690 			xfree(*fdrp);
691 		if (*fdwp)
692 			xfree(*fdwp);
693 		*fdrp = xmalloc(sz);
694 		*fdwp = xmalloc(sz);
695 		*nallocp = sz;
696 	}
697 	if (n < *fdl)
698 		debug("XXX shrink: %d < %d", n, *fdl);
699 	*fdl = n;
700 	memset(*fdrp, 0, sz);
701 	memset(*fdwp, 0, sz);
702 
703 	for (i = 0; i < sockets_alloc; i++) {
704 		switch (sockets[i].type) {
705 		case AUTH_SOCKET:
706 		case AUTH_CONNECTION:
707 			FD_SET(sockets[i].fd, *fdrp);
708 			if (buffer_len(&sockets[i].output) > 0)
709 				FD_SET(sockets[i].fd, *fdwp);
710 			break;
711 		default:
712 			break;
713 		}
714 	}
715 	return (1);
716 }
717 
718 static void
719 after_select(fd_set *readset, fd_set *writeset)
720 {
721 	struct sockaddr_un sunaddr;
722 	socklen_t slen;
723 	char buf[1024];
724 	int len, sock;
725 	u_int i;
726 	uid_t euid;
727 	gid_t egid;
728 
729 	for (i = 0; i < sockets_alloc; i++)
730 		switch (sockets[i].type) {
731 		case AUTH_UNUSED:
732 			break;
733 		case AUTH_SOCKET:
734 			if (FD_ISSET(sockets[i].fd, readset)) {
735 				slen = sizeof(sunaddr);
736 				sock = accept(sockets[i].fd,
737 				    (struct sockaddr *) &sunaddr, &slen);
738 				if (sock < 0) {
739 					error("accept from AUTH_SOCKET: %s",
740 					    strerror(errno));
741 					break;
742 				}
743 				if (getpeereid(sock, &euid, &egid) < 0) {
744 					error("getpeereid %d failed: %s",
745 					    sock, strerror(errno));
746 					close(sock);
747 					break;
748 				}
749 				if ((euid != 0) && (getuid() != euid)) {
750 					error("uid mismatch: "
751 					    "peer euid %u != uid %u",
752 					    (u_int) euid, (u_int) getuid());
753 					close(sock);
754 					break;
755 				}
756 				new_socket(AUTH_CONNECTION, sock);
757 			}
758 			break;
759 		case AUTH_CONNECTION:
760 			if (buffer_len(&sockets[i].output) > 0 &&
761 			    FD_ISSET(sockets[i].fd, writeset)) {
762 				do {
763 					len = write(sockets[i].fd,
764 					    buffer_ptr(&sockets[i].output),
765 					    buffer_len(&sockets[i].output));
766 					if (len == -1 && (errno == EAGAIN ||
767 					    errno == EINTR))
768 						continue;
769 					break;
770 				} while (1);
771 				if (len <= 0) {
772 					close_socket(&sockets[i]);
773 					break;
774 				}
775 				buffer_consume(&sockets[i].output, len);
776 			}
777 			if (FD_ISSET(sockets[i].fd, readset)) {
778 				do {
779 					len = read(sockets[i].fd, buf, sizeof(buf));
780 					if (len == -1 && (errno == EAGAIN ||
781 					    errno == EINTR))
782 						continue;
783 					break;
784 				} while (1);
785 				if (len <= 0) {
786 					close_socket(&sockets[i]);
787 					break;
788 				}
789 				buffer_append(&sockets[i].input, buf, len);
790 				process_message(&sockets[i]);
791 			}
792 			break;
793 		default:
794 			fatal("Unknown type %d", sockets[i].type);
795 		}
796 }
797 
798 static void
799 cleanup_socket(void *p)
800 {
801 	if (socket_name[0])
802 		unlink(socket_name);
803 	if (socket_dir[0])
804 		rmdir(socket_dir);
805 }
806 
807 static void
808 cleanup_exit(int i)
809 {
810 	cleanup_socket(NULL);
811 	exit(i);
812 }
813 
814 static void
815 cleanup_handler(int sig)
816 {
817 	cleanup_socket(NULL);
818 	_exit(2);
819 }
820 
821 static void
822 check_parent_exists(int sig)
823 {
824 	int save_errno = errno;
825 
826 	if (parent_pid != -1 && getppid() != parent_pid) {
827 		/* printf("Parent has died - Authentication agent exiting.\n"); */
828 		cleanup_handler(sig); /* safe */
829 	}
830 	signal(SIGALRM, check_parent_exists);
831 	alarm(10);
832 	errno = save_errno;
833 }
834 
835 static void
836 usage(void)
837 {
838 	fprintf(stderr,
839 		gettext("Usage: %s [options] [command [args ...]]\n"
840 		    "Options:\n"
841 		    "  -c          Generate C-shell commands on stdout.\n"
842 		    "  -s          Generate Bourne shell commands on stdout.\n"
843 		    "  -k          Kill the current agent.\n"
844 		    "  -d          Debug mode.\n"
845 		    "  -a socket   Bind agent socket to given name.\n"),
846 		__progname);
847 	exit(1);
848 }
849 
850 int
851 main(int ac, char **av)
852 {
853 	int sock, c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0, ch, nalloc;
854 	char *shell, *pidstr, *agentsocket = NULL;
855 	const char *format;
856 	fd_set *readsetp = NULL, *writesetp = NULL;
857 	struct sockaddr_un sunaddr;
858 #ifdef HAVE_SETRLIMIT
859 	struct rlimit rlim;
860 #endif
861 #ifdef HAVE_CYGWIN
862 	int prev_mask;
863 #endif
864 	extern int optind;
865 	extern char *optarg;
866 	pid_t pid;
867 	char pidstrbuf[1 + 3 * sizeof pid];
868 #ifdef HAVE_SOLARIS_PRIVILEGE
869 	priv_set_t *myprivs;
870 #endif /* HAVE_SOLARIS_PRIVILEGE */
871 
872 	/* drop */
873 	setegid(getgid());
874 	setgid(getgid());
875 
876 	(void) g11n_setlocale(LC_ALL, "");
877 
878 	SSLeay_add_all_algorithms();
879 
880 	__progname = get_progname(av[0]);
881 	init_rng();
882 	seed_rng();
883 
884 	while ((ch = getopt(ac, av, "cdksa:")) != -1) {
885 		switch (ch) {
886 		case 'c':
887 			if (s_flag)
888 				usage();
889 			c_flag++;
890 			break;
891 		case 'k':
892 			k_flag++;
893 			break;
894 		case 's':
895 			if (c_flag)
896 				usage();
897 			s_flag++;
898 			break;
899 		case 'd':
900 			if (d_flag)
901 				usage();
902 			d_flag++;
903 			break;
904 		case 'a':
905 			agentsocket = optarg;
906 			break;
907 		default:
908 			usage();
909 		}
910 	}
911 	ac -= optind;
912 	av += optind;
913 
914 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
915 		usage();
916 
917 	if (ac == 0 && !c_flag && !s_flag) {
918 		shell = getenv("SHELL");
919 		if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
920 			c_flag = 1;
921 	}
922 	if (k_flag) {
923 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
924 		if (pidstr == NULL) {
925 			fprintf(stderr,
926 				gettext("%s not set, cannot kill agent\n"),
927 				SSH_AGENTPID_ENV_NAME);
928 			exit(1);
929 		}
930 		pid = atoi(pidstr);
931 		if (pid < 1) {
932 			fprintf(stderr,
933 			    gettext("%s=\")%s\", which is not a good PID\n"),
934 			    SSH_AGENTPID_ENV_NAME, pidstr);
935 			exit(1);
936 		}
937 		if (kill(pid, SIGTERM) == -1) {
938 			perror("kill");
939 			exit(1);
940 		}
941 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
942 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
943 		printf(format, SSH_AGENTPID_ENV_NAME);
944 		printf("echo ");
945 		printf(gettext("Agent pid %ld killed;\n"), (long)pid);
946 		exit(0);
947 	}
948 	parent_pid = getpid();
949 
950 	if (agentsocket == NULL) {
951 		/* Create private directory for agent socket */
952 		strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
953 		if (mkdtemp(socket_dir) == NULL) {
954 			perror("mkdtemp: private socket dir");
955 			exit(1);
956 		}
957 		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
958 		    (long)parent_pid);
959 	} else {
960 		/* Try to use specified agent socket */
961 		socket_dir[0] = '\0';
962 		strlcpy(socket_name, agentsocket, sizeof socket_name);
963 	}
964 
965 	/*
966 	 * Create socket early so it will exist before command gets run from
967 	 * the parent.
968 	 */
969 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
970 	if (sock < 0) {
971 		perror("socket");
972 		cleanup_exit(1);
973 	}
974 	memset(&sunaddr, 0, sizeof(sunaddr));
975 	sunaddr.sun_family = AF_UNIX;
976 	strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
977 #ifdef HAVE_CYGWIN
978 	prev_mask = umask(0177);
979 #endif
980 	if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
981 		perror("bind");
982 #ifdef HAVE_CYGWIN
983 		umask(prev_mask);
984 #endif
985 		cleanup_exit(1);
986 	}
987 #ifdef HAVE_CYGWIN
988 	umask(prev_mask);
989 #endif
990 	if (listen(sock, 128) < 0) {
991 		perror("listen");
992 		cleanup_exit(1);
993 	}
994 
995 	/*
996 	 * Fork, and have the parent execute the command, if any, or present
997 	 * the socket data.  The child continues as the authentication agent.
998 	 */
999 	if (d_flag) {
1000 		log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1001 		format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1002 		printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1003 		    SSH_AUTHSOCKET_ENV_NAME);
1004 		printf("echo ");
1005 		printf(gettext("Agent pid %ld;\n"), (long)parent_pid);
1006 		goto skip;
1007 	}
1008 	pid = fork();
1009 	if (pid == -1) {
1010 		perror("fork");
1011 		cleanup_exit(1);
1012 	}
1013 	if (pid != 0) {		/* Parent - execute the given command. */
1014 		close(sock);
1015 		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1016 		if (ac == 0) {
1017 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1018 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1019 			    SSH_AUTHSOCKET_ENV_NAME);
1020 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1021 			    SSH_AGENTPID_ENV_NAME);
1022 			printf("echo ");
1023 			printf(gettext("Agent pid %ld;\n"), (long)pid);
1024 			exit(0);
1025 		}
1026 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1027 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1028 			perror("setenv");
1029 			exit(1);
1030 		}
1031 		execvp(av[0], av);
1032 		perror(av[0]);
1033 		exit(1);
1034 	}
1035 	/* child */
1036 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1037 
1038 #ifdef HAVE_SOLARIS_PRIVILEGE
1039 	/*
1040 	 * Drop unneeded privs, including basic ones like fork/exec.
1041 	 *
1042 	 * Idiom: remove from 'basic' privs we know we don't want,
1043 	 * invert the result and remove the resulting set from P.
1044 	 *
1045 	 * None of the priv_delset() calls below, nor the setppriv call
1046 	 * below can fail, so their return values are not checked.
1047 	 */
1048 	if ((myprivs = priv_str_to_set("basic", ",", NULL)) == NULL)
1049 		fatal("priv_str_to_set failed: %m");
1050 	(void) priv_delset(myprivs, PRIV_PROC_EXEC);
1051 	(void) priv_delset(myprivs, PRIV_PROC_FORK);
1052 	(void) priv_delset(myprivs, PRIV_FILE_LINK_ANY);
1053 	(void) priv_delset(myprivs, PRIV_PROC_INFO);
1054 	(void) priv_delset(myprivs, PRIV_PROC_SESSION);
1055 	priv_inverse(myprivs);
1056 	(void) setppriv(PRIV_OFF, PRIV_PERMITTED, myprivs);
1057 	(void) priv_freeset(myprivs);
1058 #endif /* HAVE_SOLARIS_PRIVILEGE */
1059 
1060 	if (setsid() == -1) {
1061 		error("setsid: %s", strerror(errno));
1062 		cleanup_exit(1);
1063 	}
1064 
1065 	(void)chdir("/");
1066 	close(0);
1067 	close(1);
1068 	close(2);
1069 
1070 #ifdef HAVE_SETRLIMIT
1071 	/* deny core dumps, since memory contains unencrypted private keys */
1072 	rlim.rlim_cur = rlim.rlim_max = 0;
1073 	if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1074 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1075 		cleanup_exit(1);
1076 	}
1077 #endif
1078 
1079 skip:
1080 	fatal_add_cleanup(cleanup_socket, NULL);
1081 	new_socket(AUTH_SOCKET, sock);
1082 	if (ac > 0) {
1083 		signal(SIGALRM, check_parent_exists);
1084 		alarm(10);
1085 	}
1086 	idtab_init();
1087 	if (!d_flag)
1088 		signal(SIGINT, SIG_IGN);
1089 	signal(SIGPIPE, SIG_IGN);
1090 	signal(SIGHUP, cleanup_handler);
1091 	signal(SIGTERM, cleanup_handler);
1092 	nalloc = 0;
1093 
1094 	while (1) {
1095 		prepare_select(&readsetp, &writesetp, &max_fd, &nalloc);
1096 		if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
1097 			if (errno == EINTR)
1098 				continue;
1099 			fatal("select: %s", strerror(errno));
1100 		}
1101 		after_select(readsetp, writesetp);
1102 	}
1103 	/* NOTREACHED */
1104 	return (0);	/* keep lint happy */
1105 }
1106