xref: /freebsd/crypto/openssh/ssh-agent.c (revision 1a2cdef4962b47be5057809ce730a733b7f3c27c)
1 /*	$OpenBSD: ssh-agent.c,v 1.37 2000/09/21 11:07:51 markus Exp $	*/
2 
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * The authentication agent program.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  * SSH2 implementation,
16  * Copyright (c) 2000 Markus Friedl. All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 #include "includes.h"
40 RCSID("$OpenBSD: ssh-agent.c,v 1.37 2000/09/21 11:07:51 markus Exp $");
41 RCSID("$FreeBSD$");
42 
43 #include "ssh.h"
44 #include "rsa.h"
45 #include "buffer.h"
46 #include "bufaux.h"
47 #include "xmalloc.h"
48 #include "packet.h"
49 #include "getput.h"
50 #include "mpaux.h"
51 
52 #include <openssl/evp.h>
53 #include <openssl/md5.h>
54 #include <openssl/dsa.h>
55 #include <openssl/rsa.h>
56 #include "key.h"
57 #include "authfd.h"
58 #include "dsa.h"
59 #include "kex.h"
60 #include "compat.h"
61 
62 typedef struct {
63 	int fd;
64 	enum {
65 		AUTH_UNUSED, AUTH_SOCKET, AUTH_CONNECTION
66 	} type;
67 	Buffer input;
68 	Buffer output;
69 } SocketEntry;
70 
71 unsigned int sockets_alloc = 0;
72 SocketEntry *sockets = NULL;
73 
74 typedef struct {
75 	Key *key;
76 	char *comment;
77 } Identity;
78 
79 typedef struct {
80 	int nentries;
81 	Identity *identities;
82 } Idtab;
83 
84 /* private key table, one per protocol version */
85 Idtab idtable[3];
86 
87 int max_fd = 0;
88 
89 /* pid of shell == parent of agent */
90 pid_t parent_pid = -1;
91 
92 /* pathname and directory for AUTH_SOCKET */
93 char socket_name[1024];
94 char socket_dir[1024];
95 
96 extern char *__progname;
97 
98 void
99 idtab_init(void)
100 {
101 	int i;
102 	for (i = 0; i <=2; i++){
103 		idtable[i].identities = NULL;
104 		idtable[i].nentries = 0;
105 	}
106 }
107 
108 /* return private key table for requested protocol version */
109 Idtab *
110 idtab_lookup(int version)
111 {
112 	if (version < 1 || version > 2)
113 		fatal("internal error, bad protocol version %d", version);
114 	return &idtable[version];
115 }
116 
117 /* return matching private key for given public key */
118 Key *
119 lookup_private_key(Key *key, int *idx, int version)
120 {
121 	int i;
122 	Idtab *tab = idtab_lookup(version);
123 	for (i = 0; i < tab->nentries; i++) {
124 		if (key_equal(key, tab->identities[i].key)) {
125 			if (idx != NULL)
126 				*idx = i;
127 			return tab->identities[i].key;
128 		}
129 	}
130 	return NULL;
131 }
132 
133 /* send list of supported public keys to 'client' */
134 void
135 process_request_identities(SocketEntry *e, int version)
136 {
137 	Idtab *tab = idtab_lookup(version);
138 	Buffer msg;
139 	int i;
140 
141 	buffer_init(&msg);
142 	buffer_put_char(&msg, (version == 1) ?
143 	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
144 	buffer_put_int(&msg, tab->nentries);
145 	for (i = 0; i < tab->nentries; i++) {
146 		Identity *id = &tab->identities[i];
147 		if (id->key->type == KEY_RSA) {
148 			buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
149 			buffer_put_bignum(&msg, id->key->rsa->e);
150 			buffer_put_bignum(&msg, id->key->rsa->n);
151 		} else {
152 			unsigned char *blob;
153 			unsigned int blen;
154 			dsa_make_key_blob(id->key, &blob, &blen);
155 			buffer_put_string(&msg, blob, blen);
156 			xfree(blob);
157 		}
158 		buffer_put_cstring(&msg, id->comment);
159 	}
160 	buffer_put_int(&e->output, buffer_len(&msg));
161 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
162 	buffer_free(&msg);
163 }
164 
165 /* ssh1 only */
166 void
167 process_authentication_challenge1(SocketEntry *e)
168 {
169 	Key *key, *private;
170 	BIGNUM *challenge;
171 	int i, len;
172 	Buffer msg;
173 	MD5_CTX md;
174 	unsigned char buf[32], mdbuf[16], session_id[16];
175 	unsigned int response_type;
176 
177 	buffer_init(&msg);
178 	key = key_new(KEY_RSA);
179 	challenge = BN_new();
180 
181 	buffer_get_int(&e->input);				/* ignored */
182 	buffer_get_bignum(&e->input, key->rsa->e);
183 	buffer_get_bignum(&e->input, key->rsa->n);
184 	buffer_get_bignum(&e->input, challenge);
185 
186 	/* Only protocol 1.1 is supported */
187 	if (buffer_len(&e->input) == 0)
188 		goto failure;
189 	buffer_get(&e->input, (char *) session_id, 16);
190 	response_type = buffer_get_int(&e->input);
191 	if (response_type != 1)
192 		goto failure;
193 
194 	private = lookup_private_key(key, NULL, 1);
195 	if (private != NULL) {
196 		/* Decrypt the challenge using the private key. */
197 		if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
198 			goto failure;
199 
200 		/* The response is MD5 of decrypted challenge plus session id. */
201 		len = BN_num_bytes(challenge);
202 		if (len <= 0 || len > 32) {
203 			log("process_authentication_challenge: bad challenge length %d", len);
204 			goto failure;
205 		}
206 		memset(buf, 0, 32);
207 		BN_bn2bin(challenge, buf + 32 - len);
208 		MD5_Init(&md);
209 		MD5_Update(&md, buf, 32);
210 		MD5_Update(&md, session_id, 16);
211 		MD5_Final(mdbuf, &md);
212 
213 		/* Send the response. */
214 		buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
215 		for (i = 0; i < 16; i++)
216 			buffer_put_char(&msg, mdbuf[i]);
217 		goto send;
218 	}
219 
220 failure:
221 	/* Unknown identity or protocol error.  Send failure. */
222 	buffer_put_char(&msg, SSH_AGENT_FAILURE);
223 send:
224 	buffer_put_int(&e->output, buffer_len(&msg));
225 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
226 	key_free(key);
227 	BN_clear_free(challenge);
228 	buffer_free(&msg);
229 }
230 
231 /* ssh2 only */
232 void
233 process_sign_request2(SocketEntry *e)
234 {
235 	extern int datafellows;
236 	Key *key, *private;
237 	unsigned char *blob, *data, *signature = NULL;
238 	unsigned int blen, dlen, slen = 0;
239 	int flags;
240 	Buffer msg;
241 	int ok = -1;
242 
243 	datafellows = 0;
244 
245 	blob = buffer_get_string(&e->input, &blen);
246 	data = buffer_get_string(&e->input, &dlen);
247 
248 	flags = buffer_get_int(&e->input);
249 	if (flags & SSH_AGENT_OLD_SIGNATURE)
250 		datafellows = SSH_BUG_SIGBLOB;
251 
252 	key = dsa_key_from_blob(blob, blen);
253 	if (key != NULL) {
254 		private = lookup_private_key(key, NULL, 2);
255 		if (private != NULL)
256 			ok = dsa_sign(private, &signature, &slen, data, dlen);
257 	}
258 	key_free(key);
259 	buffer_init(&msg);
260 	if (ok == 0) {
261 		buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
262 		buffer_put_string(&msg, signature, slen);
263 	} else {
264 		buffer_put_char(&msg, SSH_AGENT_FAILURE);
265 	}
266 	buffer_put_int(&e->output, buffer_len(&msg));
267 	buffer_append(&e->output, buffer_ptr(&msg),
268 	    buffer_len(&msg));
269 	buffer_free(&msg);
270 	xfree(data);
271 	xfree(blob);
272 	if (signature != NULL)
273 		xfree(signature);
274 }
275 
276 /* shared */
277 void
278 process_remove_identity(SocketEntry *e, int version)
279 {
280 	Key *key = NULL, *private;
281 	unsigned char *blob;
282 	unsigned int blen;
283 	unsigned int bits;
284 	int success = 0;
285 
286 	switch(version){
287 	case 1:
288 		key = key_new(KEY_RSA);
289 		bits = buffer_get_int(&e->input);
290 		buffer_get_bignum(&e->input, key->rsa->e);
291 		buffer_get_bignum(&e->input, key->rsa->n);
292 
293 		if (bits != key_size(key))
294 			log("Warning: identity keysize mismatch: actual %d, announced %d",
295 			      key_size(key), bits);
296 		break;
297 	case 2:
298 		blob = buffer_get_string(&e->input, &blen);
299 		key = dsa_key_from_blob(blob, blen);
300 		xfree(blob);
301 		break;
302 	}
303 	if (key != NULL) {
304 		int idx;
305 		private = lookup_private_key(key, &idx, version);
306 		if (private != NULL) {
307 			/*
308 			 * We have this key.  Free the old key.  Since we
309 			 * don\'t want to leave empty slots in the middle of
310 			 * the array, we actually free the key there and copy
311 			 * data from the last entry.
312 			 */
313 			Idtab *tab = idtab_lookup(version);
314 			key_free(tab->identities[idx].key);
315 			xfree(tab->identities[idx].comment);
316 			if (idx != tab->nentries)
317 				tab->identities[idx] = tab->identities[tab->nentries];
318 			tab->nentries--;
319 			success = 1;
320 		}
321 		key_free(key);
322 	}
323 	buffer_put_int(&e->output, 1);
324 	buffer_put_char(&e->output,
325 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
326 }
327 
328 void
329 process_remove_all_identities(SocketEntry *e, int version)
330 {
331 	unsigned int i;
332 	Idtab *tab = idtab_lookup(version);
333 
334 	/* Loop over all identities and clear the keys. */
335 	for (i = 0; i < tab->nentries; i++) {
336 		key_free(tab->identities[i].key);
337 		xfree(tab->identities[i].comment);
338 	}
339 
340 	/* Mark that there are no identities. */
341 	tab->nentries = 0;
342 
343 	/* Send success. */
344 	buffer_put_int(&e->output, 1);
345 	buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
346 	return;
347 }
348 
349 void
350 process_add_identity(SocketEntry *e, int version)
351 {
352 	Key *k = NULL;
353 	RSA *rsa;
354 	BIGNUM *aux;
355 	BN_CTX *ctx;
356 	char *type;
357 	char *comment;
358 	int success = 0;
359 	Idtab *tab = idtab_lookup(version);
360 
361 	switch (version) {
362 	case 1:
363 		k = key_new(KEY_RSA);
364 		rsa = k->rsa;
365 
366 		/* allocate mem for private key */
367 		/* XXX rsa->n and rsa->e are already allocated */
368 		rsa->d = BN_new();
369 		rsa->iqmp = BN_new();
370 		rsa->q = BN_new();
371 		rsa->p = BN_new();
372 		rsa->dmq1 = BN_new();
373 		rsa->dmp1 = BN_new();
374 
375 		buffer_get_int(&e->input);		 /* ignored */
376 
377 		buffer_get_bignum(&e->input, rsa->n);
378 		buffer_get_bignum(&e->input, rsa->e);
379 		buffer_get_bignum(&e->input, rsa->d);
380 		buffer_get_bignum(&e->input, rsa->iqmp);
381 
382 		/* SSH and SSL have p and q swapped */
383 		buffer_get_bignum(&e->input, rsa->q);	/* p */
384 		buffer_get_bignum(&e->input, rsa->p);	/* q */
385 
386 		/* Generate additional parameters */
387 		aux = BN_new();
388 		ctx = BN_CTX_new();
389 
390 		BN_sub(aux, rsa->q, BN_value_one());
391 		BN_mod(rsa->dmq1, rsa->d, aux, ctx);
392 
393 		BN_sub(aux, rsa->p, BN_value_one());
394 		BN_mod(rsa->dmp1, rsa->d, aux, ctx);
395 
396 		BN_clear_free(aux);
397 		BN_CTX_free(ctx);
398 
399 		break;
400 	case 2:
401 		type = buffer_get_string(&e->input, NULL);
402 		if (strcmp(type, KEX_DSS)) {
403 			buffer_clear(&e->input);
404 			xfree(type);
405 			goto send;
406 		}
407 		xfree(type);
408 
409 		k = key_new(KEY_DSA);
410 
411 		/* allocate mem for private key */
412 		k->dsa->priv_key = BN_new();
413 
414 		buffer_get_bignum2(&e->input, k->dsa->p);
415 		buffer_get_bignum2(&e->input, k->dsa->q);
416 		buffer_get_bignum2(&e->input, k->dsa->g);
417 		buffer_get_bignum2(&e->input, k->dsa->pub_key);
418 		buffer_get_bignum2(&e->input, k->dsa->priv_key);
419 
420 		break;
421 	}
422 
423 	comment = buffer_get_string(&e->input, NULL);
424 	if (k == NULL) {
425 		xfree(comment);
426 		goto send;
427 	}
428 	success = 1;
429 	if (lookup_private_key(k, NULL, version) == NULL) {
430 		if (tab->nentries == 0)
431 			tab->identities = xmalloc(sizeof(Identity));
432 		else
433 			tab->identities = xrealloc(tab->identities,
434 			    (tab->nentries + 1) * sizeof(Identity));
435 		tab->identities[tab->nentries].key = k;
436 		tab->identities[tab->nentries].comment = comment;
437 		/* Increment the number of identities. */
438 		tab->nentries++;
439 	} else {
440 		key_free(k);
441 		xfree(comment);
442 	}
443 send:
444 	buffer_put_int(&e->output, 1);
445 	buffer_put_char(&e->output,
446 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
447 }
448 
449 /* dispatch incoming messages */
450 
451 void
452 process_message(SocketEntry *e)
453 {
454 	unsigned int msg_len;
455 	unsigned int type;
456 	unsigned char *cp;
457 	if (buffer_len(&e->input) < 5)
458 		return;		/* Incomplete message. */
459 	cp = (unsigned char *) buffer_ptr(&e->input);
460 	msg_len = GET_32BIT(cp);
461 	if (msg_len > 256 * 1024) {
462 		shutdown(e->fd, SHUT_RDWR);
463 		close(e->fd);
464 		e->type = AUTH_UNUSED;
465 		return;
466 	}
467 	if (buffer_len(&e->input) < msg_len + 4)
468 		return;
469 	buffer_consume(&e->input, 4);
470 	type = buffer_get_char(&e->input);
471 
472 	switch (type) {
473 	/* ssh1 */
474 	case SSH_AGENTC_RSA_CHALLENGE:
475 		process_authentication_challenge1(e);
476 		break;
477 	case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
478 		process_request_identities(e, 1);
479 		break;
480 	case SSH_AGENTC_ADD_RSA_IDENTITY:
481 		process_add_identity(e, 1);
482 		break;
483 	case SSH_AGENTC_REMOVE_RSA_IDENTITY:
484 		process_remove_identity(e, 1);
485 		break;
486 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
487 		process_remove_all_identities(e, 1);
488 		break;
489 	/* ssh2 */
490 	case SSH2_AGENTC_SIGN_REQUEST:
491 		process_sign_request2(e);
492 		break;
493 	case SSH2_AGENTC_REQUEST_IDENTITIES:
494 		process_request_identities(e, 2);
495 		break;
496 	case SSH2_AGENTC_ADD_IDENTITY:
497 		process_add_identity(e, 2);
498 		break;
499 	case SSH2_AGENTC_REMOVE_IDENTITY:
500 		process_remove_identity(e, 2);
501 		break;
502 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
503 		process_remove_all_identities(e, 2);
504 		break;
505 	default:
506 		/* Unknown message.  Respond with failure. */
507 		error("Unknown message %d", type);
508 		buffer_clear(&e->input);
509 		buffer_put_int(&e->output, 1);
510 		buffer_put_char(&e->output, SSH_AGENT_FAILURE);
511 		break;
512 	}
513 }
514 
515 void
516 new_socket(int type, int fd)
517 {
518 	unsigned int i, old_alloc;
519 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
520 		error("fcntl O_NONBLOCK: %s", strerror(errno));
521 
522 	if (fd > max_fd)
523 		max_fd = fd;
524 
525 	for (i = 0; i < sockets_alloc; i++)
526 		if (sockets[i].type == AUTH_UNUSED) {
527 			sockets[i].fd = fd;
528 			sockets[i].type = type;
529 			buffer_init(&sockets[i].input);
530 			buffer_init(&sockets[i].output);
531 			return;
532 		}
533 	old_alloc = sockets_alloc;
534 	sockets_alloc += 10;
535 	if (sockets)
536 		sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
537 	else
538 		sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
539 	for (i = old_alloc; i < sockets_alloc; i++)
540 		sockets[i].type = AUTH_UNUSED;
541 	sockets[old_alloc].type = type;
542 	sockets[old_alloc].fd = fd;
543 	buffer_init(&sockets[old_alloc].input);
544 	buffer_init(&sockets[old_alloc].output);
545 }
546 
547 void
548 prepare_select(fd_set *readset, fd_set *writeset)
549 {
550 	unsigned int i;
551 	for (i = 0; i < sockets_alloc; i++)
552 		switch (sockets[i].type) {
553 		case AUTH_SOCKET:
554 		case AUTH_CONNECTION:
555 			FD_SET(sockets[i].fd, readset);
556 			if (buffer_len(&sockets[i].output) > 0)
557 				FD_SET(sockets[i].fd, writeset);
558 			break;
559 		case AUTH_UNUSED:
560 			break;
561 		default:
562 			fatal("Unknown socket type %d", sockets[i].type);
563 			break;
564 		}
565 }
566 
567 void
568 after_select(fd_set *readset, fd_set *writeset)
569 {
570 	unsigned int i;
571 	int len, sock;
572 	socklen_t slen;
573 	char buf[1024];
574 	struct sockaddr_un sunaddr;
575 
576 	for (i = 0; i < sockets_alloc; i++)
577 		switch (sockets[i].type) {
578 		case AUTH_UNUSED:
579 			break;
580 		case AUTH_SOCKET:
581 			if (FD_ISSET(sockets[i].fd, readset)) {
582 				slen = sizeof(sunaddr);
583 				sock = accept(sockets[i].fd, (struct sockaddr *) & sunaddr, &slen);
584 				if (sock < 0) {
585 					perror("accept from AUTH_SOCKET");
586 					break;
587 				}
588 				new_socket(AUTH_CONNECTION, sock);
589 			}
590 			break;
591 		case AUTH_CONNECTION:
592 			if (buffer_len(&sockets[i].output) > 0 &&
593 			    FD_ISSET(sockets[i].fd, writeset)) {
594 				len = write(sockets[i].fd, buffer_ptr(&sockets[i].output),
595 					 buffer_len(&sockets[i].output));
596 				if (len <= 0) {
597 					shutdown(sockets[i].fd, SHUT_RDWR);
598 					close(sockets[i].fd);
599 					sockets[i].type = AUTH_UNUSED;
600 					buffer_free(&sockets[i].input);
601 					buffer_free(&sockets[i].output);
602 					break;
603 				}
604 				buffer_consume(&sockets[i].output, len);
605 			}
606 			if (FD_ISSET(sockets[i].fd, readset)) {
607 				len = read(sockets[i].fd, buf, sizeof(buf));
608 				if (len <= 0) {
609 					shutdown(sockets[i].fd, SHUT_RDWR);
610 					close(sockets[i].fd);
611 					sockets[i].type = AUTH_UNUSED;
612 					buffer_free(&sockets[i].input);
613 					buffer_free(&sockets[i].output);
614 					break;
615 				}
616 				buffer_append(&sockets[i].input, buf, len);
617 				process_message(&sockets[i]);
618 			}
619 			break;
620 		default:
621 			fatal("Unknown type %d", sockets[i].type);
622 		}
623 }
624 
625 void
626 check_parent_exists(int sig)
627 {
628 	if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
629 		/* printf("Parent has died - Authentication agent exiting.\n"); */
630 		exit(1);
631 	}
632 	signal(SIGALRM, check_parent_exists);
633 	alarm(10);
634 }
635 
636 void
637 cleanup_socket(void)
638 {
639 	remove(socket_name);
640 	rmdir(socket_dir);
641 }
642 
643 void
644 cleanup_exit(int i)
645 {
646 	cleanup_socket();
647 	exit(i);
648 }
649 
650 void
651 usage()
652 {
653 	fprintf(stderr, "ssh-agent version %s\n", SSH_VERSION);
654 	fprintf(stderr, "Usage: %s [-c | -s] [-k] [command {args...]]\n",
655 		__progname);
656 	exit(1);
657 }
658 
659 int
660 main(int ac, char **av)
661 {
662 	fd_set readset, writeset;
663 	int sock, c_flag = 0, k_flag = 0, s_flag = 0, ch;
664 	struct sockaddr_un sunaddr;
665 	pid_t pid;
666 	char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
667 
668 	/* check if RSA support exists */
669 	if (rsa_alive() == 0) {
670 		fprintf(stderr,
671 			"%s: no RSA support in libssl and libcrypto.  See ssl(8).\n",
672 			__progname);
673 		exit(1);
674 	}
675 	while ((ch = getopt(ac, av, "cks")) != -1) {
676 		switch (ch) {
677 		case 'c':
678 			if (s_flag)
679 				usage();
680 			c_flag++;
681 			break;
682 		case 'k':
683 			k_flag++;
684 			break;
685 		case 's':
686 			if (c_flag)
687 				usage();
688 			s_flag++;
689 			break;
690 		default:
691 			usage();
692 		}
693 	}
694 	ac -= optind;
695 	av += optind;
696 
697 	if (ac > 0 && (c_flag || k_flag || s_flag))
698 		usage();
699 
700 	if (ac == 0 && !c_flag && !k_flag && !s_flag) {
701 		shell = getenv("SHELL");
702 		if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
703 			c_flag = 1;
704 	}
705 	if (k_flag) {
706 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
707 		if (pidstr == NULL) {
708 			fprintf(stderr, "%s not set, cannot kill agent\n",
709 				SSH_AGENTPID_ENV_NAME);
710 			exit(1);
711 		}
712 		pid = atoi(pidstr);
713 		if (pid < 1) {	/* XXX PID_MAX check too */
714 		/* Yes, PID_MAX check please */
715 			fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
716 				SSH_AGENTPID_ENV_NAME, pidstr);
717 			exit(1);
718 		}
719 		if (kill(pid, SIGTERM) == -1) {
720 			perror("kill");
721 			exit(1);
722 		}
723 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
724 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
725 		printf(format, SSH_AGENTPID_ENV_NAME);
726 		printf("echo Agent pid %d killed;\n", pid);
727 		exit(0);
728 	}
729 	parent_pid = getpid();
730 
731 	/* Create private directory for agent socket */
732 	strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
733 	if (mkdtemp(socket_dir) == NULL) {
734 		perror("mkdtemp: private socket dir");
735 		exit(1);
736 	}
737 	snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
738 		 parent_pid);
739 
740 	/*
741 	 * Create socket early so it will exist before command gets run from
742 	 * the parent.
743 	 */
744 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
745 	if (sock < 0) {
746 		perror("socket");
747 		cleanup_exit(1);
748 	}
749 	memset(&sunaddr, 0, sizeof(sunaddr));
750 	sunaddr.sun_family = AF_UNIX;
751 	strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
752 	sunaddr.sun_len = SUN_LEN(&sunaddr) + 1;
753 	if (bind(sock, (struct sockaddr *)&sunaddr, sunaddr.sun_len) < 0) {
754 		perror("bind");
755 		cleanup_exit(1);
756 	}
757 	if (listen(sock, 5) < 0) {
758 		perror("listen");
759 		cleanup_exit(1);
760 	}
761 	/*
762 	 * Fork, and have the parent execute the command, if any, or present
763 	 * the socket data.  The child continues as the authentication agent.
764 	 */
765 	pid = fork();
766 	if (pid == -1) {
767 		perror("fork");
768 		exit(1);
769 	}
770 	if (pid != 0) {		/* Parent - execute the given command. */
771 		close(sock);
772 		snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
773 		if (ac == 0) {
774 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
775 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
776 			       SSH_AUTHSOCKET_ENV_NAME);
777 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
778 			       SSH_AGENTPID_ENV_NAME);
779 			printf("echo Agent pid %d;\n", pid);
780 			exit(0);
781 		}
782 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
783 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
784 			perror("setenv");
785 			exit(1);
786 		}
787 		execvp(av[0], av);
788 		perror(av[0]);
789 		exit(1);
790 	}
791 	close(0);
792 	close(1);
793 	close(2);
794 
795 	if (setsid() == -1) {
796 		perror("setsid");
797 		cleanup_exit(1);
798 	}
799 	if (atexit(cleanup_socket) < 0) {
800 		perror("atexit");
801 		cleanup_exit(1);
802 	}
803 	new_socket(AUTH_SOCKET, sock);
804 	if (ac > 0) {
805 		signal(SIGALRM, check_parent_exists);
806 		alarm(10);
807 	}
808 	idtab_init();
809 	signal(SIGINT, SIG_IGN);
810 	signal(SIGPIPE, SIG_IGN);
811 	signal(SIGHUP, cleanup_exit);
812 	signal(SIGTERM, cleanup_exit);
813 	while (1) {
814 		FD_ZERO(&readset);
815 		FD_ZERO(&writeset);
816 		prepare_select(&readset, &writeset);
817 		if (select(max_fd + 1, &readset, &writeset, NULL, NULL) < 0) {
818 			if (errno == EINTR)
819 				continue;
820 			exit(1);
821 		}
822 		after_select(&readset, &writeset);
823 	}
824 	/* NOTREACHED */
825 }
826