xref: /freebsd/crypto/openssh/ssh-agent.c (revision 6990ffd8a95caaba6858ad44ff1b3157d1efba8f)
1 /*	$OpenBSD: ssh-agent.c,v 1.54 2001/04/03 13:56:11 stevesk 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.54 2001/04/03 13:56:11 stevesk Exp $");
41 RCSID("$FreeBSD$");
42 
43 #include <openssl/evp.h>
44 #include <openssl/md5.h>
45 
46 #include "ssh.h"
47 #include "rsa.h"
48 #include "buffer.h"
49 #include "bufaux.h"
50 #include "xmalloc.h"
51 #include "packet.h"
52 #include "getput.h"
53 #include "mpaux.h"
54 #include "key.h"
55 #include "authfd.h"
56 #include "cipher.h"
57 #include "kex.h"
58 #include "compat.h"
59 #include "log.h"
60 
61 typedef struct {
62 	int fd;
63 	enum {
64 		AUTH_UNUSED, AUTH_SOCKET, AUTH_CONNECTION
65 	} type;
66 	Buffer input;
67 	Buffer output;
68 } SocketEntry;
69 
70 u_int sockets_alloc = 0;
71 SocketEntry *sockets = NULL;
72 
73 typedef struct {
74 	Key *key;
75 	char *comment;
76 } Identity;
77 
78 typedef struct {
79 	int nentries;
80 	Identity *identities;
81 } Idtab;
82 
83 /* private key table, one per protocol version */
84 Idtab idtable[3];
85 
86 int max_fd = 0;
87 
88 /* pid of shell == parent of agent */
89 pid_t parent_pid = -1;
90 
91 /* pathname and directory for AUTH_SOCKET */
92 char socket_name[1024];
93 char socket_dir[1024];
94 
95 extern char *__progname;
96 
97 int	prepare_select(fd_set **, fd_set **, int *);
98 
99 void
100 idtab_init(void)
101 {
102 	int i;
103 	for (i = 0; i <=2; i++){
104 		idtable[i].identities = NULL;
105 		idtable[i].nentries = 0;
106 	}
107 }
108 
109 /* return private key table for requested protocol version */
110 Idtab *
111 idtab_lookup(int version)
112 {
113 	if (version < 1 || version > 2)
114 		fatal("internal error, bad protocol version %d", version);
115 	return &idtable[version];
116 }
117 
118 /* return matching private key for given public key */
119 Key *
120 lookup_private_key(Key *key, int *idx, int version)
121 {
122 	int i;
123 	Idtab *tab = idtab_lookup(version);
124 	for (i = 0; i < tab->nentries; i++) {
125 		if (key_equal(key, tab->identities[i].key)) {
126 			if (idx != NULL)
127 				*idx = i;
128 			return tab->identities[i].key;
129 		}
130 	}
131 	return NULL;
132 }
133 
134 /* send list of supported public keys to 'client' */
135 void
136 process_request_identities(SocketEntry *e, int version)
137 {
138 	Idtab *tab = idtab_lookup(version);
139 	Buffer msg;
140 	int i;
141 
142 	buffer_init(&msg);
143 	buffer_put_char(&msg, (version == 1) ?
144 	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
145 	buffer_put_int(&msg, tab->nentries);
146 	for (i = 0; i < tab->nentries; i++) {
147 		Identity *id = &tab->identities[i];
148 		if (id->key->type == KEY_RSA1) {
149 			buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
150 			buffer_put_bignum(&msg, id->key->rsa->e);
151 			buffer_put_bignum(&msg, id->key->rsa->n);
152 		} else {
153 			u_char *blob;
154 			u_int blen;
155 			key_to_blob(id->key, &blob, &blen);
156 			buffer_put_string(&msg, blob, blen);
157 			xfree(blob);
158 		}
159 		buffer_put_cstring(&msg, id->comment);
160 	}
161 	buffer_put_int(&e->output, buffer_len(&msg));
162 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
163 	buffer_free(&msg);
164 }
165 
166 /* ssh1 only */
167 void
168 process_authentication_challenge1(SocketEntry *e)
169 {
170 	Key *key, *private;
171 	BIGNUM *challenge;
172 	int i, len;
173 	Buffer msg;
174 	MD5_CTX md;
175 	u_char buf[32], mdbuf[16], session_id[16];
176 	u_int response_type;
177 
178 	buffer_init(&msg);
179 	key = key_new(KEY_RSA1);
180 	challenge = BN_new();
181 
182 	buffer_get_int(&e->input);				/* ignored */
183 	buffer_get_bignum(&e->input, key->rsa->e);
184 	buffer_get_bignum(&e->input, key->rsa->n);
185 	buffer_get_bignum(&e->input, challenge);
186 
187 	/* Only protocol 1.1 is supported */
188 	if (buffer_len(&e->input) == 0)
189 		goto failure;
190 	buffer_get(&e->input, (char *) session_id, 16);
191 	response_type = buffer_get_int(&e->input);
192 	if (response_type != 1)
193 		goto failure;
194 
195 	private = lookup_private_key(key, NULL, 1);
196 	if (private != NULL) {
197 		/* Decrypt the challenge using the private key. */
198 		if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
199 			goto failure;
200 
201 		/* The response is MD5 of decrypted challenge plus session id. */
202 		len = BN_num_bytes(challenge);
203 		if (len <= 0 || len > 32) {
204 			log("process_authentication_challenge: bad challenge length %d", len);
205 			goto failure;
206 		}
207 		memset(buf, 0, 32);
208 		BN_bn2bin(challenge, buf + 32 - len);
209 		MD5_Init(&md);
210 		MD5_Update(&md, buf, 32);
211 		MD5_Update(&md, session_id, 16);
212 		MD5_Final(mdbuf, &md);
213 
214 		/* Send the response. */
215 		buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
216 		for (i = 0; i < 16; i++)
217 			buffer_put_char(&msg, mdbuf[i]);
218 		goto send;
219 	}
220 
221 failure:
222 	/* Unknown identity or protocol error.  Send failure. */
223 	buffer_put_char(&msg, SSH_AGENT_FAILURE);
224 send:
225 	buffer_put_int(&e->output, buffer_len(&msg));
226 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
227 	key_free(key);
228 	BN_clear_free(challenge);
229 	buffer_free(&msg);
230 }
231 
232 /* ssh2 only */
233 void
234 process_sign_request2(SocketEntry *e)
235 {
236 	extern int datafellows;
237 	Key *key, *private;
238 	u_char *blob, *data, *signature = NULL;
239 	u_int blen, dlen, slen = 0;
240 	int flags;
241 	Buffer msg;
242 	int ok = -1;
243 
244 	datafellows = 0;
245 
246 	blob = buffer_get_string(&e->input, &blen);
247 	data = buffer_get_string(&e->input, &dlen);
248 
249 	flags = buffer_get_int(&e->input);
250 	if (flags & SSH_AGENT_OLD_SIGNATURE)
251 		datafellows = SSH_BUG_SIGBLOB;
252 
253 	key = key_from_blob(blob, blen);
254 	if (key != NULL) {
255 		private = lookup_private_key(key, NULL, 2);
256 		if (private != NULL)
257 			ok = key_sign(private, &signature, &slen, data, dlen);
258 	}
259 	key_free(key);
260 	buffer_init(&msg);
261 	if (ok == 0) {
262 		buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
263 		buffer_put_string(&msg, signature, slen);
264 	} else {
265 		buffer_put_char(&msg, SSH_AGENT_FAILURE);
266 	}
267 	buffer_put_int(&e->output, buffer_len(&msg));
268 	buffer_append(&e->output, buffer_ptr(&msg),
269 	    buffer_len(&msg));
270 	buffer_free(&msg);
271 	xfree(data);
272 	xfree(blob);
273 	if (signature != NULL)
274 		xfree(signature);
275 }
276 
277 /* shared */
278 void
279 process_remove_identity(SocketEntry *e, int version)
280 {
281 	Key *key = NULL, *private;
282 	u_char *blob;
283 	u_int blen;
284 	u_int bits;
285 	int success = 0;
286 
287 	switch(version){
288 	case 1:
289 		key = key_new(KEY_RSA1);
290 		bits = buffer_get_int(&e->input);
291 		buffer_get_bignum(&e->input, key->rsa->e);
292 		buffer_get_bignum(&e->input, key->rsa->n);
293 
294 		if (bits != key_size(key))
295 			log("Warning: identity keysize mismatch: actual %d, announced %d",
296 			    key_size(key), bits);
297 		break;
298 	case 2:
299 		blob = buffer_get_string(&e->input, &blen);
300 		key = key_from_blob(blob, blen);
301 		xfree(blob);
302 		break;
303 	}
304 	if (key != NULL) {
305 		int idx;
306 		private = lookup_private_key(key, &idx, version);
307 		if (private != NULL) {
308 			/*
309 			 * We have this key.  Free the old key.  Since we
310 			 * don\'t want to leave empty slots in the middle of
311 			 * the array, we actually free the key there and move
312 			 * all the entries between the empty slot and the end
313 			 * of the array.
314 			 */
315 			Idtab *tab = idtab_lookup(version);
316 			key_free(tab->identities[idx].key);
317 			xfree(tab->identities[idx].comment);
318 			if (tab->nentries < 1)
319 				fatal("process_remove_identity: "
320 				    "internal error: tab->nentries %d",
321 				    tab->nentries);
322 			if (idx != tab->nentries - 1) {
323 				int i;
324 				for (i = idx; i < tab->nentries - 1; i++)
325 					tab->identities[i] = tab->identities[i+1];
326 			}
327 			tab->identities[tab->nentries - 1].key = NULL;
328 			tab->identities[tab->nentries - 1].comment = NULL;
329 			tab->nentries--;
330 			success = 1;
331 		}
332 		key_free(key);
333 	}
334 	buffer_put_int(&e->output, 1);
335 	buffer_put_char(&e->output,
336 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
337 }
338 
339 void
340 process_remove_all_identities(SocketEntry *e, int version)
341 {
342 	u_int i;
343 	Idtab *tab = idtab_lookup(version);
344 
345 	/* Loop over all identities and clear the keys. */
346 	for (i = 0; i < tab->nentries; i++) {
347 		key_free(tab->identities[i].key);
348 		xfree(tab->identities[i].comment);
349 	}
350 
351 	/* Mark that there are no identities. */
352 	tab->nentries = 0;
353 
354 	/* Send success. */
355 	buffer_put_int(&e->output, 1);
356 	buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
357 	return;
358 }
359 
360 void
361 process_add_identity(SocketEntry *e, int version)
362 {
363 	Key *k = NULL;
364 	char *type_name;
365 	char *comment;
366 	int type, success = 0;
367 	Idtab *tab = idtab_lookup(version);
368 
369 	switch (version) {
370 	case 1:
371 		k = key_new_private(KEY_RSA1);
372 		buffer_get_int(&e->input);			/* ignored */
373 		buffer_get_bignum(&e->input, k->rsa->n);
374 		buffer_get_bignum(&e->input, k->rsa->e);
375 		buffer_get_bignum(&e->input, k->rsa->d);
376 		buffer_get_bignum(&e->input, k->rsa->iqmp);
377 
378 		/* SSH and SSL have p and q swapped */
379 		buffer_get_bignum(&e->input, k->rsa->q);	/* p */
380 		buffer_get_bignum(&e->input, k->rsa->p);	/* q */
381 
382 		/* Generate additional parameters */
383 		generate_additional_parameters(k->rsa);
384 		break;
385 	case 2:
386 		type_name = buffer_get_string(&e->input, NULL);
387 		type = key_type_from_name(type_name);
388 		xfree(type_name);
389 		switch(type) {
390 		case KEY_DSA:
391 			k = key_new_private(type);
392 			buffer_get_bignum2(&e->input, k->dsa->p);
393 			buffer_get_bignum2(&e->input, k->dsa->q);
394 			buffer_get_bignum2(&e->input, k->dsa->g);
395 			buffer_get_bignum2(&e->input, k->dsa->pub_key);
396 			buffer_get_bignum2(&e->input, k->dsa->priv_key);
397 			break;
398 		case KEY_RSA:
399 			k = key_new_private(type);
400 			buffer_get_bignum2(&e->input, k->rsa->n);
401 			buffer_get_bignum2(&e->input, k->rsa->e);
402 			buffer_get_bignum2(&e->input, k->rsa->d);
403 			buffer_get_bignum2(&e->input, k->rsa->iqmp);
404 			buffer_get_bignum2(&e->input, k->rsa->p);
405 			buffer_get_bignum2(&e->input, k->rsa->q);
406 
407 			/* Generate additional parameters */
408 			generate_additional_parameters(k->rsa);
409 			break;
410 		default:
411 			buffer_clear(&e->input);
412 			goto send;
413 		}
414 		break;
415 	}
416 	comment = buffer_get_string(&e->input, NULL);
417 	if (k == NULL) {
418 		xfree(comment);
419 		goto send;
420 	}
421 	success = 1;
422 	if (lookup_private_key(k, NULL, version) == NULL) {
423 		if (tab->nentries == 0)
424 			tab->identities = xmalloc(sizeof(Identity));
425 		else
426 			tab->identities = xrealloc(tab->identities,
427 			    (tab->nentries + 1) * sizeof(Identity));
428 		tab->identities[tab->nentries].key = k;
429 		tab->identities[tab->nentries].comment = comment;
430 		/* Increment the number of identities. */
431 		tab->nentries++;
432 	} else {
433 		key_free(k);
434 		xfree(comment);
435 	}
436 send:
437 	buffer_put_int(&e->output, 1);
438 	buffer_put_char(&e->output,
439 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
440 }
441 
442 /* dispatch incoming messages */
443 
444 void
445 process_message(SocketEntry *e)
446 {
447 	u_int msg_len;
448 	u_int type;
449 	u_char *cp;
450 	if (buffer_len(&e->input) < 5)
451 		return;		/* Incomplete message. */
452 	cp = (u_char *) buffer_ptr(&e->input);
453 	msg_len = GET_32BIT(cp);
454 	if (msg_len > 256 * 1024) {
455 		shutdown(e->fd, SHUT_RDWR);
456 		close(e->fd);
457 		e->type = AUTH_UNUSED;
458 		return;
459 	}
460 	if (buffer_len(&e->input) < msg_len + 4)
461 		return;
462 	buffer_consume(&e->input, 4);
463 	type = buffer_get_char(&e->input);
464 
465 	switch (type) {
466 	/* ssh1 */
467 	case SSH_AGENTC_RSA_CHALLENGE:
468 		process_authentication_challenge1(e);
469 		break;
470 	case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
471 		process_request_identities(e, 1);
472 		break;
473 	case SSH_AGENTC_ADD_RSA_IDENTITY:
474 		process_add_identity(e, 1);
475 		break;
476 	case SSH_AGENTC_REMOVE_RSA_IDENTITY:
477 		process_remove_identity(e, 1);
478 		break;
479 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
480 		process_remove_all_identities(e, 1);
481 		break;
482 	/* ssh2 */
483 	case SSH2_AGENTC_SIGN_REQUEST:
484 		process_sign_request2(e);
485 		break;
486 	case SSH2_AGENTC_REQUEST_IDENTITIES:
487 		process_request_identities(e, 2);
488 		break;
489 	case SSH2_AGENTC_ADD_IDENTITY:
490 		process_add_identity(e, 2);
491 		break;
492 	case SSH2_AGENTC_REMOVE_IDENTITY:
493 		process_remove_identity(e, 2);
494 		break;
495 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
496 		process_remove_all_identities(e, 2);
497 		break;
498 	default:
499 		/* Unknown message.  Respond with failure. */
500 		error("Unknown message %d", type);
501 		buffer_clear(&e->input);
502 		buffer_put_int(&e->output, 1);
503 		buffer_put_char(&e->output, SSH_AGENT_FAILURE);
504 		break;
505 	}
506 }
507 
508 void
509 new_socket(int type, int fd)
510 {
511 	u_int i, old_alloc;
512 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
513 		error("fcntl O_NONBLOCK: %s", strerror(errno));
514 
515 	if (fd > max_fd)
516 		max_fd = fd;
517 
518 	for (i = 0; i < sockets_alloc; i++)
519 		if (sockets[i].type == AUTH_UNUSED) {
520 			sockets[i].fd = fd;
521 			sockets[i].type = type;
522 			buffer_init(&sockets[i].input);
523 			buffer_init(&sockets[i].output);
524 			return;
525 		}
526 	old_alloc = sockets_alloc;
527 	sockets_alloc += 10;
528 	if (sockets)
529 		sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
530 	else
531 		sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
532 	for (i = old_alloc; i < sockets_alloc; i++)
533 		sockets[i].type = AUTH_UNUSED;
534 	sockets[old_alloc].type = type;
535 	sockets[old_alloc].fd = fd;
536 	buffer_init(&sockets[old_alloc].input);
537 	buffer_init(&sockets[old_alloc].output);
538 }
539 
540 int
541 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl)
542 {
543 	u_int i, sz;
544 	int n = 0;
545 
546 	for (i = 0; i < sockets_alloc; i++) {
547 		switch (sockets[i].type) {
548 		case AUTH_SOCKET:
549 		case AUTH_CONNECTION:
550 			n = MAX(n, sockets[i].fd);
551 			break;
552 		case AUTH_UNUSED:
553 			break;
554 		default:
555 			fatal("Unknown socket type %d", sockets[i].type);
556 			break;
557 		}
558 	}
559 
560 	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
561 	if (*fdrp == NULL || n > *fdl) {
562 		if (*fdrp)
563 			xfree(*fdrp);
564 		if (*fdwp)
565 			xfree(*fdwp);
566 		*fdrp = xmalloc(sz);
567 		*fdwp = xmalloc(sz);
568 		*fdl = n;
569 	}
570 	memset(*fdrp, 0, sz);
571 	memset(*fdwp, 0, sz);
572 
573 	for (i = 0; i < sockets_alloc; i++) {
574 		switch (sockets[i].type) {
575 		case AUTH_SOCKET:
576 		case AUTH_CONNECTION:
577 			FD_SET(sockets[i].fd, *fdrp);
578 			if (buffer_len(&sockets[i].output) > 0)
579 				FD_SET(sockets[i].fd, *fdwp);
580 			break;
581 		default:
582 			break;
583 		}
584 	}
585 	return (1);
586 }
587 
588 void
589 after_select(fd_set *readset, fd_set *writeset)
590 {
591 	u_int i;
592 	int len, sock;
593 	socklen_t slen;
594 	char buf[1024];
595 	struct sockaddr_un sunaddr;
596 
597 	for (i = 0; i < sockets_alloc; i++)
598 		switch (sockets[i].type) {
599 		case AUTH_UNUSED:
600 			break;
601 		case AUTH_SOCKET:
602 			if (FD_ISSET(sockets[i].fd, readset)) {
603 				slen = sizeof(sunaddr);
604 				sock = accept(sockets[i].fd,
605 				    (struct sockaddr *) &sunaddr, &slen);
606 				if (sock < 0) {
607 					perror("accept from AUTH_SOCKET");
608 					break;
609 				}
610 				new_socket(AUTH_CONNECTION, sock);
611 			}
612 			break;
613 		case AUTH_CONNECTION:
614 			if (buffer_len(&sockets[i].output) > 0 &&
615 			    FD_ISSET(sockets[i].fd, writeset)) {
616 				do {
617 					len = write(sockets[i].fd,
618 					    buffer_ptr(&sockets[i].output),
619 					    buffer_len(&sockets[i].output));
620 					if (len == -1 && (errno == EAGAIN ||
621 					    errno == EINTR))
622 						continue;
623 					break;
624 				} while (1);
625 				if (len <= 0) {
626 					shutdown(sockets[i].fd, SHUT_RDWR);
627 					close(sockets[i].fd);
628 					sockets[i].type = AUTH_UNUSED;
629 					buffer_free(&sockets[i].input);
630 					buffer_free(&sockets[i].output);
631 					break;
632 				}
633 				buffer_consume(&sockets[i].output, len);
634 			}
635 			if (FD_ISSET(sockets[i].fd, readset)) {
636 				do {
637 					len = read(sockets[i].fd, buf, sizeof(buf));
638 					if (len == -1 && (errno == EAGAIN ||
639 					    errno == EINTR))
640 						continue;
641 					break;
642 				} while (1);
643 				if (len <= 0) {
644 					shutdown(sockets[i].fd, SHUT_RDWR);
645 					close(sockets[i].fd);
646 					sockets[i].type = AUTH_UNUSED;
647 					buffer_free(&sockets[i].input);
648 					buffer_free(&sockets[i].output);
649 					break;
650 				}
651 				buffer_append(&sockets[i].input, buf, len);
652 				process_message(&sockets[i]);
653 			}
654 			break;
655 		default:
656 			fatal("Unknown type %d", sockets[i].type);
657 		}
658 }
659 
660 void
661 check_parent_exists(int sig)
662 {
663 	int save_errno = errno;
664 
665 	if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
666 		/* printf("Parent has died - Authentication agent exiting.\n"); */
667 		exit(1);
668 	}
669 	signal(SIGALRM, check_parent_exists);
670 	alarm(10);
671 	errno = save_errno;
672 }
673 
674 void
675 cleanup_socket(void)
676 {
677 	if (socket_name[0])
678 		unlink(socket_name);
679 	if (socket_dir[0])
680 		rmdir(socket_dir);
681 }
682 
683 void
684 cleanup_exit(int i)
685 {
686 	cleanup_socket();
687 	exit(i);
688 }
689 
690 void
691 cleanup_handler(int sig)
692 {
693 	cleanup_socket();
694 	_exit(2);
695 }
696 
697 void
698 usage(void)
699 {
700 	fprintf(stderr, "ssh-agent version %s\n", SSH_VERSION);
701 	fprintf(stderr, "Usage: %s [-c | -s] [-k] [command {args...]]\n",
702 	    __progname);
703 	exit(1);
704 }
705 
706 int
707 main(int ac, char **av)
708 {
709 	int sock, c_flag = 0, k_flag = 0, s_flag = 0, ch;
710 	struct sockaddr_un sunaddr;
711 	struct rlimit rlim;
712 	pid_t pid;
713 	char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
714 	extern int optind;
715 	fd_set *readsetp = NULL, *writesetp = NULL;
716 
717 	SSLeay_add_all_algorithms();
718 
719 	while ((ch = getopt(ac, av, "cks")) != -1) {
720 		switch (ch) {
721 		case 'c':
722 			if (s_flag)
723 				usage();
724 			c_flag++;
725 			break;
726 		case 'k':
727 			k_flag++;
728 			break;
729 		case 's':
730 			if (c_flag)
731 				usage();
732 			s_flag++;
733 			break;
734 		default:
735 			usage();
736 		}
737 	}
738 	ac -= optind;
739 	av += optind;
740 
741 	if (ac > 0 && (c_flag || k_flag || s_flag))
742 		usage();
743 
744 	if (ac == 0 && !c_flag && !k_flag && !s_flag) {
745 		shell = getenv("SHELL");
746 		if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
747 			c_flag = 1;
748 	}
749 	if (k_flag) {
750 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
751 		if (pidstr == NULL) {
752 			fprintf(stderr, "%s not set, cannot kill agent\n",
753 			    SSH_AGENTPID_ENV_NAME);
754 			exit(1);
755 		}
756 		pid = atoi(pidstr);
757 		if (pid < 1) {
758 			fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
759 			    SSH_AGENTPID_ENV_NAME, pidstr);
760 			exit(1);
761 		}
762 		if (kill(pid, SIGTERM) == -1) {
763 			perror("kill");
764 			exit(1);
765 		}
766 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
767 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
768 		printf(format, SSH_AGENTPID_ENV_NAME);
769 		printf("echo Agent pid %d killed;\n", pid);
770 		exit(0);
771 	}
772 	parent_pid = getpid();
773 
774 	/* Create private directory for agent socket */
775 	strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
776 	if (mkdtemp(socket_dir) == NULL) {
777 		perror("mkdtemp: private socket dir");
778 		exit(1);
779 	}
780 	snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
781 	    parent_pid);
782 
783 	/*
784 	 * Create socket early so it will exist before command gets run from
785 	 * the parent.
786 	 */
787 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
788 	if (sock < 0) {
789 		perror("socket");
790 		cleanup_exit(1);
791 	}
792 	memset(&sunaddr, 0, sizeof(sunaddr));
793 	sunaddr.sun_family = AF_UNIX;
794 	strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
795 	sunaddr.sun_len = SUN_LEN(&sunaddr) + 1;
796 	if (bind(sock, (struct sockaddr *)&sunaddr, sunaddr.sun_len) < 0) {
797 		perror("bind");
798 		cleanup_exit(1);
799 	}
800 	if (listen(sock, 5) < 0) {
801 		perror("listen");
802 		cleanup_exit(1);
803 	}
804 
805 	/*
806 	 * Fork, and have the parent execute the command, if any, or present
807 	 * the socket data.  The child continues as the authentication agent.
808 	 */
809 	pid = fork();
810 	if (pid == -1) {
811 		perror("fork");
812 		exit(1);
813 	}
814 	if (pid != 0) {		/* Parent - execute the given command. */
815 		close(sock);
816 		snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
817 		if (ac == 0) {
818 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
819 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
820 			    SSH_AUTHSOCKET_ENV_NAME);
821 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
822 			    SSH_AGENTPID_ENV_NAME);
823 			printf("echo Agent pid %d;\n", pid);
824 			exit(0);
825 		}
826 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
827 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
828 			perror("setenv");
829 			exit(1);
830 		}
831 		execvp(av[0], av);
832 		perror(av[0]);
833 		exit(1);
834 	}
835 	close(0);
836 	close(1);
837 	close(2);
838 
839 	/* deny core dumps, since memory contains unencrypted private keys */
840 	rlim.rlim_cur = rlim.rlim_max = 0;
841 	if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
842 		perror("setrlimit rlimit_core failed");
843 		cleanup_exit(1);
844 	}
845 	if (setsid() == -1) {
846 		perror("setsid");
847 		cleanup_exit(1);
848 	}
849 	if (atexit(cleanup_socket) < 0) {
850 		perror("atexit");
851 		cleanup_exit(1);
852 	}
853 	new_socket(AUTH_SOCKET, sock);
854 	if (ac > 0) {
855 		signal(SIGALRM, check_parent_exists);
856 		alarm(10);
857 	}
858 	idtab_init();
859 	signal(SIGINT, SIG_IGN);
860 	signal(SIGPIPE, SIG_IGN);
861 	signal(SIGHUP, cleanup_handler);
862 	signal(SIGTERM, cleanup_handler);
863 	while (1) {
864 		prepare_select(&readsetp, &writesetp, &max_fd);
865 		if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
866 			if (errno == EINTR)
867 				continue;
868 			exit(1);
869 		}
870 		after_select(readsetp, writesetp);
871 	}
872 	/* NOTREACHED */
873 }
874