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