1 /* $OpenBSD: ssh-agent.c,v 1.55 2001/06/23 15:12:20 itojun 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.55 2001/06/23 15:12:20 itojun Exp $");
42 #include <openssl/evp.h>
43 #include <openssl/md5.h>
63 AUTH_UNUSED, AUTH_SOCKET, AUTH_CONNECTION
69 u_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;
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_RSA1) {
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 key_to_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 u_char buf[32], mdbuf[16], session_id[16];
180 key = key_new(KEY_RSA1);
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 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
202 /* The response is MD5 of decrypted challenge plus session id. */
203 len = BN_num_bytes(challenge);
204 if (len <= 0 || len > 32) {
205 log("process_authentication_challenge: bad challenge length %d", len);
209 BN_bn2bin(challenge, buf + 32 - len);
211 MD5_Update(&md, buf, 32);
212 MD5_Update(&md, session_id, 16);
213 MD5_Final(mdbuf, &md);
215 /* Send the response. */
216 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
217 for (i = 0; i < 16; i++)
218 buffer_put_char(&msg, mdbuf[i]);
223 /* Unknown identity or protocol error. Send failure. */
224 buffer_put_char(&msg, SSH_AGENT_FAILURE);
226 buffer_put_int(&e->output, buffer_len(&msg));
227 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
229 BN_clear_free(challenge);
235 process_sign_request2(SocketEntry *e)
237 extern int datafellows;
239 u_char *blob, *data, *signature = NULL;
240 u_int blen, dlen, slen = 0;
247 blob = buffer_get_string(&e->input, &blen);
248 data = buffer_get_string(&e->input, &dlen);
250 flags = buffer_get_int(&e->input);
251 if (flags & SSH_AGENT_OLD_SIGNATURE)
252 datafellows = SSH_BUG_SIGBLOB;
254 key = key_from_blob(blob, blen);
256 private = lookup_private_key(key, NULL, 2);
258 ok = key_sign(private, &signature, &slen, data, dlen);
263 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
264 buffer_put_string(&msg, signature, slen);
266 buffer_put_char(&msg, SSH_AGENT_FAILURE);
268 buffer_put_int(&e->output, buffer_len(&msg));
269 buffer_append(&e->output, buffer_ptr(&msg),
274 if (signature != NULL)
280 process_remove_identity(SocketEntry *e, int version)
282 Key *key = NULL, *private;
290 key = key_new(KEY_RSA1);
291 bits = buffer_get_int(&e->input);
292 buffer_get_bignum(&e->input, key->rsa->e);
293 buffer_get_bignum(&e->input, key->rsa->n);
295 if (bits != key_size(key))
296 log("Warning: identity keysize mismatch: actual %d, announced %d",
297 key_size(key), bits);
300 blob = buffer_get_string(&e->input, &blen);
301 key = key_from_blob(blob, blen);
307 private = lookup_private_key(key, &idx, version);
308 if (private != NULL) {
310 * We have this key. Free the old key. Since we
311 * don\'t want to leave empty slots in the middle of
312 * the array, we actually free the key there and move
313 * all the entries between the empty slot and the end
316 Idtab *tab = idtab_lookup(version);
317 key_free(tab->identities[idx].key);
318 xfree(tab->identities[idx].comment);
319 if (tab->nentries < 1)
320 fatal("process_remove_identity: "
321 "internal error: tab->nentries %d",
323 if (idx != tab->nentries - 1) {
325 for (i = idx; i < tab->nentries - 1; i++)
326 tab->identities[i] = tab->identities[i+1];
328 tab->identities[tab->nentries - 1].key = NULL;
329 tab->identities[tab->nentries - 1].comment = NULL;
335 buffer_put_int(&e->output, 1);
336 buffer_put_char(&e->output,
337 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
341 process_remove_all_identities(SocketEntry *e, int version)
344 Idtab *tab = idtab_lookup(version);
346 /* Loop over all identities and clear the keys. */
347 for (i = 0; i < tab->nentries; i++) {
348 key_free(tab->identities[i].key);
349 xfree(tab->identities[i].comment);
352 /* Mark that there are no identities. */
356 buffer_put_int(&e->output, 1);
357 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
362 process_add_identity(SocketEntry *e, int version)
367 int type, success = 0;
368 Idtab *tab = idtab_lookup(version);
372 k = key_new_private(KEY_RSA1);
373 buffer_get_int(&e->input); /* ignored */
374 buffer_get_bignum(&e->input, k->rsa->n);
375 buffer_get_bignum(&e->input, k->rsa->e);
376 buffer_get_bignum(&e->input, k->rsa->d);
377 buffer_get_bignum(&e->input, k->rsa->iqmp);
379 /* SSH and SSL have p and q swapped */
380 buffer_get_bignum(&e->input, k->rsa->q); /* p */
381 buffer_get_bignum(&e->input, k->rsa->p); /* q */
383 /* Generate additional parameters */
384 generate_additional_parameters(k->rsa);
387 type_name = buffer_get_string(&e->input, NULL);
388 type = key_type_from_name(type_name);
392 k = key_new_private(type);
393 buffer_get_bignum2(&e->input, k->dsa->p);
394 buffer_get_bignum2(&e->input, k->dsa->q);
395 buffer_get_bignum2(&e->input, k->dsa->g);
396 buffer_get_bignum2(&e->input, k->dsa->pub_key);
397 buffer_get_bignum2(&e->input, k->dsa->priv_key);
400 k = key_new_private(type);
401 buffer_get_bignum2(&e->input, k->rsa->n);
402 buffer_get_bignum2(&e->input, k->rsa->e);
403 buffer_get_bignum2(&e->input, k->rsa->d);
404 buffer_get_bignum2(&e->input, k->rsa->iqmp);
405 buffer_get_bignum2(&e->input, k->rsa->p);
406 buffer_get_bignum2(&e->input, k->rsa->q);
408 /* Generate additional parameters */
409 generate_additional_parameters(k->rsa);
412 buffer_clear(&e->input);
417 comment = buffer_get_string(&e->input, NULL);
423 if (lookup_private_key(k, NULL, version) == NULL) {
424 if (tab->nentries == 0)
425 tab->identities = xmalloc(sizeof(Identity));
427 tab->identities = xrealloc(tab->identities,
428 (tab->nentries + 1) * sizeof(Identity));
429 tab->identities[tab->nentries].key = k;
430 tab->identities[tab->nentries].comment = comment;
431 /* Increment the number of identities. */
438 buffer_put_int(&e->output, 1);
439 buffer_put_char(&e->output,
440 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
443 /* dispatch incoming messages */
446 process_message(SocketEntry *e)
451 if (buffer_len(&e->input) < 5)
452 return; /* Incomplete message. */
453 cp = (u_char *) buffer_ptr(&e->input);
454 msg_len = GET_32BIT(cp);
455 if (msg_len > 256 * 1024) {
456 shutdown(e->fd, SHUT_RDWR);
458 e->type = AUTH_UNUSED;
461 if (buffer_len(&e->input) < msg_len + 4)
463 buffer_consume(&e->input, 4);
464 type = buffer_get_char(&e->input);
468 case SSH_AGENTC_RSA_CHALLENGE:
469 process_authentication_challenge1(e);
471 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
472 process_request_identities(e, 1);
474 case SSH_AGENTC_ADD_RSA_IDENTITY:
475 process_add_identity(e, 1);
477 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
478 process_remove_identity(e, 1);
480 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
481 process_remove_all_identities(e, 1);
484 case SSH2_AGENTC_SIGN_REQUEST:
485 process_sign_request2(e);
487 case SSH2_AGENTC_REQUEST_IDENTITIES:
488 process_request_identities(e, 2);
490 case SSH2_AGENTC_ADD_IDENTITY:
491 process_add_identity(e, 2);
493 case SSH2_AGENTC_REMOVE_IDENTITY:
494 process_remove_identity(e, 2);
496 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
497 process_remove_all_identities(e, 2);
500 /* Unknown message. Respond with failure. */
501 error("Unknown message %d", type);
502 buffer_clear(&e->input);
503 buffer_put_int(&e->output, 1);
504 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
510 new_socket(int type, int fd)
513 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
514 error("fcntl O_NONBLOCK: %s", strerror(errno));
519 for (i = 0; i < sockets_alloc; i++)
520 if (sockets[i].type == AUTH_UNUSED) {
522 sockets[i].type = type;
523 buffer_init(&sockets[i].input);
524 buffer_init(&sockets[i].output);
527 old_alloc = sockets_alloc;
530 sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
532 sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
533 for (i = old_alloc; i < sockets_alloc; i++)
534 sockets[i].type = AUTH_UNUSED;
535 sockets[old_alloc].type = type;
536 sockets[old_alloc].fd = fd;
537 buffer_init(&sockets[old_alloc].input);
538 buffer_init(&sockets[old_alloc].output);
542 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl)
547 for (i = 0; i < sockets_alloc; i++) {
548 switch (sockets[i].type) {
550 case AUTH_CONNECTION:
551 n = MAX(n, sockets[i].fd);
556 fatal("Unknown socket type %d", sockets[i].type);
561 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
562 if (*fdrp == NULL || n > *fdl) {
571 memset(*fdrp, 0, sz);
572 memset(*fdwp, 0, sz);
574 for (i = 0; i < sockets_alloc; i++) {
575 switch (sockets[i].type) {
577 case AUTH_CONNECTION:
578 FD_SET(sockets[i].fd, *fdrp);
579 if (buffer_len(&sockets[i].output) > 0)
580 FD_SET(sockets[i].fd, *fdwp);
590 after_select(fd_set *readset, fd_set *writeset)
596 struct sockaddr_un sunaddr;
598 for (i = 0; i < sockets_alloc; i++)
599 switch (sockets[i].type) {
603 if (FD_ISSET(sockets[i].fd, readset)) {
604 slen = sizeof(sunaddr);
605 sock = accept(sockets[i].fd,
606 (struct sockaddr *) &sunaddr, &slen);
608 perror("accept from AUTH_SOCKET");
611 new_socket(AUTH_CONNECTION, sock);
614 case AUTH_CONNECTION:
615 if (buffer_len(&sockets[i].output) > 0 &&
616 FD_ISSET(sockets[i].fd, writeset)) {
618 len = write(sockets[i].fd,
619 buffer_ptr(&sockets[i].output),
620 buffer_len(&sockets[i].output));
621 if (len == -1 && (errno == EAGAIN ||
627 shutdown(sockets[i].fd, SHUT_RDWR);
628 close(sockets[i].fd);
629 sockets[i].type = AUTH_UNUSED;
630 buffer_free(&sockets[i].input);
631 buffer_free(&sockets[i].output);
634 buffer_consume(&sockets[i].output, len);
636 if (FD_ISSET(sockets[i].fd, readset)) {
638 len = read(sockets[i].fd, buf, sizeof(buf));
639 if (len == -1 && (errno == EAGAIN ||
645 shutdown(sockets[i].fd, SHUT_RDWR);
646 close(sockets[i].fd);
647 sockets[i].type = AUTH_UNUSED;
648 buffer_free(&sockets[i].input);
649 buffer_free(&sockets[i].output);
652 buffer_append(&sockets[i].input, buf, len);
653 process_message(&sockets[i]);
657 fatal("Unknown type %d", sockets[i].type);
662 check_parent_exists(int sig)
664 int save_errno = errno;
666 if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
667 /* printf("Parent has died - Authentication agent exiting.\n"); */
670 signal(SIGALRM, check_parent_exists);
692 cleanup_handler(int sig)
701 fprintf(stderr, "ssh-agent version %s\n", SSH_VERSION);
702 fprintf(stderr, "Usage: %s [-c | -s] [-k] [command {args...]]\n",
708 main(int ac, char **av)
710 int sock, c_flag = 0, k_flag = 0, s_flag = 0, ch;
711 struct sockaddr_un sunaddr;
712 #ifdef HAVE_SETRLIMIT
719 char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
721 fd_set *readsetp = NULL, *writesetp = NULL;
723 SSLeay_add_all_algorithms();
725 __progname = get_progname(av[0]);
729 #ifdef __GNU_LIBRARY__
730 while ((ch = getopt(ac, av, "+cks")) != -1) {
731 #else /* __GNU_LIBRARY__ */
732 while ((ch = getopt(ac, av, "cks")) != -1) {
733 #endif /* __GNU_LIBRARY__ */
755 if (ac > 0 && (c_flag || k_flag || s_flag))
758 if (ac == 0 && !c_flag && !k_flag && !s_flag) {
759 shell = getenv("SHELL");
760 if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
764 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
765 if (pidstr == NULL) {
766 fprintf(stderr, "%s not set, cannot kill agent\n",
767 SSH_AGENTPID_ENV_NAME);
772 fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
773 SSH_AGENTPID_ENV_NAME, pidstr);
776 if (kill(pid, SIGTERM) == -1) {
780 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
781 printf(format, SSH_AUTHSOCKET_ENV_NAME);
782 printf(format, SSH_AGENTPID_ENV_NAME);
783 printf("echo Agent pid %d killed;\n", pid);
786 parent_pid = getpid();
788 /* Create private directory for agent socket */
789 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
790 if (mkdtemp(socket_dir) == NULL) {
791 perror("mkdtemp: private socket dir");
794 snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
798 * Create socket early so it will exist before command gets run from
801 sock = socket(AF_UNIX, SOCK_STREAM, 0);
806 memset(&sunaddr, 0, sizeof(sunaddr));
807 sunaddr.sun_family = AF_UNIX;
808 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
810 prev_mask = umask(0177);
812 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
822 if (listen(sock, 5) < 0) {
828 * Fork, and have the parent execute the command, if any, or present
829 * the socket data. The child continues as the authentication agent.
836 if (pid != 0) { /* Parent - execute the given command. */
838 snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
840 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
841 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
842 SSH_AUTHSOCKET_ENV_NAME);
843 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
844 SSH_AGENTPID_ENV_NAME);
845 printf("echo Agent pid %d;\n", pid);
848 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
849 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
861 #ifdef HAVE_SETRLIMIT
862 /* deny core dumps, since memory contains unencrypted private keys */
863 rlim.rlim_cur = rlim.rlim_max = 0;
864 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
865 perror("setrlimit rlimit_core failed");
869 if (setsid() == -1) {
873 if (atexit(cleanup_socket) < 0) {
877 new_socket(AUTH_SOCKET, sock);
879 signal(SIGALRM, check_parent_exists);
883 signal(SIGINT, SIG_IGN);
884 signal(SIGPIPE, SIG_IGN);
885 signal(SIGHUP, cleanup_handler);
886 signal(SIGTERM, cleanup_handler);
888 prepare_select(&readsetp, &writesetp, &max_fd);
889 if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
894 after_select(readsetp, writesetp);