1 /* $OpenBSD: ssh-agent.c,v 1.145 2006/07/22 19:08:54 stevesk Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * The authentication agent program.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
14 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 #include <sys/types.h>
41 #include <sys/socket.h>
45 #include "openbsd-compat/sys-queue.h"
46 #include <sys/resource.h>
57 #include <openssl/evp.h>
58 #include <openssl/md5.h>
75 #if defined(HAVE_SYS_PRCTL_H)
76 #include <sys/prctl.h> /* For prctl() and PR_SET_DUMPABLE */
93 u_int sockets_alloc = 0;
94 SocketEntry *sockets = NULL;
96 typedef struct identity {
97 TAILQ_ENTRY(identity) next;
106 TAILQ_HEAD(idqueue, identity) idlist;
109 /* private key table, one per protocol version */
114 /* pid of shell == parent of agent */
115 pid_t parent_pid = -1;
117 /* pathname and directory for AUTH_SOCKET */
118 char socket_name[MAXPATHLEN];
119 char socket_dir[MAXPATHLEN];
123 char *lock_passwd = NULL;
125 extern char *__progname;
127 /* Default lifetime (0 == forever) */
128 static int lifetime = 0;
131 close_socket(SocketEntry *e)
135 e->type = AUTH_UNUSED;
136 buffer_free(&e->input);
137 buffer_free(&e->output);
138 buffer_free(&e->request);
146 for (i = 0; i <=2; i++) {
147 TAILQ_INIT(&idtable[i].idlist);
148 idtable[i].nentries = 0;
152 /* return private key table for requested protocol version */
154 idtab_lookup(int version)
156 if (version < 1 || version > 2)
157 fatal("internal error, bad protocol version %d", version);
158 return &idtable[version];
162 free_identity(Identity *id)
169 /* return matching private key for given public key */
171 lookup_identity(Key *key, int version)
175 Idtab *tab = idtab_lookup(version);
176 TAILQ_FOREACH(id, &tab->idlist, next) {
177 if (key_equal(key, id->key))
183 /* Check confirmation of keysign request */
185 confirm_key(Identity *id)
190 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
191 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
199 /* send list of supported public keys to 'client' */
201 process_request_identities(SocketEntry *e, int version)
203 Idtab *tab = idtab_lookup(version);
208 buffer_put_char(&msg, (version == 1) ?
209 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
210 buffer_put_int(&msg, tab->nentries);
211 TAILQ_FOREACH(id, &tab->idlist, next) {
212 if (id->key->type == KEY_RSA1) {
213 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
214 buffer_put_bignum(&msg, id->key->rsa->e);
215 buffer_put_bignum(&msg, id->key->rsa->n);
219 key_to_blob(id->key, &blob, &blen);
220 buffer_put_string(&msg, blob, blen);
223 buffer_put_cstring(&msg, id->comment);
225 buffer_put_int(&e->output, buffer_len(&msg));
226 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
232 process_authentication_challenge1(SocketEntry *e)
234 u_char buf[32], mdbuf[16], session_id[16];
244 key = key_new(KEY_RSA1);
245 if ((challenge = BN_new()) == NULL)
246 fatal("process_authentication_challenge1: BN_new failed");
248 (void) buffer_get_int(&e->request); /* ignored */
249 buffer_get_bignum(&e->request, key->rsa->e);
250 buffer_get_bignum(&e->request, key->rsa->n);
251 buffer_get_bignum(&e->request, challenge);
253 /* Only protocol 1.1 is supported */
254 if (buffer_len(&e->request) == 0)
256 buffer_get(&e->request, session_id, 16);
257 response_type = buffer_get_int(&e->request);
258 if (response_type != 1)
261 id = lookup_identity(key, 1);
262 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
263 Key *private = id->key;
264 /* Decrypt the challenge using the private key. */
265 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
268 /* The response is MD5 of decrypted challenge plus session id. */
269 len = BN_num_bytes(challenge);
270 if (len <= 0 || len > 32) {
271 logit("process_authentication_challenge: bad challenge length %d", len);
275 BN_bn2bin(challenge, buf + 32 - len);
277 MD5_Update(&md, buf, 32);
278 MD5_Update(&md, session_id, 16);
279 MD5_Final(mdbuf, &md);
281 /* Send the response. */
282 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
283 for (i = 0; i < 16; i++)
284 buffer_put_char(&msg, mdbuf[i]);
289 /* Unknown identity or protocol error. Send failure. */
290 buffer_put_char(&msg, SSH_AGENT_FAILURE);
292 buffer_put_int(&e->output, buffer_len(&msg));
293 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
295 BN_clear_free(challenge);
301 process_sign_request2(SocketEntry *e)
303 u_char *blob, *data, *signature = NULL;
304 u_int blen, dlen, slen = 0;
305 extern int datafellows;
312 blob = buffer_get_string(&e->request, &blen);
313 data = buffer_get_string(&e->request, &dlen);
315 flags = buffer_get_int(&e->request);
316 if (flags & SSH_AGENT_OLD_SIGNATURE)
317 datafellows = SSH_BUG_SIGBLOB;
319 key = key_from_blob(blob, blen);
321 Identity *id = lookup_identity(key, 2);
322 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
323 ok = key_sign(id->key, &signature, &slen, data, dlen);
328 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
329 buffer_put_string(&msg, signature, slen);
331 buffer_put_char(&msg, SSH_AGENT_FAILURE);
333 buffer_put_int(&e->output, buffer_len(&msg));
334 buffer_append(&e->output, buffer_ptr(&msg),
339 if (signature != NULL)
345 process_remove_identity(SocketEntry *e, int version)
354 key = key_new(KEY_RSA1);
355 bits = buffer_get_int(&e->request);
356 buffer_get_bignum(&e->request, key->rsa->e);
357 buffer_get_bignum(&e->request, key->rsa->n);
359 if (bits != key_size(key))
360 logit("Warning: identity keysize mismatch: actual %u, announced %u",
361 key_size(key), bits);
364 blob = buffer_get_string(&e->request, &blen);
365 key = key_from_blob(blob, blen);
370 Identity *id = lookup_identity(key, version);
373 * We have this key. Free the old key. Since we
374 * don't want to leave empty slots in the middle of
375 * the array, we actually free the key there and move
376 * all the entries between the empty slot and the end
379 Idtab *tab = idtab_lookup(version);
380 if (tab->nentries < 1)
381 fatal("process_remove_identity: "
382 "internal error: tab->nentries %d",
384 TAILQ_REMOVE(&tab->idlist, id, next);
391 buffer_put_int(&e->output, 1);
392 buffer_put_char(&e->output,
393 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
397 process_remove_all_identities(SocketEntry *e, int version)
399 Idtab *tab = idtab_lookup(version);
402 /* Loop over all identities and clear the keys. */
403 for (id = TAILQ_FIRST(&tab->idlist); id;
404 id = TAILQ_FIRST(&tab->idlist)) {
405 TAILQ_REMOVE(&tab->idlist, id, next);
409 /* Mark that there are no identities. */
413 buffer_put_int(&e->output, 1);
414 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
420 u_int now = time(NULL);
425 for (version = 1; version < 3; version++) {
426 tab = idtab_lookup(version);
427 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
428 nxt = TAILQ_NEXT(id, next);
429 if (id->death != 0 && now >= id->death) {
430 TAILQ_REMOVE(&tab->idlist, id, next);
439 process_add_identity(SocketEntry *e, int version)
441 Idtab *tab = idtab_lookup(version);
442 int type, success = 0, death = 0, confirm = 0;
443 char *type_name, *comment;
448 k = key_new_private(KEY_RSA1);
449 (void) buffer_get_int(&e->request); /* ignored */
450 buffer_get_bignum(&e->request, k->rsa->n);
451 buffer_get_bignum(&e->request, k->rsa->e);
452 buffer_get_bignum(&e->request, k->rsa->d);
453 buffer_get_bignum(&e->request, k->rsa->iqmp);
455 /* SSH and SSL have p and q swapped */
456 buffer_get_bignum(&e->request, k->rsa->q); /* p */
457 buffer_get_bignum(&e->request, k->rsa->p); /* q */
459 /* Generate additional parameters */
460 rsa_generate_additional_parameters(k->rsa);
463 type_name = buffer_get_string(&e->request, NULL);
464 type = key_type_from_name(type_name);
468 k = key_new_private(type);
469 buffer_get_bignum2(&e->request, k->dsa->p);
470 buffer_get_bignum2(&e->request, k->dsa->q);
471 buffer_get_bignum2(&e->request, k->dsa->g);
472 buffer_get_bignum2(&e->request, k->dsa->pub_key);
473 buffer_get_bignum2(&e->request, k->dsa->priv_key);
476 k = key_new_private(type);
477 buffer_get_bignum2(&e->request, k->rsa->n);
478 buffer_get_bignum2(&e->request, k->rsa->e);
479 buffer_get_bignum2(&e->request, k->rsa->d);
480 buffer_get_bignum2(&e->request, k->rsa->iqmp);
481 buffer_get_bignum2(&e->request, k->rsa->p);
482 buffer_get_bignum2(&e->request, k->rsa->q);
484 /* Generate additional parameters */
485 rsa_generate_additional_parameters(k->rsa);
488 buffer_clear(&e->request);
493 /* enable blinding */
497 if (RSA_blinding_on(k->rsa, NULL) != 1) {
498 error("process_add_identity: RSA_blinding_on failed");
504 comment = buffer_get_string(&e->request, NULL);
510 while (buffer_len(&e->request)) {
511 switch (buffer_get_char(&e->request)) {
512 case SSH_AGENT_CONSTRAIN_LIFETIME:
513 death = time(NULL) + buffer_get_int(&e->request);
515 case SSH_AGENT_CONSTRAIN_CONFIRM:
522 if (lifetime && !death)
523 death = time(NULL) + lifetime;
524 if (lookup_identity(k, version) == NULL) {
525 Identity *id = xmalloc(sizeof(Identity));
527 id->comment = comment;
529 id->confirm = confirm;
530 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
531 /* Increment the number of identities. */
538 buffer_put_int(&e->output, 1);
539 buffer_put_char(&e->output,
540 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
543 /* XXX todo: encrypt sensitive data with passphrase */
545 process_lock_agent(SocketEntry *e, int lock)
550 passwd = buffer_get_string(&e->request, NULL);
551 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
553 memset(lock_passwd, 0, strlen(lock_passwd));
557 } else if (!locked && lock) {
559 lock_passwd = xstrdup(passwd);
562 memset(passwd, 0, strlen(passwd));
565 buffer_put_int(&e->output, 1);
566 buffer_put_char(&e->output,
567 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
571 no_identities(SocketEntry *e, u_int type)
576 buffer_put_char(&msg,
577 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
578 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
579 buffer_put_int(&msg, 0);
580 buffer_put_int(&e->output, buffer_len(&msg));
581 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
587 process_add_smartcard_key (SocketEntry *e)
589 char *sc_reader_id = NULL, *pin;
590 int i, version, success = 0, death = 0, confirm = 0;
595 sc_reader_id = buffer_get_string(&e->request, NULL);
596 pin = buffer_get_string(&e->request, NULL);
598 while (buffer_len(&e->request)) {
599 switch (buffer_get_char(&e->request)) {
600 case SSH_AGENT_CONSTRAIN_LIFETIME:
601 death = time(NULL) + buffer_get_int(&e->request);
603 case SSH_AGENT_CONSTRAIN_CONFIRM:
610 if (lifetime && !death)
611 death = time(NULL) + lifetime;
613 keys = sc_get_keys(sc_reader_id, pin);
617 if (keys == NULL || keys[0] == NULL) {
618 error("sc_get_keys failed");
621 for (i = 0; keys[i] != NULL; i++) {
623 version = k->type == KEY_RSA1 ? 1 : 2;
624 tab = idtab_lookup(version);
625 if (lookup_identity(k, version) == NULL) {
626 id = xmalloc(sizeof(Identity));
628 id->comment = sc_get_key_label(k);
630 id->confirm = confirm;
631 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
641 buffer_put_int(&e->output, 1);
642 buffer_put_char(&e->output,
643 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
647 process_remove_smartcard_key(SocketEntry *e)
649 char *sc_reader_id = NULL, *pin;
650 int i, version, success = 0;
651 Key **keys, *k = NULL;
655 sc_reader_id = buffer_get_string(&e->request, NULL);
656 pin = buffer_get_string(&e->request, NULL);
657 keys = sc_get_keys(sc_reader_id, pin);
661 if (keys == NULL || keys[0] == NULL) {
662 error("sc_get_keys failed");
665 for (i = 0; keys[i] != NULL; i++) {
667 version = k->type == KEY_RSA1 ? 1 : 2;
668 if ((id = lookup_identity(k, version)) != NULL) {
669 tab = idtab_lookup(version);
670 TAILQ_REMOVE(&tab->idlist, id, next);
680 buffer_put_int(&e->output, 1);
681 buffer_put_char(&e->output,
682 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
684 #endif /* SMARTCARD */
686 /* dispatch incoming messages */
689 process_message(SocketEntry *e)
697 if (buffer_len(&e->input) < 5)
698 return; /* Incomplete message. */
699 cp = buffer_ptr(&e->input);
700 msg_len = get_u32(cp);
701 if (msg_len > 256 * 1024) {
705 if (buffer_len(&e->input) < msg_len + 4)
708 /* move the current input to e->request */
709 buffer_consume(&e->input, 4);
710 buffer_clear(&e->request);
711 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
712 buffer_consume(&e->input, msg_len);
713 type = buffer_get_char(&e->request);
715 /* check wheter agent is locked */
716 if (locked && type != SSH_AGENTC_UNLOCK) {
717 buffer_clear(&e->request);
719 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
720 case SSH2_AGENTC_REQUEST_IDENTITIES:
721 /* send empty lists */
722 no_identities(e, type);
725 /* send a fail message for all other request types */
726 buffer_put_int(&e->output, 1);
727 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
732 debug("type %d", type);
734 case SSH_AGENTC_LOCK:
735 case SSH_AGENTC_UNLOCK:
736 process_lock_agent(e, type == SSH_AGENTC_LOCK);
739 case SSH_AGENTC_RSA_CHALLENGE:
740 process_authentication_challenge1(e);
742 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
743 process_request_identities(e, 1);
745 case SSH_AGENTC_ADD_RSA_IDENTITY:
746 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
747 process_add_identity(e, 1);
749 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
750 process_remove_identity(e, 1);
752 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
753 process_remove_all_identities(e, 1);
756 case SSH2_AGENTC_SIGN_REQUEST:
757 process_sign_request2(e);
759 case SSH2_AGENTC_REQUEST_IDENTITIES:
760 process_request_identities(e, 2);
762 case SSH2_AGENTC_ADD_IDENTITY:
763 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
764 process_add_identity(e, 2);
766 case SSH2_AGENTC_REMOVE_IDENTITY:
767 process_remove_identity(e, 2);
769 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
770 process_remove_all_identities(e, 2);
773 case SSH_AGENTC_ADD_SMARTCARD_KEY:
774 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
775 process_add_smartcard_key(e);
777 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
778 process_remove_smartcard_key(e);
780 #endif /* SMARTCARD */
782 /* Unknown message. Respond with failure. */
783 error("Unknown message %d", type);
784 buffer_clear(&e->request);
785 buffer_put_int(&e->output, 1);
786 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
792 new_socket(sock_type type, int fd)
794 u_int i, old_alloc, new_alloc;
801 for (i = 0; i < sockets_alloc; i++)
802 if (sockets[i].type == AUTH_UNUSED) {
804 buffer_init(&sockets[i].input);
805 buffer_init(&sockets[i].output);
806 buffer_init(&sockets[i].request);
807 sockets[i].type = type;
810 old_alloc = sockets_alloc;
811 new_alloc = sockets_alloc + 10;
812 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
813 for (i = old_alloc; i < new_alloc; i++)
814 sockets[i].type = AUTH_UNUSED;
815 sockets_alloc = new_alloc;
816 sockets[old_alloc].fd = fd;
817 buffer_init(&sockets[old_alloc].input);
818 buffer_init(&sockets[old_alloc].output);
819 buffer_init(&sockets[old_alloc].request);
820 sockets[old_alloc].type = type;
824 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp)
829 for (i = 0; i < sockets_alloc; i++) {
830 switch (sockets[i].type) {
832 case AUTH_CONNECTION:
833 n = MAX(n, sockets[i].fd);
838 fatal("Unknown socket type %d", sockets[i].type);
843 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
844 if (*fdrp == NULL || sz > *nallocp) {
854 debug("XXX shrink: %d < %d", n, *fdl);
856 memset(*fdrp, 0, sz);
857 memset(*fdwp, 0, sz);
859 for (i = 0; i < sockets_alloc; i++) {
860 switch (sockets[i].type) {
862 case AUTH_CONNECTION:
863 FD_SET(sockets[i].fd, *fdrp);
864 if (buffer_len(&sockets[i].output) > 0)
865 FD_SET(sockets[i].fd, *fdwp);
875 after_select(fd_set *readset, fd_set *writeset)
877 struct sockaddr_un sunaddr;
885 for (i = 0; i < sockets_alloc; i++)
886 switch (sockets[i].type) {
890 if (FD_ISSET(sockets[i].fd, readset)) {
891 slen = sizeof(sunaddr);
892 sock = accept(sockets[i].fd,
893 (struct sockaddr *)&sunaddr, &slen);
895 error("accept from AUTH_SOCKET: %s",
899 if (getpeereid(sock, &euid, &egid) < 0) {
900 error("getpeereid %d failed: %s",
901 sock, strerror(errno));
905 if ((euid != 0) && (getuid() != euid)) {
906 error("uid mismatch: "
907 "peer euid %u != uid %u",
908 (u_int) euid, (u_int) getuid());
912 new_socket(AUTH_CONNECTION, sock);
915 case AUTH_CONNECTION:
916 if (buffer_len(&sockets[i].output) > 0 &&
917 FD_ISSET(sockets[i].fd, writeset)) {
919 len = write(sockets[i].fd,
920 buffer_ptr(&sockets[i].output),
921 buffer_len(&sockets[i].output));
922 if (len == -1 && (errno == EAGAIN ||
928 close_socket(&sockets[i]);
931 buffer_consume(&sockets[i].output, len);
933 if (FD_ISSET(sockets[i].fd, readset)) {
935 len = read(sockets[i].fd, buf, sizeof(buf));
936 if (len == -1 && (errno == EAGAIN ||
942 close_socket(&sockets[i]);
945 buffer_append(&sockets[i].input, buf, len);
946 process_message(&sockets[i]);
950 fatal("Unknown type %d", sockets[i].type);
972 cleanup_handler(int sig)
980 check_parent_exists(int sig)
982 int save_errno = errno;
984 if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
985 /* printf("Parent has died - Authentication agent exiting.\n"); */
986 cleanup_handler(sig); /* safe */
988 mysignal(SIGALRM, check_parent_exists);
996 fprintf(stderr, "Usage: %s [options] [command [args ...]]\n",
998 fprintf(stderr, "Options:\n");
999 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1000 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1001 fprintf(stderr, " -k Kill the current agent.\n");
1002 fprintf(stderr, " -d Debug mode.\n");
1003 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1004 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1009 main(int ac, char **av)
1011 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1014 char *shell, *format, *pidstr, *agentsocket = NULL;
1015 fd_set *readsetp = NULL, *writesetp = NULL;
1016 struct sockaddr_un sunaddr;
1017 #ifdef HAVE_SETRLIMIT
1022 extern char *optarg;
1024 char pidstrbuf[1 + 3 * sizeof pid];
1026 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1033 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1034 /* Disable ptrace on Linux without sgid bit */
1035 prctl(PR_SET_DUMPABLE, 0);
1038 SSLeay_add_all_algorithms();
1040 __progname = ssh_get_progname(av[0]);
1044 while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1065 agentsocket = optarg;
1068 if ((lifetime = convtime(optarg)) == -1) {
1069 fprintf(stderr, "Invalid lifetime\n");
1080 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1083 if (ac == 0 && !c_flag && !s_flag) {
1084 shell = getenv("SHELL");
1085 if (shell != NULL &&
1086 strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
1090 const char *errstr = NULL;
1092 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1093 if (pidstr == NULL) {
1094 fprintf(stderr, "%s not set, cannot kill agent\n",
1095 SSH_AGENTPID_ENV_NAME);
1098 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1101 "%s=\"%s\", which is not a good PID: %s\n",
1102 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1105 if (kill(pid, SIGTERM) == -1) {
1109 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1110 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1111 printf(format, SSH_AGENTPID_ENV_NAME);
1112 printf("echo Agent pid %ld killed;\n", (long)pid);
1115 parent_pid = getpid();
1117 if (agentsocket == NULL) {
1118 /* Create private directory for agent socket */
1119 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXXXX", sizeof socket_dir);
1120 if (mkdtemp(socket_dir) == NULL) {
1121 perror("mkdtemp: private socket dir");
1124 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1127 /* Try to use specified agent socket */
1128 socket_dir[0] = '\0';
1129 strlcpy(socket_name, agentsocket, sizeof socket_name);
1133 * Create socket early so it will exist before command gets run from
1136 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1139 *socket_name = '\0'; /* Don't unlink any existing file */
1142 memset(&sunaddr, 0, sizeof(sunaddr));
1143 sunaddr.sun_family = AF_UNIX;
1144 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1145 prev_mask = umask(0177);
1146 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1148 *socket_name = '\0'; /* Don't unlink any existing file */
1153 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1159 * Fork, and have the parent execute the command, if any, or present
1160 * the socket data. The child continues as the authentication agent.
1163 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1164 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1165 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1166 SSH_AUTHSOCKET_ENV_NAME);
1167 printf("echo Agent pid %ld;\n", (long)parent_pid);
1175 if (pid != 0) { /* Parent - execute the given command. */
1177 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1179 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1180 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1181 SSH_AUTHSOCKET_ENV_NAME);
1182 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1183 SSH_AGENTPID_ENV_NAME);
1184 printf("echo Agent pid %ld;\n", (long)pid);
1187 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1188 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1197 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1199 if (setsid() == -1) {
1200 error("setsid: %s", strerror(errno));
1205 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1206 /* XXX might close listen socket */
1207 (void)dup2(fd, STDIN_FILENO);
1208 (void)dup2(fd, STDOUT_FILENO);
1209 (void)dup2(fd, STDERR_FILENO);
1214 #ifdef HAVE_SETRLIMIT
1215 /* deny core dumps, since memory contains unencrypted private keys */
1216 rlim.rlim_cur = rlim.rlim_max = 0;
1217 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1218 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1224 new_socket(AUTH_SOCKET, sock);
1226 mysignal(SIGALRM, check_parent_exists);
1231 signal(SIGINT, SIG_IGN);
1232 signal(SIGPIPE, SIG_IGN);
1233 signal(SIGHUP, cleanup_handler);
1234 signal(SIGTERM, cleanup_handler);
1238 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc);
1239 if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
1242 fatal("select: %s", strerror(errno));
1244 after_select(readsetp, writesetp);