1 /* $OpenBSD: ssh-agent.c,v 1.48 2001/01/25 08:06:33 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.48 2001/01/25 08:06:33 deraadt 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;
100 int prepare_select(fd_set **, fd_set **, int *);
106 for (i = 0; i <=2; i++){
107 idtable[i].identities = NULL;
108 idtable[i].nentries = 0;
112 /* return private key table for requested protocol version */
114 idtab_lookup(int version)
116 if (version < 1 || version > 2)
117 fatal("internal error, bad protocol version %d", version);
118 return &idtable[version];
121 /* return matching private key for given public key */
123 lookup_private_key(Key *key, int *idx, int version)
126 Idtab *tab = idtab_lookup(version);
127 for (i = 0; i < tab->nentries; i++) {
128 if (key_equal(key, tab->identities[i].key)) {
131 return tab->identities[i].key;
137 /* send list of supported public keys to 'client' */
139 process_request_identities(SocketEntry *e, int version)
141 Idtab *tab = idtab_lookup(version);
146 buffer_put_char(&msg, (version == 1) ?
147 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
148 buffer_put_int(&msg, tab->nentries);
149 for (i = 0; i < tab->nentries; i++) {
150 Identity *id = &tab->identities[i];
151 if (id->key->type == KEY_RSA1) {
152 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
153 buffer_put_bignum(&msg, id->key->rsa->e);
154 buffer_put_bignum(&msg, id->key->rsa->n);
158 key_to_blob(id->key, &blob, &blen);
159 buffer_put_string(&msg, blob, blen);
162 buffer_put_cstring(&msg, id->comment);
164 buffer_put_int(&e->output, buffer_len(&msg));
165 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
171 process_authentication_challenge1(SocketEntry *e)
178 u_char buf[32], mdbuf[16], session_id[16];
182 key = key_new(KEY_RSA1);
183 challenge = BN_new();
185 buffer_get_int(&e->input); /* ignored */
186 buffer_get_bignum(&e->input, key->rsa->e);
187 buffer_get_bignum(&e->input, key->rsa->n);
188 buffer_get_bignum(&e->input, challenge);
190 /* Only protocol 1.1 is supported */
191 if (buffer_len(&e->input) == 0)
193 buffer_get(&e->input, (char *) session_id, 16);
194 response_type = buffer_get_int(&e->input);
195 if (response_type != 1)
198 private = lookup_private_key(key, NULL, 1);
199 if (private != NULL) {
200 /* Decrypt the challenge using the private key. */
201 rsa_private_decrypt(challenge, challenge, private->rsa);
203 /* The response is MD5 of decrypted challenge plus session id. */
204 len = BN_num_bytes(challenge);
205 if (len <= 0 || len > 32) {
206 log("process_authentication_challenge: bad challenge length %d", len);
210 BN_bn2bin(challenge, buf + 32 - len);
212 MD5_Update(&md, buf, 32);
213 MD5_Update(&md, session_id, 16);
214 MD5_Final(mdbuf, &md);
216 /* Send the response. */
217 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
218 for (i = 0; i < 16; i++)
219 buffer_put_char(&msg, mdbuf[i]);
224 /* Unknown identity or protocol error. Send failure. */
225 buffer_put_char(&msg, SSH_AGENT_FAILURE);
227 buffer_put_int(&e->output, buffer_len(&msg));
228 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
230 BN_clear_free(challenge);
236 process_sign_request2(SocketEntry *e)
238 extern int datafellows;
240 u_char *blob, *data, *signature = NULL;
241 u_int blen, dlen, slen = 0;
248 blob = buffer_get_string(&e->input, &blen);
249 data = buffer_get_string(&e->input, &dlen);
251 flags = buffer_get_int(&e->input);
252 if (flags & SSH_AGENT_OLD_SIGNATURE)
253 datafellows = SSH_BUG_SIGBLOB;
255 key = key_from_blob(blob, blen);
257 private = lookup_private_key(key, NULL, 2);
259 ok = key_sign(private, &signature, &slen, data, dlen);
264 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
265 buffer_put_string(&msg, signature, slen);
267 buffer_put_char(&msg, SSH_AGENT_FAILURE);
269 buffer_put_int(&e->output, buffer_len(&msg));
270 buffer_append(&e->output, buffer_ptr(&msg),
275 if (signature != NULL)
281 process_remove_identity(SocketEntry *e, int version)
283 Key *key = NULL, *private;
291 key = key_new(KEY_RSA1);
292 bits = buffer_get_int(&e->input);
293 buffer_get_bignum(&e->input, key->rsa->e);
294 buffer_get_bignum(&e->input, key->rsa->n);
296 if (bits != key_size(key))
297 log("Warning: identity keysize mismatch: actual %d, announced %d",
298 key_size(key), bits);
301 blob = buffer_get_string(&e->input, &blen);
302 key = key_from_blob(blob, blen);
308 private = lookup_private_key(key, &idx, version);
309 if (private != NULL) {
311 * We have this key. Free the old key. Since we
312 * don\'t want to leave empty slots in the middle of
313 * the array, we actually free the key there and move
314 * all the entries between the empty slot and the end
317 Idtab *tab = idtab_lookup(version);
318 key_free(tab->identities[idx].key);
319 xfree(tab->identities[idx].comment);
320 if (tab->nentries < 1)
321 fatal("process_remove_identity: "
322 "internal error: tab->nentries %d",
324 if (idx != tab->nentries - 1) {
326 for (i = idx; i < tab->nentries - 1; i++)
327 tab->identities[i] = tab->identities[i+1];
329 tab->identities[tab->nentries - 1].key = NULL;
330 tab->identities[tab->nentries - 1].comment = NULL;
336 buffer_put_int(&e->output, 1);
337 buffer_put_char(&e->output,
338 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
342 process_remove_all_identities(SocketEntry *e, int version)
345 Idtab *tab = idtab_lookup(version);
347 /* Loop over all identities and clear the keys. */
348 for (i = 0; i < tab->nentries; i++) {
349 key_free(tab->identities[i].key);
350 xfree(tab->identities[i].comment);
353 /* Mark that there are no identities. */
357 buffer_put_int(&e->output, 1);
358 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
363 generate_additional_parameters(RSA *rsa)
367 /* Generate additional parameters */
371 BN_sub(aux, rsa->q, BN_value_one());
372 BN_mod(rsa->dmq1, rsa->d, aux, ctx);
374 BN_sub(aux, rsa->p, BN_value_one());
375 BN_mod(rsa->dmp1, rsa->d, aux, ctx);
382 process_add_identity(SocketEntry *e, int version)
387 int type, success = 0;
388 Idtab *tab = idtab_lookup(version);
392 k = key_new_private(KEY_RSA1);
393 buffer_get_int(&e->input); /* ignored */
394 buffer_get_bignum(&e->input, k->rsa->n);
395 buffer_get_bignum(&e->input, k->rsa->e);
396 buffer_get_bignum(&e->input, k->rsa->d);
397 buffer_get_bignum(&e->input, k->rsa->iqmp);
399 /* SSH and SSL have p and q swapped */
400 buffer_get_bignum(&e->input, k->rsa->q); /* p */
401 buffer_get_bignum(&e->input, k->rsa->p); /* q */
403 /* Generate additional parameters */
404 generate_additional_parameters(k->rsa);
407 type_name = buffer_get_string(&e->input, NULL);
408 type = key_type_from_name(type_name);
412 k = key_new_private(type);
413 buffer_get_bignum2(&e->input, k->dsa->p);
414 buffer_get_bignum2(&e->input, k->dsa->q);
415 buffer_get_bignum2(&e->input, k->dsa->g);
416 buffer_get_bignum2(&e->input, k->dsa->pub_key);
417 buffer_get_bignum2(&e->input, k->dsa->priv_key);
420 k = key_new_private(type);
421 buffer_get_bignum2(&e->input, k->rsa->n);
422 buffer_get_bignum2(&e->input, k->rsa->e);
423 buffer_get_bignum2(&e->input, k->rsa->d);
424 buffer_get_bignum2(&e->input, k->rsa->iqmp);
425 buffer_get_bignum2(&e->input, k->rsa->p);
426 buffer_get_bignum2(&e->input, k->rsa->q);
428 /* Generate additional parameters */
429 generate_additional_parameters(k->rsa);
432 buffer_clear(&e->input);
437 comment = buffer_get_string(&e->input, NULL);
443 if (lookup_private_key(k, NULL, version) == NULL) {
444 if (tab->nentries == 0)
445 tab->identities = xmalloc(sizeof(Identity));
447 tab->identities = xrealloc(tab->identities,
448 (tab->nentries + 1) * sizeof(Identity));
449 tab->identities[tab->nentries].key = k;
450 tab->identities[tab->nentries].comment = comment;
451 /* Increment the number of identities. */
458 buffer_put_int(&e->output, 1);
459 buffer_put_char(&e->output,
460 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
463 /* dispatch incoming messages */
466 process_message(SocketEntry *e)
471 if (buffer_len(&e->input) < 5)
472 return; /* Incomplete message. */
473 cp = (u_char *) buffer_ptr(&e->input);
474 msg_len = GET_32BIT(cp);
475 if (msg_len > 256 * 1024) {
476 shutdown(e->fd, SHUT_RDWR);
478 e->type = AUTH_UNUSED;
481 if (buffer_len(&e->input) < msg_len + 4)
483 buffer_consume(&e->input, 4);
484 type = buffer_get_char(&e->input);
488 case SSH_AGENTC_RSA_CHALLENGE:
489 process_authentication_challenge1(e);
491 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
492 process_request_identities(e, 1);
494 case SSH_AGENTC_ADD_RSA_IDENTITY:
495 process_add_identity(e, 1);
497 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
498 process_remove_identity(e, 1);
500 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
501 process_remove_all_identities(e, 1);
504 case SSH2_AGENTC_SIGN_REQUEST:
505 process_sign_request2(e);
507 case SSH2_AGENTC_REQUEST_IDENTITIES:
508 process_request_identities(e, 2);
510 case SSH2_AGENTC_ADD_IDENTITY:
511 process_add_identity(e, 2);
513 case SSH2_AGENTC_REMOVE_IDENTITY:
514 process_remove_identity(e, 2);
516 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
517 process_remove_all_identities(e, 2);
520 /* Unknown message. Respond with failure. */
521 error("Unknown message %d", type);
522 buffer_clear(&e->input);
523 buffer_put_int(&e->output, 1);
524 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
530 new_socket(int type, int fd)
533 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
534 error("fcntl O_NONBLOCK: %s", strerror(errno));
539 for (i = 0; i < sockets_alloc; i++)
540 if (sockets[i].type == AUTH_UNUSED) {
542 sockets[i].type = type;
543 buffer_init(&sockets[i].input);
544 buffer_init(&sockets[i].output);
547 old_alloc = sockets_alloc;
550 sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
552 sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
553 for (i = old_alloc; i < sockets_alloc; i++)
554 sockets[i].type = AUTH_UNUSED;
555 sockets[old_alloc].type = type;
556 sockets[old_alloc].fd = fd;
557 buffer_init(&sockets[old_alloc].input);
558 buffer_init(&sockets[old_alloc].output);
562 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl)
567 for (i = 0; i < sockets_alloc; i++) {
568 switch (sockets[i].type) {
570 case AUTH_CONNECTION:
571 n = MAX(n, sockets[i].fd);
576 fatal("Unknown socket type %d", sockets[i].type);
581 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
582 if (*fdrp == NULL || n > *fdl) {
591 memset(*fdrp, 0, sz);
592 memset(*fdwp, 0, sz);
594 for (i = 0; i < sockets_alloc; i++) {
595 switch (sockets[i].type) {
597 case AUTH_CONNECTION:
598 FD_SET(sockets[i].fd, *fdrp);
599 if (buffer_len(&sockets[i].output) > 0)
600 FD_SET(sockets[i].fd, *fdwp);
610 after_select(fd_set *readset, fd_set *writeset)
616 struct sockaddr_un sunaddr;
618 for (i = 0; i < sockets_alloc; i++)
619 switch (sockets[i].type) {
623 if (FD_ISSET(sockets[i].fd, readset)) {
624 slen = sizeof(sunaddr);
625 sock = accept(sockets[i].fd,
626 (struct sockaddr *) &sunaddr, &slen);
628 perror("accept from AUTH_SOCKET");
631 new_socket(AUTH_CONNECTION, sock);
634 case AUTH_CONNECTION:
635 if (buffer_len(&sockets[i].output) > 0 &&
636 FD_ISSET(sockets[i].fd, writeset)) {
637 len = write(sockets[i].fd,
638 buffer_ptr(&sockets[i].output),
639 buffer_len(&sockets[i].output));
641 shutdown(sockets[i].fd, SHUT_RDWR);
642 close(sockets[i].fd);
643 sockets[i].type = AUTH_UNUSED;
644 buffer_free(&sockets[i].input);
645 buffer_free(&sockets[i].output);
648 buffer_consume(&sockets[i].output, len);
650 if (FD_ISSET(sockets[i].fd, readset)) {
651 len = read(sockets[i].fd, buf, sizeof(buf));
653 shutdown(sockets[i].fd, SHUT_RDWR);
654 close(sockets[i].fd);
655 sockets[i].type = AUTH_UNUSED;
656 buffer_free(&sockets[i].input);
657 buffer_free(&sockets[i].output);
660 buffer_append(&sockets[i].input, buf, len);
661 process_message(&sockets[i]);
665 fatal("Unknown type %d", sockets[i].type);
670 check_parent_exists(int sig)
672 int save_errno = errno;
674 if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
675 /* printf("Parent has died - Authentication agent exiting.\n"); */
678 signal(SIGALRM, check_parent_exists);
700 cleanup_handler(int sig)
709 fprintf(stderr, "ssh-agent version %s\n", SSH_VERSION);
710 fprintf(stderr, "Usage: %s [-c | -s] [-k] [command {args...]]\n",
716 main(int ac, char **av)
718 int sock, c_flag = 0, k_flag = 0, s_flag = 0, ch;
719 struct sockaddr_un sunaddr;
720 #ifdef HAVE_SETRLIMIT
724 char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
726 fd_set *readsetp = NULL, *writesetp = NULL;
728 __progname = get_progname(av[0]);
731 #ifdef __GNU_LIBRARY__
732 while ((ch = getopt(ac, av, "+cks")) != -1) {
733 #else /* __GNU_LIBRARY__ */
734 while ((ch = getopt(ac, av, "cks")) != -1) {
735 #endif /* __GNU_LIBRARY__ */
757 if (ac > 0 && (c_flag || k_flag || s_flag))
760 if (ac == 0 && !c_flag && !k_flag && !s_flag) {
761 shell = getenv("SHELL");
762 if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
766 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
767 if (pidstr == NULL) {
768 fprintf(stderr, "%s not set, cannot kill agent\n",
769 SSH_AGENTPID_ENV_NAME);
774 fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
775 SSH_AGENTPID_ENV_NAME, pidstr);
778 if (kill(pid, SIGTERM) == -1) {
782 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
783 printf(format, SSH_AUTHSOCKET_ENV_NAME);
784 printf(format, SSH_AGENTPID_ENV_NAME);
785 printf("echo Agent pid %d killed;\n", pid);
788 parent_pid = getpid();
790 /* Create private directory for agent socket */
791 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
792 if (mkdtemp(socket_dir) == NULL) {
793 perror("mkdtemp: private socket dir");
796 snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
800 * Create socket early so it will exist before command gets run from
803 sock = socket(AF_UNIX, SOCK_STREAM, 0);
808 memset(&sunaddr, 0, sizeof(sunaddr));
809 sunaddr.sun_family = AF_UNIX;
810 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
811 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
815 if (listen(sock, 5) < 0) {
821 * Fork, and have the parent execute the command, if any, or present
822 * the socket data. The child continues as the authentication agent.
829 if (pid != 0) { /* Parent - execute the given command. */
831 snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
833 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
834 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
835 SSH_AUTHSOCKET_ENV_NAME);
836 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
837 SSH_AGENTPID_ENV_NAME);
838 printf("echo Agent pid %d;\n", pid);
841 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
842 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
854 #ifdef HAVE_SETRLIMIT
855 /* deny core dumps, since memory contains unencrypted private keys */
856 rlim.rlim_cur = rlim.rlim_max = 0;
857 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
858 perror("setrlimit rlimit_core failed");
862 if (setsid() == -1) {
866 if (atexit(cleanup_socket) < 0) {
870 new_socket(AUTH_SOCKET, sock);
872 signal(SIGALRM, check_parent_exists);
876 signal(SIGINT, SIG_IGN);
877 signal(SIGPIPE, SIG_IGN);
878 signal(SIGHUP, cleanup_handler);
879 signal(SIGTERM, cleanup_handler);
881 prepare_select(&readsetp, &writesetp, &max_fd);
882 if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
887 after_select(readsetp, writesetp);