1 /* $OpenBSD: ssh-agent.c,v 1.56 2001/06/25 08:25:40 markus 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 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 RCSID("$OpenBSD: ssh-agent.c,v 1.56 2001/06/25 08:25:40 markus Exp $");
41 #include <openssl/evp.h>
42 #include <openssl/md5.h>
62 AUTH_UNUSED, AUTH_SOCKET, AUTH_CONNECTION
68 u_int sockets_alloc = 0;
69 SocketEntry *sockets = NULL;
81 /* private key table, one per protocol version */
86 /* pid of shell == parent of agent */
87 pid_t parent_pid = -1;
89 /* pathname and directory for AUTH_SOCKET */
90 char socket_name[1024];
91 char socket_dir[1024];
93 #ifdef HAVE___PROGNAME
94 extern char *__progname;
103 for (i = 0; i <=2; i++){
104 idtable[i].identities = NULL;
105 idtable[i].nentries = 0;
109 /* return private key table for requested protocol version */
111 idtab_lookup(int version)
113 if (version < 1 || version > 2)
114 fatal("internal error, bad protocol version %d", version);
115 return &idtable[version];
118 /* return matching private key for given public key */
120 lookup_private_key(Key *key, int *idx, int version)
123 Idtab *tab = idtab_lookup(version);
124 for (i = 0; i < tab->nentries; i++) {
125 if (key_equal(key, tab->identities[i].key)) {
128 return tab->identities[i].key;
134 /* send list of supported public keys to 'client' */
136 process_request_identities(SocketEntry *e, int version)
138 Idtab *tab = idtab_lookup(version);
143 buffer_put_char(&msg, (version == 1) ?
144 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
145 buffer_put_int(&msg, tab->nentries);
146 for (i = 0; i < tab->nentries; i++) {
147 Identity *id = &tab->identities[i];
148 if (id->key->type == KEY_RSA1) {
149 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
150 buffer_put_bignum(&msg, id->key->rsa->e);
151 buffer_put_bignum(&msg, id->key->rsa->n);
155 key_to_blob(id->key, &blob, &blen);
156 buffer_put_string(&msg, blob, blen);
159 buffer_put_cstring(&msg, id->comment);
161 buffer_put_int(&e->output, buffer_len(&msg));
162 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
168 process_authentication_challenge1(SocketEntry *e)
175 u_char buf[32], mdbuf[16], session_id[16];
179 key = key_new(KEY_RSA1);
180 challenge = BN_new();
182 buffer_get_int(&e->input); /* ignored */
183 buffer_get_bignum(&e->input, key->rsa->e);
184 buffer_get_bignum(&e->input, key->rsa->n);
185 buffer_get_bignum(&e->input, challenge);
187 /* Only protocol 1.1 is supported */
188 if (buffer_len(&e->input) == 0)
190 buffer_get(&e->input, (char *) session_id, 16);
191 response_type = buffer_get_int(&e->input);
192 if (response_type != 1)
195 private = lookup_private_key(key, NULL, 1);
196 if (private != NULL) {
197 /* Decrypt the challenge using the private key. */
198 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
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 u_char *blob, *data, *signature = NULL;
239 u_int blen, dlen, slen = 0;
246 blob = buffer_get_string(&e->input, &blen);
247 data = buffer_get_string(&e->input, &dlen);
249 flags = buffer_get_int(&e->input);
250 if (flags & SSH_AGENT_OLD_SIGNATURE)
251 datafellows = SSH_BUG_SIGBLOB;
253 key = key_from_blob(blob, blen);
255 private = lookup_private_key(key, NULL, 2);
257 ok = key_sign(private, &signature, &slen, data, dlen);
262 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
263 buffer_put_string(&msg, signature, slen);
265 buffer_put_char(&msg, SSH_AGENT_FAILURE);
267 buffer_put_int(&e->output, buffer_len(&msg));
268 buffer_append(&e->output, buffer_ptr(&msg),
273 if (signature != NULL)
279 process_remove_identity(SocketEntry *e, int version)
281 Key *key = NULL, *private;
289 key = key_new(KEY_RSA1);
290 bits = buffer_get_int(&e->input);
291 buffer_get_bignum(&e->input, key->rsa->e);
292 buffer_get_bignum(&e->input, key->rsa->n);
294 if (bits != key_size(key))
295 log("Warning: identity keysize mismatch: actual %d, announced %d",
296 key_size(key), bits);
299 blob = buffer_get_string(&e->input, &blen);
300 key = key_from_blob(blob, blen);
306 private = lookup_private_key(key, &idx, version);
307 if (private != NULL) {
309 * We have this key. Free the old key. Since we
310 * don\'t want to leave empty slots in the middle of
311 * the array, we actually free the key there and move
312 * all the entries between the empty slot and the end
315 Idtab *tab = idtab_lookup(version);
316 key_free(tab->identities[idx].key);
317 xfree(tab->identities[idx].comment);
318 if (tab->nentries < 1)
319 fatal("process_remove_identity: "
320 "internal error: tab->nentries %d",
322 if (idx != tab->nentries - 1) {
324 for (i = idx; i < tab->nentries - 1; i++)
325 tab->identities[i] = tab->identities[i+1];
327 tab->identities[tab->nentries - 1].key = NULL;
328 tab->identities[tab->nentries - 1].comment = NULL;
334 buffer_put_int(&e->output, 1);
335 buffer_put_char(&e->output,
336 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
340 process_remove_all_identities(SocketEntry *e, int version)
343 Idtab *tab = idtab_lookup(version);
345 /* Loop over all identities and clear the keys. */
346 for (i = 0; i < tab->nentries; i++) {
347 key_free(tab->identities[i].key);
348 xfree(tab->identities[i].comment);
351 /* Mark that there are no identities. */
355 buffer_put_int(&e->output, 1);
356 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
361 process_add_identity(SocketEntry *e, int version)
366 int type, success = 0;
367 Idtab *tab = idtab_lookup(version);
371 k = key_new_private(KEY_RSA1);
372 buffer_get_int(&e->input); /* ignored */
373 buffer_get_bignum(&e->input, k->rsa->n);
374 buffer_get_bignum(&e->input, k->rsa->e);
375 buffer_get_bignum(&e->input, k->rsa->d);
376 buffer_get_bignum(&e->input, k->rsa->iqmp);
378 /* SSH and SSL have p and q swapped */
379 buffer_get_bignum(&e->input, k->rsa->q); /* p */
380 buffer_get_bignum(&e->input, k->rsa->p); /* q */
382 /* Generate additional parameters */
383 generate_additional_parameters(k->rsa);
386 type_name = buffer_get_string(&e->input, NULL);
387 type = key_type_from_name(type_name);
391 k = key_new_private(type);
392 buffer_get_bignum2(&e->input, k->dsa->p);
393 buffer_get_bignum2(&e->input, k->dsa->q);
394 buffer_get_bignum2(&e->input, k->dsa->g);
395 buffer_get_bignum2(&e->input, k->dsa->pub_key);
396 buffer_get_bignum2(&e->input, k->dsa->priv_key);
399 k = key_new_private(type);
400 buffer_get_bignum2(&e->input, k->rsa->n);
401 buffer_get_bignum2(&e->input, k->rsa->e);
402 buffer_get_bignum2(&e->input, k->rsa->d);
403 buffer_get_bignum2(&e->input, k->rsa->iqmp);
404 buffer_get_bignum2(&e->input, k->rsa->p);
405 buffer_get_bignum2(&e->input, k->rsa->q);
407 /* Generate additional parameters */
408 generate_additional_parameters(k->rsa);
411 buffer_clear(&e->input);
416 comment = buffer_get_string(&e->input, NULL);
422 if (lookup_private_key(k, NULL, version) == NULL) {
423 if (tab->nentries == 0)
424 tab->identities = xmalloc(sizeof(Identity));
426 tab->identities = xrealloc(tab->identities,
427 (tab->nentries + 1) * sizeof(Identity));
428 tab->identities[tab->nentries].key = k;
429 tab->identities[tab->nentries].comment = comment;
430 /* Increment the number of identities. */
437 buffer_put_int(&e->output, 1);
438 buffer_put_char(&e->output,
439 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
442 /* dispatch incoming messages */
445 process_message(SocketEntry *e)
450 if (buffer_len(&e->input) < 5)
451 return; /* Incomplete message. */
452 cp = (u_char *) buffer_ptr(&e->input);
453 msg_len = GET_32BIT(cp);
454 if (msg_len > 256 * 1024) {
455 shutdown(e->fd, SHUT_RDWR);
457 e->type = AUTH_UNUSED;
460 if (buffer_len(&e->input) < msg_len + 4)
462 buffer_consume(&e->input, 4);
463 type = buffer_get_char(&e->input);
467 case SSH_AGENTC_RSA_CHALLENGE:
468 process_authentication_challenge1(e);
470 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
471 process_request_identities(e, 1);
473 case SSH_AGENTC_ADD_RSA_IDENTITY:
474 process_add_identity(e, 1);
476 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
477 process_remove_identity(e, 1);
479 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
480 process_remove_all_identities(e, 1);
483 case SSH2_AGENTC_SIGN_REQUEST:
484 process_sign_request2(e);
486 case SSH2_AGENTC_REQUEST_IDENTITIES:
487 process_request_identities(e, 2);
489 case SSH2_AGENTC_ADD_IDENTITY:
490 process_add_identity(e, 2);
492 case SSH2_AGENTC_REMOVE_IDENTITY:
493 process_remove_identity(e, 2);
495 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
496 process_remove_all_identities(e, 2);
499 /* Unknown message. Respond with failure. */
500 error("Unknown message %d", type);
501 buffer_clear(&e->input);
502 buffer_put_int(&e->output, 1);
503 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
509 new_socket(int type, int fd)
512 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
513 error("fcntl O_NONBLOCK: %s", strerror(errno));
518 for (i = 0; i < sockets_alloc; i++)
519 if (sockets[i].type == AUTH_UNUSED) {
521 sockets[i].type = type;
522 buffer_init(&sockets[i].input);
523 buffer_init(&sockets[i].output);
526 old_alloc = sockets_alloc;
529 sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
531 sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
532 for (i = old_alloc; i < sockets_alloc; i++)
533 sockets[i].type = AUTH_UNUSED;
534 sockets[old_alloc].type = type;
535 sockets[old_alloc].fd = fd;
536 buffer_init(&sockets[old_alloc].input);
537 buffer_init(&sockets[old_alloc].output);
541 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl)
546 for (i = 0; i < sockets_alloc; i++) {
547 switch (sockets[i].type) {
549 case AUTH_CONNECTION:
550 n = MAX(n, sockets[i].fd);
555 fatal("Unknown socket type %d", sockets[i].type);
560 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
561 if (*fdrp == NULL || n > *fdl) {
570 memset(*fdrp, 0, sz);
571 memset(*fdwp, 0, sz);
573 for (i = 0; i < sockets_alloc; i++) {
574 switch (sockets[i].type) {
576 case AUTH_CONNECTION:
577 FD_SET(sockets[i].fd, *fdrp);
578 if (buffer_len(&sockets[i].output) > 0)
579 FD_SET(sockets[i].fd, *fdwp);
589 after_select(fd_set *readset, fd_set *writeset)
595 struct sockaddr_un sunaddr;
597 for (i = 0; i < sockets_alloc; i++)
598 switch (sockets[i].type) {
602 if (FD_ISSET(sockets[i].fd, readset)) {
603 slen = sizeof(sunaddr);
604 sock = accept(sockets[i].fd,
605 (struct sockaddr *) &sunaddr, &slen);
607 perror("accept from AUTH_SOCKET");
610 new_socket(AUTH_CONNECTION, sock);
613 case AUTH_CONNECTION:
614 if (buffer_len(&sockets[i].output) > 0 &&
615 FD_ISSET(sockets[i].fd, writeset)) {
617 len = write(sockets[i].fd,
618 buffer_ptr(&sockets[i].output),
619 buffer_len(&sockets[i].output));
620 if (len == -1 && (errno == EAGAIN ||
626 shutdown(sockets[i].fd, SHUT_RDWR);
627 close(sockets[i].fd);
628 sockets[i].type = AUTH_UNUSED;
629 buffer_free(&sockets[i].input);
630 buffer_free(&sockets[i].output);
633 buffer_consume(&sockets[i].output, len);
635 if (FD_ISSET(sockets[i].fd, readset)) {
637 len = read(sockets[i].fd, buf, sizeof(buf));
638 if (len == -1 && (errno == EAGAIN ||
644 shutdown(sockets[i].fd, SHUT_RDWR);
645 close(sockets[i].fd);
646 sockets[i].type = AUTH_UNUSED;
647 buffer_free(&sockets[i].input);
648 buffer_free(&sockets[i].output);
651 buffer_append(&sockets[i].input, buf, len);
652 process_message(&sockets[i]);
656 fatal("Unknown type %d", sockets[i].type);
661 check_parent_exists(int sig)
663 int save_errno = errno;
665 if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
666 /* printf("Parent has died - Authentication agent exiting.\n"); */
669 signal(SIGALRM, check_parent_exists);
691 cleanup_handler(int sig)
700 fprintf(stderr, "ssh-agent version %s\n", SSH_VERSION);
701 fprintf(stderr, "Usage: %s [-c | -s] [-k] [command {args...]]\n",
707 main(int ac, char **av)
709 int sock, c_flag = 0, k_flag = 0, s_flag = 0, ch;
710 struct sockaddr_un sunaddr;
711 #ifdef HAVE_SETRLIMIT
718 char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
720 fd_set *readsetp = NULL, *writesetp = NULL;
722 SSLeay_add_all_algorithms();
724 __progname = get_progname(av[0]);
728 #ifdef __GNU_LIBRARY__
729 while ((ch = getopt(ac, av, "+cks")) != -1) {
730 #else /* __GNU_LIBRARY__ */
731 while ((ch = getopt(ac, av, "cks")) != -1) {
732 #endif /* __GNU_LIBRARY__ */
754 if (ac > 0 && (c_flag || k_flag || s_flag))
757 if (ac == 0 && !c_flag && !k_flag && !s_flag) {
758 shell = getenv("SHELL");
759 if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
763 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
764 if (pidstr == NULL) {
765 fprintf(stderr, "%s not set, cannot kill agent\n",
766 SSH_AGENTPID_ENV_NAME);
771 fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
772 SSH_AGENTPID_ENV_NAME, pidstr);
775 if (kill(pid, SIGTERM) == -1) {
779 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
780 printf(format, SSH_AUTHSOCKET_ENV_NAME);
781 printf(format, SSH_AGENTPID_ENV_NAME);
782 printf("echo Agent pid %d killed;\n", pid);
785 parent_pid = getpid();
787 /* Create private directory for agent socket */
788 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
789 if (mkdtemp(socket_dir) == NULL) {
790 perror("mkdtemp: private socket dir");
793 snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
797 * Create socket early so it will exist before command gets run from
800 sock = socket(AF_UNIX, SOCK_STREAM, 0);
805 memset(&sunaddr, 0, sizeof(sunaddr));
806 sunaddr.sun_family = AF_UNIX;
807 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
809 prev_mask = umask(0177);
811 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
821 if (listen(sock, 5) < 0) {
827 * Fork, and have the parent execute the command, if any, or present
828 * the socket data. The child continues as the authentication agent.
835 if (pid != 0) { /* Parent - execute the given command. */
837 snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
839 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
840 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
841 SSH_AUTHSOCKET_ENV_NAME);
842 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
843 SSH_AGENTPID_ENV_NAME);
844 printf("echo Agent pid %d;\n", pid);
847 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
848 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
860 #ifdef HAVE_SETRLIMIT
861 /* deny core dumps, since memory contains unencrypted private keys */
862 rlim.rlim_cur = rlim.rlim_max = 0;
863 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
864 perror("setrlimit rlimit_core failed");
868 if (setsid() == -1) {
872 if (atexit(cleanup_socket) < 0) {
876 new_socket(AUTH_SOCKET, sock);
878 signal(SIGALRM, check_parent_exists);
882 signal(SIGINT, SIG_IGN);
883 signal(SIGPIPE, SIG_IGN);
884 signal(SIGHUP, cleanup_handler);
885 signal(SIGTERM, cleanup_handler);
887 prepare_select(&readsetp, &writesetp, &max_fd);
888 if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
893 after_select(readsetp, writesetp);