1 /* $OpenBSD: ssh-agent.c,v 1.36 2000/09/15 07:13:49 deraadt Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * The authentication agent program.
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".
15 * SSH2 implementation,
16 * Copyright (c) 2000 Markus Friedl. All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
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.
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.
40 RCSID("$OpenBSD: ssh-agent.c,v 1.36 2000/09/15 07:13:49 deraadt Exp $");
51 #include <openssl/evp.h>
52 #include <openssl/md5.h>
53 #include <openssl/dsa.h>
54 #include <openssl/rsa.h>
63 AUTH_UNUSED, AUTH_SOCKET, AUTH_CONNECTION
69 unsigned int sockets_alloc = 0;
70 SocketEntry *sockets = NULL;
82 /* private key table, one per protocol version */
87 /* pid of shell == parent of agent */
88 pid_t parent_pid = -1;
90 /* pathname and directory for AUTH_SOCKET */
91 char socket_name[1024];
92 char socket_dir[1024];
94 #ifdef HAVE___PROGNAME
95 extern char *__progname;
96 #else /* HAVE___PROGNAME */
97 static const char *__progname = "ssh-agent";
98 #endif /* HAVE___PROGNAME */
104 for (i = 0; i <=2; i++){
105 idtable[i].identities = NULL;
106 idtable[i].nentries = 0;
110 /* return private key table for requested protocol version */
112 idtab_lookup(int version)
114 if (version < 1 || version > 2)
115 fatal("internal error, bad protocol version %d", version);
116 return &idtable[version];
119 /* return matching private key for given public key */
121 lookup_private_key(Key *key, int *idx, int version)
124 Idtab *tab = idtab_lookup(version);
125 for (i = 0; i < tab->nentries; i++) {
126 if (key_equal(key, tab->identities[i].key)) {
129 return tab->identities[i].key;
135 /* send list of supported public keys to 'client' */
137 process_request_identities(SocketEntry *e, int version)
139 Idtab *tab = idtab_lookup(version);
144 buffer_put_char(&msg, (version == 1) ?
145 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
146 buffer_put_int(&msg, tab->nentries);
147 for (i = 0; i < tab->nentries; i++) {
148 Identity *id = &tab->identities[i];
149 if (id->key->type == KEY_RSA) {
150 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
151 buffer_put_bignum(&msg, id->key->rsa->e);
152 buffer_put_bignum(&msg, id->key->rsa->n);
156 dsa_make_key_blob(id->key, &blob, &blen);
157 buffer_put_string(&msg, blob, blen);
160 buffer_put_cstring(&msg, id->comment);
162 buffer_put_int(&e->output, buffer_len(&msg));
163 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
169 process_authentication_challenge1(SocketEntry *e)
176 unsigned char buf[32], mdbuf[16], session_id[16];
177 unsigned int response_type;
180 key = key_new(KEY_RSA);
181 challenge = BN_new();
183 buffer_get_int(&e->input); /* ignored */
184 buffer_get_bignum(&e->input, key->rsa->e);
185 buffer_get_bignum(&e->input, key->rsa->n);
186 buffer_get_bignum(&e->input, challenge);
188 /* Only protocol 1.1 is supported */
189 if (buffer_len(&e->input) == 0)
191 buffer_get(&e->input, (char *) session_id, 16);
192 response_type = buffer_get_int(&e->input);
193 if (response_type != 1)
196 private = lookup_private_key(key, NULL, 1);
197 if (private != NULL) {
198 /* Decrypt the challenge using the private key. */
199 rsa_private_decrypt(challenge, challenge, private->rsa);
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);
208 BN_bn2bin(challenge, buf + 32 - len);
210 MD5_Update(&md, buf, 32);
211 MD5_Update(&md, session_id, 16);
212 MD5_Final(mdbuf, &md);
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]);
222 /* Unknown identity or protocol error. Send failure. */
223 buffer_put_char(&msg, SSH_AGENT_FAILURE);
225 buffer_put_int(&e->output, buffer_len(&msg));
226 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
228 BN_clear_free(challenge);
234 process_sign_request2(SocketEntry *e)
236 extern int datafellows;
238 unsigned char *blob, *data, *signature = NULL;
239 unsigned int blen, dlen, slen = 0;
245 blob = buffer_get_string(&e->input, &blen);
246 data = buffer_get_string(&e->input, &dlen);
247 buffer_get_int(&e->input); /* flags, unused */
249 key = dsa_key_from_blob(blob, blen);
251 private = lookup_private_key(key, NULL, 2);
253 ok = dsa_sign(private, &signature, &slen, data, dlen);
258 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
259 buffer_put_string(&msg, signature, slen);
261 buffer_put_char(&msg, SSH_AGENT_FAILURE);
263 buffer_put_int(&e->output, buffer_len(&msg));
264 buffer_append(&e->output, buffer_ptr(&msg),
269 if (signature != NULL)
275 process_remove_identity(SocketEntry *e, int version)
277 Key *key = NULL, *private;
285 key = key_new(KEY_RSA);
286 bits = buffer_get_int(&e->input);
287 buffer_get_bignum(&e->input, key->rsa->e);
288 buffer_get_bignum(&e->input, key->rsa->n);
290 if (bits != key_size(key))
291 log("Warning: identity keysize mismatch: actual %d, announced %d",
292 key_size(key), bits);
295 blob = buffer_get_string(&e->input, &blen);
296 key = dsa_key_from_blob(blob, blen);
302 private = lookup_private_key(key, &idx, version);
303 if (private != NULL) {
305 * We have this key. Free the old key. Since we
306 * don\'t want to leave empty slots in the middle of
307 * the array, we actually free the key there and copy
308 * data from the last entry.
310 Idtab *tab = idtab_lookup(version);
311 key_free(tab->identities[idx].key);
312 xfree(tab->identities[idx].comment);
313 if (idx != tab->nentries)
314 tab->identities[idx] = tab->identities[tab->nentries];
320 buffer_put_int(&e->output, 1);
321 buffer_put_char(&e->output,
322 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
326 process_remove_all_identities(SocketEntry *e, int version)
329 Idtab *tab = idtab_lookup(version);
331 /* Loop over all identities and clear the keys. */
332 for (i = 0; i < tab->nentries; i++) {
333 key_free(tab->identities[i].key);
334 xfree(tab->identities[i].comment);
337 /* Mark that there are no identities. */
341 buffer_put_int(&e->output, 1);
342 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
347 process_add_identity(SocketEntry *e, int version)
356 Idtab *tab = idtab_lookup(version);
360 k = key_new(KEY_RSA);
363 /* allocate mem for private key */
364 /* XXX rsa->n and rsa->e are already allocated */
366 rsa->iqmp = BN_new();
369 rsa->dmq1 = BN_new();
370 rsa->dmp1 = BN_new();
372 buffer_get_int(&e->input); /* ignored */
374 buffer_get_bignum(&e->input, rsa->n);
375 buffer_get_bignum(&e->input, rsa->e);
376 buffer_get_bignum(&e->input, rsa->d);
377 buffer_get_bignum(&e->input, rsa->iqmp);
379 /* SSH and SSL have p and q swapped */
380 buffer_get_bignum(&e->input, rsa->q); /* p */
381 buffer_get_bignum(&e->input, rsa->p); /* q */
383 /* Generate additional parameters */
387 BN_sub(aux, rsa->q, BN_value_one());
388 BN_mod(rsa->dmq1, rsa->d, aux, ctx);
390 BN_sub(aux, rsa->p, BN_value_one());
391 BN_mod(rsa->dmp1, rsa->d, aux, ctx);
398 type = buffer_get_string(&e->input, NULL);
399 if (strcmp(type, KEX_DSS)) {
400 buffer_clear(&e->input);
406 k = key_new(KEY_DSA);
408 /* allocate mem for private key */
409 k->dsa->priv_key = BN_new();
411 buffer_get_bignum2(&e->input, k->dsa->p);
412 buffer_get_bignum2(&e->input, k->dsa->q);
413 buffer_get_bignum2(&e->input, k->dsa->g);
414 buffer_get_bignum2(&e->input, k->dsa->pub_key);
415 buffer_get_bignum2(&e->input, k->dsa->priv_key);
420 comment = buffer_get_string(&e->input, NULL);
426 if (lookup_private_key(k, NULL, version) == NULL) {
427 if (tab->nentries == 0)
428 tab->identities = xmalloc(sizeof(Identity));
430 tab->identities = xrealloc(tab->identities,
431 (tab->nentries + 1) * sizeof(Identity));
432 tab->identities[tab->nentries].key = k;
433 tab->identities[tab->nentries].comment = comment;
434 /* Increment the number of identities. */
441 buffer_put_int(&e->output, 1);
442 buffer_put_char(&e->output,
443 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
446 /* dispatch incoming messages */
449 process_message(SocketEntry *e)
451 unsigned int msg_len;
454 if (buffer_len(&e->input) < 5)
455 return; /* Incomplete message. */
456 cp = (unsigned char *) buffer_ptr(&e->input);
457 msg_len = GET_32BIT(cp);
458 if (msg_len > 256 * 1024) {
459 shutdown(e->fd, SHUT_RDWR);
461 e->type = AUTH_UNUSED;
464 if (buffer_len(&e->input) < msg_len + 4)
466 buffer_consume(&e->input, 4);
467 type = buffer_get_char(&e->input);
471 case SSH_AGENTC_RSA_CHALLENGE:
472 process_authentication_challenge1(e);
474 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
475 process_request_identities(e, 1);
477 case SSH_AGENTC_ADD_RSA_IDENTITY:
478 process_add_identity(e, 1);
480 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
481 process_remove_identity(e, 1);
483 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
484 process_remove_all_identities(e, 1);
487 case SSH2_AGENTC_SIGN_REQUEST:
488 process_sign_request2(e);
490 case SSH2_AGENTC_REQUEST_IDENTITIES:
491 process_request_identities(e, 2);
493 case SSH2_AGENTC_ADD_IDENTITY:
494 process_add_identity(e, 2);
496 case SSH2_AGENTC_REMOVE_IDENTITY:
497 process_remove_identity(e, 2);
499 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
500 process_remove_all_identities(e, 2);
503 /* Unknown message. Respond with failure. */
504 error("Unknown message %d", type);
505 buffer_clear(&e->input);
506 buffer_put_int(&e->output, 1);
507 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
513 new_socket(int type, int fd)
515 unsigned int i, old_alloc;
516 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
517 error("fcntl O_NONBLOCK: %s", strerror(errno));
522 for (i = 0; i < sockets_alloc; i++)
523 if (sockets[i].type == AUTH_UNUSED) {
525 sockets[i].type = type;
526 buffer_init(&sockets[i].input);
527 buffer_init(&sockets[i].output);
530 old_alloc = sockets_alloc;
533 sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
535 sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
536 for (i = old_alloc; i < sockets_alloc; i++)
537 sockets[i].type = AUTH_UNUSED;
538 sockets[old_alloc].type = type;
539 sockets[old_alloc].fd = fd;
540 buffer_init(&sockets[old_alloc].input);
541 buffer_init(&sockets[old_alloc].output);
545 prepare_select(fd_set *readset, fd_set *writeset)
548 for (i = 0; i < sockets_alloc; i++)
549 switch (sockets[i].type) {
551 case AUTH_CONNECTION:
552 FD_SET(sockets[i].fd, readset);
553 if (buffer_len(&sockets[i].output) > 0)
554 FD_SET(sockets[i].fd, writeset);
559 fatal("Unknown socket type %d", sockets[i].type);
565 after_select(fd_set *readset, fd_set *writeset)
571 struct sockaddr_un sunaddr;
573 for (i = 0; i < sockets_alloc; i++)
574 switch (sockets[i].type) {
578 if (FD_ISSET(sockets[i].fd, readset)) {
579 slen = sizeof(sunaddr);
580 sock = accept(sockets[i].fd, (struct sockaddr *) & sunaddr, &slen);
582 perror("accept from AUTH_SOCKET");
585 new_socket(AUTH_CONNECTION, sock);
588 case AUTH_CONNECTION:
589 if (buffer_len(&sockets[i].output) > 0 &&
590 FD_ISSET(sockets[i].fd, writeset)) {
591 len = write(sockets[i].fd, buffer_ptr(&sockets[i].output),
592 buffer_len(&sockets[i].output));
594 shutdown(sockets[i].fd, SHUT_RDWR);
595 close(sockets[i].fd);
596 sockets[i].type = AUTH_UNUSED;
597 buffer_free(&sockets[i].input);
598 buffer_free(&sockets[i].output);
601 buffer_consume(&sockets[i].output, len);
603 if (FD_ISSET(sockets[i].fd, readset)) {
604 len = read(sockets[i].fd, buf, sizeof(buf));
606 shutdown(sockets[i].fd, SHUT_RDWR);
607 close(sockets[i].fd);
608 sockets[i].type = AUTH_UNUSED;
609 buffer_free(&sockets[i].input);
610 buffer_free(&sockets[i].output);
613 buffer_append(&sockets[i].input, buf, len);
614 process_message(&sockets[i]);
618 fatal("Unknown type %d", sockets[i].type);
623 check_parent_exists(int sig)
625 if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
626 /* printf("Parent has died - Authentication agent exiting.\n"); */
629 signal(SIGALRM, check_parent_exists);
650 fprintf(stderr, "ssh-agent version %s\n", SSH_VERSION);
651 fprintf(stderr, "Usage: %s [-c | -s] [-k] [command {args...]]\n",
657 main(int ac, char **av)
659 fd_set readset, writeset;
660 int sock, c_flag = 0, k_flag = 0, s_flag = 0, ch;
661 struct sockaddr_un sunaddr;
663 char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
668 /* check if RSA support exists */
669 if (rsa_alive() == 0) {
671 "%s: no RSA support in libssl and libcrypto. See ssl(8).\n",
675 #ifdef __GNU_LIBRARY__
676 while ((ch = getopt(ac, av, "+cks")) != -1) {
677 #else /* __GNU_LIBRARY__ */
678 while ((ch = getopt(ac, av, "cks")) != -1) {
679 #endif /* __GNU_LIBRARY__ */
701 if (ac > 0 && (c_flag || k_flag || s_flag))
704 if (ac == 0 && !c_flag && !k_flag && !s_flag) {
705 shell = getenv("SHELL");
706 if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
710 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
711 if (pidstr == NULL) {
712 fprintf(stderr, "%s not set, cannot kill agent\n",
713 SSH_AGENTPID_ENV_NAME);
717 if (pid < 1) { /* XXX PID_MAX check too */
718 /* Yes, PID_MAX check please */
719 fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
720 SSH_AGENTPID_ENV_NAME, pidstr);
723 if (kill(pid, SIGTERM) == -1) {
727 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
728 printf(format, SSH_AUTHSOCKET_ENV_NAME);
729 printf(format, SSH_AGENTPID_ENV_NAME);
730 printf("echo Agent pid %d killed;\n", pid);
733 parent_pid = getpid();
735 /* Create private directory for agent socket */
736 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
737 if (mkdtemp(socket_dir) == NULL) {
738 perror("mkdtemp: private socket dir");
741 snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
745 * Create socket early so it will exist before command gets run from
748 sock = socket(AF_UNIX, SOCK_STREAM, 0);
753 memset(&sunaddr, 0, sizeof(sunaddr));
754 sunaddr.sun_family = AF_UNIX;
755 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
756 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
760 if (listen(sock, 5) < 0) {
765 * Fork, and have the parent execute the command, if any, or present
766 * the socket data. The child continues as the authentication agent.
773 if (pid != 0) { /* Parent - execute the given command. */
775 snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
777 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
778 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
779 SSH_AUTHSOCKET_ENV_NAME);
780 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
781 SSH_AGENTPID_ENV_NAME);
782 printf("echo Agent pid %d;\n", pid);
785 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
786 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
798 if (setsid() == -1) {
802 if (atexit(cleanup_socket) < 0) {
806 new_socket(AUTH_SOCKET, sock);
808 signal(SIGALRM, check_parent_exists);
812 signal(SIGINT, SIG_IGN);
813 signal(SIGPIPE, SIG_IGN);
814 signal(SIGHUP, cleanup_exit);
815 signal(SIGTERM, cleanup_exit);
819 prepare_select(&readset, &writeset);
820 if (select(max_fd + 1, &readset, &writeset, NULL, NULL) < 0) {
825 after_select(&readset, &writeset);