xref: /freebsd/crypto/openssh/ssh-agent.c (revision 23f282aa31e9b6fceacd449020e936e98d6f2298)
1 /*	$OpenBSD: ssh-agent.c,v 1.26 2000/03/16 20:56:14 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  * Created: Wed Mar 29 03:46:59 1995 ylo
8  * The authentication agent program.
9  *
10  * $FreeBSD$
11  */
12 
13 #include "includes.h"
14 RCSID("$OpenBSD: ssh-agent.c,v 1.26 2000/03/16 20:56:14 markus Exp $");
15 
16 #include "ssh.h"
17 #include "rsa.h"
18 #include "authfd.h"
19 #include "buffer.h"
20 #include "bufaux.h"
21 #include "xmalloc.h"
22 #include "packet.h"
23 #include "getput.h"
24 #include "mpaux.h"
25 
26 #include <openssl/md5.h>
27 
28 typedef struct {
29 	int fd;
30 	enum {
31 		AUTH_UNUSED, AUTH_SOCKET, AUTH_CONNECTION
32 	} type;
33 	Buffer input;
34 	Buffer output;
35 } SocketEntry;
36 
37 unsigned int sockets_alloc = 0;
38 SocketEntry *sockets = NULL;
39 
40 typedef struct {
41 	RSA *key;
42 	char *comment;
43 } Identity;
44 
45 unsigned int num_identities = 0;
46 Identity *identities = NULL;
47 
48 int max_fd = 0;
49 
50 /* pid of shell == parent of agent */
51 int parent_pid = -1;
52 
53 /* pathname and directory for AUTH_SOCKET */
54 char socket_name[1024];
55 char socket_dir[1024];
56 
57 extern char *__progname;
58 
59 void
60 process_request_identity(SocketEntry *e)
61 {
62 	Buffer msg;
63 	int i;
64 
65 	buffer_init(&msg);
66 	buffer_put_char(&msg, SSH_AGENT_RSA_IDENTITIES_ANSWER);
67 	buffer_put_int(&msg, num_identities);
68 	for (i = 0; i < num_identities; i++) {
69 		buffer_put_int(&msg, BN_num_bits(identities[i].key->n));
70 		buffer_put_bignum(&msg, identities[i].key->e);
71 		buffer_put_bignum(&msg, identities[i].key->n);
72 		buffer_put_string(&msg, identities[i].comment,
73 				  strlen(identities[i].comment));
74 	}
75 	buffer_put_int(&e->output, buffer_len(&msg));
76 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
77 	buffer_free(&msg);
78 }
79 
80 void
81 process_authentication_challenge(SocketEntry *e)
82 {
83 	int i, pub_bits, len;
84 	BIGNUM *pub_e, *pub_n, *challenge;
85 	Buffer msg;
86 	MD5_CTX md;
87 	unsigned char buf[32], mdbuf[16], session_id[16];
88 	unsigned int response_type;
89 
90 	buffer_init(&msg);
91 	pub_e = BN_new();
92 	pub_n = BN_new();
93 	challenge = BN_new();
94 	pub_bits = buffer_get_int(&e->input);
95 	buffer_get_bignum(&e->input, pub_e);
96 	buffer_get_bignum(&e->input, pub_n);
97 	buffer_get_bignum(&e->input, challenge);
98 	if (buffer_len(&e->input) == 0) {
99 		/* Compatibility code for old servers. */
100 		memset(session_id, 0, 16);
101 		response_type = 0;
102 	} else {
103 		/* New code. */
104 		buffer_get(&e->input, (char *) session_id, 16);
105 		response_type = buffer_get_int(&e->input);
106 	}
107 	for (i = 0; i < num_identities; i++)
108 		if (pub_bits == BN_num_bits(identities[i].key->n) &&
109 		    BN_cmp(pub_e, identities[i].key->e) == 0 &&
110 		    BN_cmp(pub_n, identities[i].key->n) == 0) {
111 			/* Decrypt the challenge using the private key. */
112 			rsa_private_decrypt(challenge, challenge, identities[i].key);
113 
114 			/* Compute the desired response. */
115 			switch (response_type) {
116 			case 0:/* As of protocol 1.0 */
117 				/* This response type is no longer supported. */
118 				log("Compatibility with ssh protocol 1.0 no longer supported.");
119 				buffer_put_char(&msg, SSH_AGENT_FAILURE);
120 				goto send;
121 
122 			case 1:/* As of protocol 1.1 */
123 				/* The response is MD5 of decrypted challenge plus session id. */
124 				len = BN_num_bytes(challenge);
125 
126 				if (len <= 0 || len > 32) {
127 					fatal("process_authentication_challenge: "
128 					 "bad challenge length %d", len);
129 				}
130 				memset(buf, 0, 32);
131 				BN_bn2bin(challenge, buf + 32 - len);
132 				MD5_Init(&md);
133 				MD5_Update(&md, buf, 32);
134 				MD5_Update(&md, session_id, 16);
135 				MD5_Final(mdbuf, &md);
136 				break;
137 
138 			default:
139 				fatal("process_authentication_challenge: bad response_type %d",
140 				      response_type);
141 				break;
142 			}
143 
144 			/* Send the response. */
145 			buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
146 			for (i = 0; i < 16; i++)
147 				buffer_put_char(&msg, mdbuf[i]);
148 
149 			goto send;
150 		}
151 	/* Unknown identity.  Send failure. */
152 	buffer_put_char(&msg, SSH_AGENT_FAILURE);
153 send:
154 	buffer_put_int(&e->output, buffer_len(&msg));
155 	buffer_append(&e->output, buffer_ptr(&msg),
156 		      buffer_len(&msg));
157 	buffer_free(&msg);
158 	BN_clear_free(pub_e);
159 	BN_clear_free(pub_n);
160 	BN_clear_free(challenge);
161 }
162 
163 void
164 process_remove_identity(SocketEntry *e)
165 {
166 	unsigned int bits;
167 	unsigned int i;
168 	BIGNUM *dummy, *n;
169 
170 	dummy = BN_new();
171 	n = BN_new();
172 
173 	/* Get the key from the packet. */
174 	bits = buffer_get_int(&e->input);
175 	buffer_get_bignum(&e->input, dummy);
176 	buffer_get_bignum(&e->input, n);
177 
178 	if (bits != BN_num_bits(n))
179 		error("Warning: identity keysize mismatch: actual %d, announced %d",
180 		      BN_num_bits(n), bits);
181 
182 	/* Check if we have the key. */
183 	for (i = 0; i < num_identities; i++)
184 		if (BN_cmp(identities[i].key->n, n) == 0) {
185 			/*
186 			 * We have this key.  Free the old key.  Since we
187 			 * don\'t want to leave empty slots in the middle of
188 			 * the array, we actually free the key there and copy
189 			 * data from the last entry.
190 			 */
191 			RSA_free(identities[i].key);
192 			xfree(identities[i].comment);
193 			if (i < num_identities - 1)
194 				identities[i] = identities[num_identities - 1];
195 			num_identities--;
196 			BN_clear_free(dummy);
197 			BN_clear_free(n);
198 
199 			/* Send success. */
200 			buffer_put_int(&e->output, 1);
201 			buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
202 			return;
203 		}
204 	/* We did not have the key. */
205 	BN_clear(dummy);
206 	BN_clear(n);
207 
208 	/* Send failure. */
209 	buffer_put_int(&e->output, 1);
210 	buffer_put_char(&e->output, SSH_AGENT_FAILURE);
211 }
212 
213 /*
214  * Removes all identities from the agent.
215  */
216 void
217 process_remove_all_identities(SocketEntry *e)
218 {
219 	unsigned int i;
220 
221 	/* Loop over all identities and clear the keys. */
222 	for (i = 0; i < num_identities; i++) {
223 		RSA_free(identities[i].key);
224 		xfree(identities[i].comment);
225 	}
226 
227 	/* Mark that there are no identities. */
228 	num_identities = 0;
229 
230 	/* Send success. */
231 	buffer_put_int(&e->output, 1);
232 	buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
233 	return;
234 }
235 
236 /*
237  * Adds an identity to the agent.
238  */
239 void
240 process_add_identity(SocketEntry *e)
241 {
242 	RSA *k;
243 	int i;
244 	BIGNUM *aux;
245 	BN_CTX *ctx;
246 
247 	if (num_identities == 0)
248 		identities = xmalloc(sizeof(Identity));
249 	else
250 		identities = xrealloc(identities, (num_identities + 1) * sizeof(Identity));
251 
252 	identities[num_identities].key = RSA_new();
253 	k = identities[num_identities].key;
254 	buffer_get_int(&e->input);	/* bits */
255 	k->n = BN_new();
256 	buffer_get_bignum(&e->input, k->n);
257 	k->e = BN_new();
258 	buffer_get_bignum(&e->input, k->e);
259 	k->d = BN_new();
260 	buffer_get_bignum(&e->input, k->d);
261 	k->iqmp = BN_new();
262 	buffer_get_bignum(&e->input, k->iqmp);
263 	/* SSH and SSL have p and q swapped */
264 	k->q = BN_new();
265 	buffer_get_bignum(&e->input, k->q);	/* p */
266 	k->p = BN_new();
267 	buffer_get_bignum(&e->input, k->p);	/* q */
268 
269 	/* Generate additional parameters */
270 	aux = BN_new();
271 	ctx = BN_CTX_new();
272 
273 	BN_sub(aux, k->q, BN_value_one());
274 	k->dmq1 = BN_new();
275 	BN_mod(k->dmq1, k->d, aux, ctx);
276 
277 	BN_sub(aux, k->p, BN_value_one());
278 	k->dmp1 = BN_new();
279 	BN_mod(k->dmp1, k->d, aux, ctx);
280 
281 	BN_clear_free(aux);
282 	BN_CTX_free(ctx);
283 
284 	identities[num_identities].comment = buffer_get_string(&e->input, NULL);
285 
286 	/* Check if we already have the key. */
287 	for (i = 0; i < num_identities; i++)
288 		if (BN_cmp(identities[i].key->n, k->n) == 0) {
289 			/*
290 			 * We already have this key.  Clear and free the new
291 			 * data and return success.
292 			 */
293 			RSA_free(k);
294 			xfree(identities[num_identities].comment);
295 
296 			/* Send success. */
297 			buffer_put_int(&e->output, 1);
298 			buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
299 			return;
300 		}
301 	/* Increment the number of identities. */
302 	num_identities++;
303 
304 	/* Send a success message. */
305 	buffer_put_int(&e->output, 1);
306 	buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
307 }
308 
309 void
310 process_message(SocketEntry *e)
311 {
312 	unsigned int msg_len;
313 	unsigned int type;
314 	unsigned char *cp;
315 	if (buffer_len(&e->input) < 5)
316 		return;		/* Incomplete message. */
317 	cp = (unsigned char *) buffer_ptr(&e->input);
318 	msg_len = GET_32BIT(cp);
319 	if (msg_len > 256 * 1024) {
320 		shutdown(e->fd, SHUT_RDWR);
321 		close(e->fd);
322 		e->type = AUTH_UNUSED;
323 		return;
324 	}
325 	if (buffer_len(&e->input) < msg_len + 4)
326 		return;
327 	buffer_consume(&e->input, 4);
328 	type = buffer_get_char(&e->input);
329 
330 	switch (type) {
331 	case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
332 		process_request_identity(e);
333 		break;
334 	case SSH_AGENTC_RSA_CHALLENGE:
335 		process_authentication_challenge(e);
336 		break;
337 	case SSH_AGENTC_ADD_RSA_IDENTITY:
338 		process_add_identity(e);
339 		break;
340 	case SSH_AGENTC_REMOVE_RSA_IDENTITY:
341 		process_remove_identity(e);
342 		break;
343 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
344 		process_remove_all_identities(e);
345 		break;
346 	default:
347 		/* Unknown message.  Respond with failure. */
348 		error("Unknown message %d", type);
349 		buffer_clear(&e->input);
350 		buffer_put_int(&e->output, 1);
351 		buffer_put_char(&e->output, SSH_AGENT_FAILURE);
352 		break;
353 	}
354 }
355 
356 void
357 new_socket(int type, int fd)
358 {
359 	unsigned int i, old_alloc;
360 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
361 		error("fcntl O_NONBLOCK: %s", strerror(errno));
362 
363 	if (fd > max_fd)
364 		max_fd = fd;
365 
366 	for (i = 0; i < sockets_alloc; i++)
367 		if (sockets[i].type == AUTH_UNUSED) {
368 			sockets[i].fd = fd;
369 			sockets[i].type = type;
370 			buffer_init(&sockets[i].input);
371 			buffer_init(&sockets[i].output);
372 			return;
373 		}
374 	old_alloc = sockets_alloc;
375 	sockets_alloc += 10;
376 	if (sockets)
377 		sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
378 	else
379 		sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
380 	for (i = old_alloc; i < sockets_alloc; i++)
381 		sockets[i].type = AUTH_UNUSED;
382 	sockets[old_alloc].type = type;
383 	sockets[old_alloc].fd = fd;
384 	buffer_init(&sockets[old_alloc].input);
385 	buffer_init(&sockets[old_alloc].output);
386 }
387 
388 void
389 prepare_select(fd_set *readset, fd_set *writeset)
390 {
391 	unsigned int i;
392 	for (i = 0; i < sockets_alloc; i++)
393 		switch (sockets[i].type) {
394 		case AUTH_SOCKET:
395 		case AUTH_CONNECTION:
396 			FD_SET(sockets[i].fd, readset);
397 			if (buffer_len(&sockets[i].output) > 0)
398 				FD_SET(sockets[i].fd, writeset);
399 			break;
400 		case AUTH_UNUSED:
401 			break;
402 		default:
403 			fatal("Unknown socket type %d", sockets[i].type);
404 			break;
405 		}
406 }
407 
408 void
409 after_select(fd_set *readset, fd_set *writeset)
410 {
411 	unsigned int i;
412 	int len, sock;
413 	socklen_t slen;
414 	char buf[1024];
415 	struct sockaddr_un sunaddr;
416 
417 	for (i = 0; i < sockets_alloc; i++)
418 		switch (sockets[i].type) {
419 		case AUTH_UNUSED:
420 			break;
421 		case AUTH_SOCKET:
422 			if (FD_ISSET(sockets[i].fd, readset)) {
423 				slen = sizeof(sunaddr);
424 				sock = accept(sockets[i].fd, (struct sockaddr *) & sunaddr, &slen);
425 				if (sock < 0) {
426 					perror("accept from AUTH_SOCKET");
427 					break;
428 				}
429 				new_socket(AUTH_CONNECTION, sock);
430 			}
431 			break;
432 		case AUTH_CONNECTION:
433 			if (buffer_len(&sockets[i].output) > 0 &&
434 			    FD_ISSET(sockets[i].fd, writeset)) {
435 				len = write(sockets[i].fd, buffer_ptr(&sockets[i].output),
436 					 buffer_len(&sockets[i].output));
437 				if (len <= 0) {
438 					shutdown(sockets[i].fd, SHUT_RDWR);
439 					close(sockets[i].fd);
440 					sockets[i].type = AUTH_UNUSED;
441 					break;
442 				}
443 				buffer_consume(&sockets[i].output, len);
444 			}
445 			if (FD_ISSET(sockets[i].fd, readset)) {
446 				len = read(sockets[i].fd, buf, sizeof(buf));
447 				if (len <= 0) {
448 					shutdown(sockets[i].fd, SHUT_RDWR);
449 					close(sockets[i].fd);
450 					sockets[i].type = AUTH_UNUSED;
451 					break;
452 				}
453 				buffer_append(&sockets[i].input, buf, len);
454 				process_message(&sockets[i]);
455 			}
456 			break;
457 		default:
458 			fatal("Unknown type %d", sockets[i].type);
459 		}
460 }
461 
462 void
463 check_parent_exists(int sig)
464 {
465 	if (kill(parent_pid, 0) < 0) {
466 		/* printf("Parent has died - Authentication agent exiting.\n"); */
467 		exit(1);
468 	}
469 	signal(SIGALRM, check_parent_exists);
470 	alarm(10);
471 }
472 
473 void
474 cleanup_socket(void)
475 {
476 	remove(socket_name);
477 	rmdir(socket_dir);
478 }
479 
480 void
481 cleanup_exit(int i)
482 {
483 	cleanup_socket();
484 	exit(i);
485 }
486 
487 void
488 usage()
489 {
490 	fprintf(stderr, "ssh-agent version %s\n", SSH_VERSION);
491 	fprintf(stderr, "Usage: %s [-c | -s] [-k] [command {args...]]\n",
492 		__progname);
493 	exit(1);
494 }
495 
496 int
497 main(int ac, char **av)
498 {
499 	fd_set readset, writeset;
500 	int sock, c_flag = 0, k_flag = 0, s_flag = 0, ch;
501 	struct sockaddr_un sunaddr;
502 	pid_t pid;
503 	char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
504 
505 	/* check if RSA support exists */
506 	if (rsa_alive() == 0) {
507 		fprintf(stderr,
508 			"%s: no RSA support in libssl and libcrypto.  See ssl(8).\n",
509 			__progname);
510 		exit(1);
511 	}
512 	while ((ch = getopt(ac, av, "cks")) != -1) {
513 		switch (ch) {
514 		case 'c':
515 			if (s_flag)
516 				usage();
517 			c_flag++;
518 			break;
519 		case 'k':
520 			k_flag++;
521 			break;
522 		case 's':
523 			if (c_flag)
524 				usage();
525 			s_flag++;
526 			break;
527 		default:
528 			usage();
529 		}
530 	}
531 	ac -= optind;
532 	av += optind;
533 
534 	if (ac > 0 && (c_flag || k_flag || s_flag))
535 		usage();
536 
537 	if (ac == 0 && !c_flag && !k_flag && !s_flag) {
538 		shell = getenv("SHELL");
539 		if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
540 			c_flag = 1;
541 	}
542 	if (k_flag) {
543 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
544 		if (pidstr == NULL) {
545 			fprintf(stderr, "%s not set, cannot kill agent\n",
546 				SSH_AGENTPID_ENV_NAME);
547 			exit(1);
548 		}
549 		pid = atoi(pidstr);
550 		if (pid < 1) {	/* XXX PID_MAX check too */
551 			fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
552 				SSH_AGENTPID_ENV_NAME, pidstr);
553 			exit(1);
554 		}
555 		if (kill(pid, SIGTERM) == -1) {
556 			perror("kill");
557 			exit(1);
558 		}
559 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
560 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
561 		printf(format, SSH_AGENTPID_ENV_NAME);
562 		printf("echo Agent pid %d killed;\n", pid);
563 		exit(0);
564 	}
565 	parent_pid = getpid();
566 
567 	/* Create private directory for agent socket */
568 	strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
569 	if (mkdtemp(socket_dir) == NULL) {
570 		perror("mkdtemp: private socket dir");
571 		exit(1);
572 	}
573 	snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
574 		 parent_pid);
575 
576 	/*
577 	 * Create socket early so it will exist before command gets run from
578 	 * the parent.
579 	 */
580 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
581 	if (sock < 0) {
582 		perror("socket");
583 		cleanup_exit(1);
584 	}
585 	memset(&sunaddr, 0, sizeof(sunaddr));
586 	sunaddr.sun_family = AF_UNIX;
587 	strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
588 	if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
589 		perror("bind");
590 		cleanup_exit(1);
591 	}
592 	if (listen(sock, 5) < 0) {
593 		perror("listen");
594 		cleanup_exit(1);
595 	}
596 	/*
597 	 * Fork, and have the parent execute the command, if any, or present
598 	 * the socket data.  The child continues as the authentication agent.
599 	 */
600 	pid = fork();
601 	if (pid == -1) {
602 		perror("fork");
603 		exit(1);
604 	}
605 	if (pid != 0) {		/* Parent - execute the given command. */
606 		close(sock);
607 		snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
608 		if (ac == 0) {
609 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
610 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
611 			       SSH_AUTHSOCKET_ENV_NAME);
612 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
613 			       SSH_AGENTPID_ENV_NAME);
614 			printf("echo Agent pid %d;\n", pid);
615 			exit(0);
616 		}
617 		setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1);
618 		setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1);
619 		execvp(av[0], av);
620 		perror(av[0]);
621 		exit(1);
622 	}
623 	close(0);
624 	close(1);
625 	close(2);
626 
627 	if (setsid() == -1) {
628 		perror("setsid");
629 		cleanup_exit(1);
630 	}
631 	if (atexit(cleanup_socket) < 0) {
632 		perror("atexit");
633 		cleanup_exit(1);
634 	}
635 	new_socket(AUTH_SOCKET, sock);
636 	if (ac > 0) {
637 		signal(SIGALRM, check_parent_exists);
638 		alarm(10);
639 	}
640 	signal(SIGINT, SIG_IGN);
641 	signal(SIGPIPE, SIG_IGN);
642 	signal(SIGHUP, cleanup_exit);
643 	signal(SIGTERM, cleanup_exit);
644 	while (1) {
645 		FD_ZERO(&readset);
646 		FD_ZERO(&writeset);
647 		prepare_select(&readset, &writeset);
648 		if (select(max_fd + 1, &readset, &writeset, NULL, NULL) < 0) {
649 			if (errno == EINTR)
650 				continue;
651 			exit(1);
652 		}
653 		after_select(&readset, &writeset);
654 	}
655 	/* NOTREACHED */
656 }
657