1 /* $OpenBSD: ssh-agent.c,v 1.148 2006/07/26 02:35:17 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>
40 #include <sys/param.h>
41 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #ifdef HAVE_SYS_TIME_H
45 # include <sys/time.h>
50 #include "openbsd-compat/sys-queue.h"
52 #include <openssl/evp.h>
53 #include <openssl/md5.h>
80 #if defined(HAVE_SYS_PRCTL_H)
81 #include <sys/prctl.h> /* For prctl() and PR_SET_DUMPABLE */
98 u_int sockets_alloc = 0;
99 SocketEntry *sockets = NULL;
101 typedef struct identity {
102 TAILQ_ENTRY(identity) next;
111 TAILQ_HEAD(idqueue, identity) idlist;
114 /* private key table, one per protocol version */
119 /* pid of shell == parent of agent */
120 pid_t parent_pid = -1;
122 /* pathname and directory for AUTH_SOCKET */
123 char socket_name[MAXPATHLEN];
124 char socket_dir[MAXPATHLEN];
128 char *lock_passwd = NULL;
130 extern char *__progname;
132 /* Default lifetime (0 == forever) */
133 static int lifetime = 0;
136 close_socket(SocketEntry *e)
140 e->type = AUTH_UNUSED;
141 buffer_free(&e->input);
142 buffer_free(&e->output);
143 buffer_free(&e->request);
151 for (i = 0; i <=2; i++) {
152 TAILQ_INIT(&idtable[i].idlist);
153 idtable[i].nentries = 0;
157 /* return private key table for requested protocol version */
159 idtab_lookup(int version)
161 if (version < 1 || version > 2)
162 fatal("internal error, bad protocol version %d", version);
163 return &idtable[version];
167 free_identity(Identity *id)
174 /* return matching private key for given public key */
176 lookup_identity(Key *key, int version)
180 Idtab *tab = idtab_lookup(version);
181 TAILQ_FOREACH(id, &tab->idlist, next) {
182 if (key_equal(key, id->key))
188 /* Check confirmation of keysign request */
190 confirm_key(Identity *id)
195 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
196 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
204 /* send list of supported public keys to 'client' */
206 process_request_identities(SocketEntry *e, int version)
208 Idtab *tab = idtab_lookup(version);
213 buffer_put_char(&msg, (version == 1) ?
214 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
215 buffer_put_int(&msg, tab->nentries);
216 TAILQ_FOREACH(id, &tab->idlist, next) {
217 if (id->key->type == KEY_RSA1) {
218 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
219 buffer_put_bignum(&msg, id->key->rsa->e);
220 buffer_put_bignum(&msg, id->key->rsa->n);
224 key_to_blob(id->key, &blob, &blen);
225 buffer_put_string(&msg, blob, blen);
228 buffer_put_cstring(&msg, id->comment);
230 buffer_put_int(&e->output, buffer_len(&msg));
231 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
237 process_authentication_challenge1(SocketEntry *e)
239 u_char buf[32], mdbuf[16], session_id[16];
249 key = key_new(KEY_RSA1);
250 if ((challenge = BN_new()) == NULL)
251 fatal("process_authentication_challenge1: BN_new failed");
253 (void) buffer_get_int(&e->request); /* ignored */
254 buffer_get_bignum(&e->request, key->rsa->e);
255 buffer_get_bignum(&e->request, key->rsa->n);
256 buffer_get_bignum(&e->request, challenge);
258 /* Only protocol 1.1 is supported */
259 if (buffer_len(&e->request) == 0)
261 buffer_get(&e->request, session_id, 16);
262 response_type = buffer_get_int(&e->request);
263 if (response_type != 1)
266 id = lookup_identity(key, 1);
267 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
268 Key *private = id->key;
269 /* Decrypt the challenge using the private key. */
270 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
273 /* The response is MD5 of decrypted challenge plus session id. */
274 len = BN_num_bytes(challenge);
275 if (len <= 0 || len > 32) {
276 logit("process_authentication_challenge: bad challenge length %d", len);
280 BN_bn2bin(challenge, buf + 32 - len);
282 MD5_Update(&md, buf, 32);
283 MD5_Update(&md, session_id, 16);
284 MD5_Final(mdbuf, &md);
286 /* Send the response. */
287 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
288 for (i = 0; i < 16; i++)
289 buffer_put_char(&msg, mdbuf[i]);
294 /* Unknown identity or protocol error. Send failure. */
295 buffer_put_char(&msg, SSH_AGENT_FAILURE);
297 buffer_put_int(&e->output, buffer_len(&msg));
298 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
300 BN_clear_free(challenge);
306 process_sign_request2(SocketEntry *e)
308 u_char *blob, *data, *signature = NULL;
309 u_int blen, dlen, slen = 0;
310 extern int datafellows;
317 blob = buffer_get_string(&e->request, &blen);
318 data = buffer_get_string(&e->request, &dlen);
320 flags = buffer_get_int(&e->request);
321 if (flags & SSH_AGENT_OLD_SIGNATURE)
322 datafellows = SSH_BUG_SIGBLOB;
324 key = key_from_blob(blob, blen);
326 Identity *id = lookup_identity(key, 2);
327 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
328 ok = key_sign(id->key, &signature, &slen, data, dlen);
333 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
334 buffer_put_string(&msg, signature, slen);
336 buffer_put_char(&msg, SSH_AGENT_FAILURE);
338 buffer_put_int(&e->output, buffer_len(&msg));
339 buffer_append(&e->output, buffer_ptr(&msg),
344 if (signature != NULL)
350 process_remove_identity(SocketEntry *e, int version)
359 key = key_new(KEY_RSA1);
360 bits = buffer_get_int(&e->request);
361 buffer_get_bignum(&e->request, key->rsa->e);
362 buffer_get_bignum(&e->request, key->rsa->n);
364 if (bits != key_size(key))
365 logit("Warning: identity keysize mismatch: actual %u, announced %u",
366 key_size(key), bits);
369 blob = buffer_get_string(&e->request, &blen);
370 key = key_from_blob(blob, blen);
375 Identity *id = lookup_identity(key, version);
378 * We have this key. Free the old key. Since we
379 * don't want to leave empty slots in the middle of
380 * the array, we actually free the key there and move
381 * all the entries between the empty slot and the end
384 Idtab *tab = idtab_lookup(version);
385 if (tab->nentries < 1)
386 fatal("process_remove_identity: "
387 "internal error: tab->nentries %d",
389 TAILQ_REMOVE(&tab->idlist, id, next);
396 buffer_put_int(&e->output, 1);
397 buffer_put_char(&e->output,
398 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
402 process_remove_all_identities(SocketEntry *e, int version)
404 Idtab *tab = idtab_lookup(version);
407 /* Loop over all identities and clear the keys. */
408 for (id = TAILQ_FIRST(&tab->idlist); id;
409 id = TAILQ_FIRST(&tab->idlist)) {
410 TAILQ_REMOVE(&tab->idlist, id, next);
414 /* Mark that there are no identities. */
418 buffer_put_int(&e->output, 1);
419 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
425 u_int now = time(NULL);
430 for (version = 1; version < 3; version++) {
431 tab = idtab_lookup(version);
432 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
433 nxt = TAILQ_NEXT(id, next);
434 if (id->death != 0 && now >= id->death) {
435 TAILQ_REMOVE(&tab->idlist, id, next);
444 process_add_identity(SocketEntry *e, int version)
446 Idtab *tab = idtab_lookup(version);
447 int type, success = 0, death = 0, confirm = 0;
448 char *type_name, *comment;
453 k = key_new_private(KEY_RSA1);
454 (void) buffer_get_int(&e->request); /* ignored */
455 buffer_get_bignum(&e->request, k->rsa->n);
456 buffer_get_bignum(&e->request, k->rsa->e);
457 buffer_get_bignum(&e->request, k->rsa->d);
458 buffer_get_bignum(&e->request, k->rsa->iqmp);
460 /* SSH and SSL have p and q swapped */
461 buffer_get_bignum(&e->request, k->rsa->q); /* p */
462 buffer_get_bignum(&e->request, k->rsa->p); /* q */
464 /* Generate additional parameters */
465 rsa_generate_additional_parameters(k->rsa);
468 type_name = buffer_get_string(&e->request, NULL);
469 type = key_type_from_name(type_name);
473 k = key_new_private(type);
474 buffer_get_bignum2(&e->request, k->dsa->p);
475 buffer_get_bignum2(&e->request, k->dsa->q);
476 buffer_get_bignum2(&e->request, k->dsa->g);
477 buffer_get_bignum2(&e->request, k->dsa->pub_key);
478 buffer_get_bignum2(&e->request, k->dsa->priv_key);
481 k = key_new_private(type);
482 buffer_get_bignum2(&e->request, k->rsa->n);
483 buffer_get_bignum2(&e->request, k->rsa->e);
484 buffer_get_bignum2(&e->request, k->rsa->d);
485 buffer_get_bignum2(&e->request, k->rsa->iqmp);
486 buffer_get_bignum2(&e->request, k->rsa->p);
487 buffer_get_bignum2(&e->request, k->rsa->q);
489 /* Generate additional parameters */
490 rsa_generate_additional_parameters(k->rsa);
493 buffer_clear(&e->request);
498 /* enable blinding */
502 if (RSA_blinding_on(k->rsa, NULL) != 1) {
503 error("process_add_identity: RSA_blinding_on failed");
509 comment = buffer_get_string(&e->request, NULL);
515 while (buffer_len(&e->request)) {
516 switch (buffer_get_char(&e->request)) {
517 case SSH_AGENT_CONSTRAIN_LIFETIME:
518 death = time(NULL) + buffer_get_int(&e->request);
520 case SSH_AGENT_CONSTRAIN_CONFIRM:
527 if (lifetime && !death)
528 death = time(NULL) + lifetime;
529 if (lookup_identity(k, version) == NULL) {
530 Identity *id = xmalloc(sizeof(Identity));
532 id->comment = comment;
534 id->confirm = confirm;
535 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
536 /* Increment the number of identities. */
543 buffer_put_int(&e->output, 1);
544 buffer_put_char(&e->output,
545 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
548 /* XXX todo: encrypt sensitive data with passphrase */
550 process_lock_agent(SocketEntry *e, int lock)
555 passwd = buffer_get_string(&e->request, NULL);
556 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
558 memset(lock_passwd, 0, strlen(lock_passwd));
562 } else if (!locked && lock) {
564 lock_passwd = xstrdup(passwd);
567 memset(passwd, 0, strlen(passwd));
570 buffer_put_int(&e->output, 1);
571 buffer_put_char(&e->output,
572 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
576 no_identities(SocketEntry *e, u_int type)
581 buffer_put_char(&msg,
582 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
583 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
584 buffer_put_int(&msg, 0);
585 buffer_put_int(&e->output, buffer_len(&msg));
586 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
592 process_add_smartcard_key (SocketEntry *e)
594 char *sc_reader_id = NULL, *pin;
595 int i, version, success = 0, death = 0, confirm = 0;
600 sc_reader_id = buffer_get_string(&e->request, NULL);
601 pin = buffer_get_string(&e->request, NULL);
603 while (buffer_len(&e->request)) {
604 switch (buffer_get_char(&e->request)) {
605 case SSH_AGENT_CONSTRAIN_LIFETIME:
606 death = time(NULL) + buffer_get_int(&e->request);
608 case SSH_AGENT_CONSTRAIN_CONFIRM:
615 if (lifetime && !death)
616 death = time(NULL) + lifetime;
618 keys = sc_get_keys(sc_reader_id, pin);
622 if (keys == NULL || keys[0] == NULL) {
623 error("sc_get_keys failed");
626 for (i = 0; keys[i] != NULL; i++) {
628 version = k->type == KEY_RSA1 ? 1 : 2;
629 tab = idtab_lookup(version);
630 if (lookup_identity(k, version) == NULL) {
631 id = xmalloc(sizeof(Identity));
633 id->comment = sc_get_key_label(k);
635 id->confirm = confirm;
636 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
646 buffer_put_int(&e->output, 1);
647 buffer_put_char(&e->output,
648 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
652 process_remove_smartcard_key(SocketEntry *e)
654 char *sc_reader_id = NULL, *pin;
655 int i, version, success = 0;
656 Key **keys, *k = NULL;
660 sc_reader_id = buffer_get_string(&e->request, NULL);
661 pin = buffer_get_string(&e->request, NULL);
662 keys = sc_get_keys(sc_reader_id, pin);
666 if (keys == NULL || keys[0] == NULL) {
667 error("sc_get_keys failed");
670 for (i = 0; keys[i] != NULL; i++) {
672 version = k->type == KEY_RSA1 ? 1 : 2;
673 if ((id = lookup_identity(k, version)) != NULL) {
674 tab = idtab_lookup(version);
675 TAILQ_REMOVE(&tab->idlist, id, next);
685 buffer_put_int(&e->output, 1);
686 buffer_put_char(&e->output,
687 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
689 #endif /* SMARTCARD */
691 /* dispatch incoming messages */
694 process_message(SocketEntry *e)
702 if (buffer_len(&e->input) < 5)
703 return; /* Incomplete message. */
704 cp = buffer_ptr(&e->input);
705 msg_len = get_u32(cp);
706 if (msg_len > 256 * 1024) {
710 if (buffer_len(&e->input) < msg_len + 4)
713 /* move the current input to e->request */
714 buffer_consume(&e->input, 4);
715 buffer_clear(&e->request);
716 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
717 buffer_consume(&e->input, msg_len);
718 type = buffer_get_char(&e->request);
720 /* check wheter agent is locked */
721 if (locked && type != SSH_AGENTC_UNLOCK) {
722 buffer_clear(&e->request);
724 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
725 case SSH2_AGENTC_REQUEST_IDENTITIES:
726 /* send empty lists */
727 no_identities(e, type);
730 /* send a fail message for all other request types */
731 buffer_put_int(&e->output, 1);
732 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
737 debug("type %d", type);
739 case SSH_AGENTC_LOCK:
740 case SSH_AGENTC_UNLOCK:
741 process_lock_agent(e, type == SSH_AGENTC_LOCK);
744 case SSH_AGENTC_RSA_CHALLENGE:
745 process_authentication_challenge1(e);
747 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
748 process_request_identities(e, 1);
750 case SSH_AGENTC_ADD_RSA_IDENTITY:
751 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
752 process_add_identity(e, 1);
754 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
755 process_remove_identity(e, 1);
757 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
758 process_remove_all_identities(e, 1);
761 case SSH2_AGENTC_SIGN_REQUEST:
762 process_sign_request2(e);
764 case SSH2_AGENTC_REQUEST_IDENTITIES:
765 process_request_identities(e, 2);
767 case SSH2_AGENTC_ADD_IDENTITY:
768 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
769 process_add_identity(e, 2);
771 case SSH2_AGENTC_REMOVE_IDENTITY:
772 process_remove_identity(e, 2);
774 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
775 process_remove_all_identities(e, 2);
778 case SSH_AGENTC_ADD_SMARTCARD_KEY:
779 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
780 process_add_smartcard_key(e);
782 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
783 process_remove_smartcard_key(e);
785 #endif /* SMARTCARD */
787 /* Unknown message. Respond with failure. */
788 error("Unknown message %d", type);
789 buffer_clear(&e->request);
790 buffer_put_int(&e->output, 1);
791 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
797 new_socket(sock_type type, int fd)
799 u_int i, old_alloc, new_alloc;
806 for (i = 0; i < sockets_alloc; i++)
807 if (sockets[i].type == AUTH_UNUSED) {
809 buffer_init(&sockets[i].input);
810 buffer_init(&sockets[i].output);
811 buffer_init(&sockets[i].request);
812 sockets[i].type = type;
815 old_alloc = sockets_alloc;
816 new_alloc = sockets_alloc + 10;
817 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
818 for (i = old_alloc; i < new_alloc; i++)
819 sockets[i].type = AUTH_UNUSED;
820 sockets_alloc = new_alloc;
821 sockets[old_alloc].fd = fd;
822 buffer_init(&sockets[old_alloc].input);
823 buffer_init(&sockets[old_alloc].output);
824 buffer_init(&sockets[old_alloc].request);
825 sockets[old_alloc].type = type;
829 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp)
834 for (i = 0; i < sockets_alloc; i++) {
835 switch (sockets[i].type) {
837 case AUTH_CONNECTION:
838 n = MAX(n, sockets[i].fd);
843 fatal("Unknown socket type %d", sockets[i].type);
848 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
849 if (*fdrp == NULL || sz > *nallocp) {
859 debug("XXX shrink: %d < %d", n, *fdl);
861 memset(*fdrp, 0, sz);
862 memset(*fdwp, 0, sz);
864 for (i = 0; i < sockets_alloc; i++) {
865 switch (sockets[i].type) {
867 case AUTH_CONNECTION:
868 FD_SET(sockets[i].fd, *fdrp);
869 if (buffer_len(&sockets[i].output) > 0)
870 FD_SET(sockets[i].fd, *fdwp);
880 after_select(fd_set *readset, fd_set *writeset)
882 struct sockaddr_un sunaddr;
890 for (i = 0; i < sockets_alloc; i++)
891 switch (sockets[i].type) {
895 if (FD_ISSET(sockets[i].fd, readset)) {
896 slen = sizeof(sunaddr);
897 sock = accept(sockets[i].fd,
898 (struct sockaddr *)&sunaddr, &slen);
900 error("accept from AUTH_SOCKET: %s",
904 if (getpeereid(sock, &euid, &egid) < 0) {
905 error("getpeereid %d failed: %s",
906 sock, strerror(errno));
910 if ((euid != 0) && (getuid() != euid)) {
911 error("uid mismatch: "
912 "peer euid %u != uid %u",
913 (u_int) euid, (u_int) getuid());
917 new_socket(AUTH_CONNECTION, sock);
920 case AUTH_CONNECTION:
921 if (buffer_len(&sockets[i].output) > 0 &&
922 FD_ISSET(sockets[i].fd, writeset)) {
924 len = write(sockets[i].fd,
925 buffer_ptr(&sockets[i].output),
926 buffer_len(&sockets[i].output));
927 if (len == -1 && (errno == EAGAIN ||
933 close_socket(&sockets[i]);
936 buffer_consume(&sockets[i].output, len);
938 if (FD_ISSET(sockets[i].fd, readset)) {
940 len = read(sockets[i].fd, buf, sizeof(buf));
941 if (len == -1 && (errno == EAGAIN ||
947 close_socket(&sockets[i]);
950 buffer_append(&sockets[i].input, buf, len);
951 process_message(&sockets[i]);
955 fatal("Unknown type %d", sockets[i].type);
977 cleanup_handler(int sig)
985 check_parent_exists(int sig)
987 int save_errno = errno;
989 if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
990 /* printf("Parent has died - Authentication agent exiting.\n"); */
991 cleanup_handler(sig); /* safe */
993 mysignal(SIGALRM, check_parent_exists);
1001 fprintf(stderr, "Usage: %s [options] [command [args ...]]\n",
1003 fprintf(stderr, "Options:\n");
1004 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1005 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1006 fprintf(stderr, " -k Kill the current agent.\n");
1007 fprintf(stderr, " -d Debug mode.\n");
1008 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1009 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1014 main(int ac, char **av)
1016 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1019 char *shell, *format, *pidstr, *agentsocket = NULL;
1020 fd_set *readsetp = NULL, *writesetp = NULL;
1021 struct sockaddr_un sunaddr;
1022 #ifdef HAVE_SETRLIMIT
1027 extern char *optarg;
1029 char pidstrbuf[1 + 3 * sizeof pid];
1031 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1038 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1039 /* Disable ptrace on Linux without sgid bit */
1040 prctl(PR_SET_DUMPABLE, 0);
1043 SSLeay_add_all_algorithms();
1045 __progname = ssh_get_progname(av[0]);
1049 while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1070 agentsocket = optarg;
1073 if ((lifetime = convtime(optarg)) == -1) {
1074 fprintf(stderr, "Invalid lifetime\n");
1085 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1088 if (ac == 0 && !c_flag && !s_flag) {
1089 shell = getenv("SHELL");
1090 if (shell != NULL &&
1091 strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
1095 const char *errstr = NULL;
1097 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1098 if (pidstr == NULL) {
1099 fprintf(stderr, "%s not set, cannot kill agent\n",
1100 SSH_AGENTPID_ENV_NAME);
1103 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1106 "%s=\"%s\", which is not a good PID: %s\n",
1107 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1110 if (kill(pid, SIGTERM) == -1) {
1114 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1115 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1116 printf(format, SSH_AGENTPID_ENV_NAME);
1117 printf("echo Agent pid %ld killed;\n", (long)pid);
1120 parent_pid = getpid();
1122 if (agentsocket == NULL) {
1123 /* Create private directory for agent socket */
1124 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXXXX", sizeof socket_dir);
1125 if (mkdtemp(socket_dir) == NULL) {
1126 perror("mkdtemp: private socket dir");
1129 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1132 /* Try to use specified agent socket */
1133 socket_dir[0] = '\0';
1134 strlcpy(socket_name, agentsocket, sizeof socket_name);
1138 * Create socket early so it will exist before command gets run from
1141 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1144 *socket_name = '\0'; /* Don't unlink any existing file */
1147 memset(&sunaddr, 0, sizeof(sunaddr));
1148 sunaddr.sun_family = AF_UNIX;
1149 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1150 prev_mask = umask(0177);
1151 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1153 *socket_name = '\0'; /* Don't unlink any existing file */
1158 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1164 * Fork, and have the parent execute the command, if any, or present
1165 * the socket data. The child continues as the authentication agent.
1168 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1169 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1170 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1171 SSH_AUTHSOCKET_ENV_NAME);
1172 printf("echo Agent pid %ld;\n", (long)parent_pid);
1180 if (pid != 0) { /* Parent - execute the given command. */
1182 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1184 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1185 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1186 SSH_AUTHSOCKET_ENV_NAME);
1187 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1188 SSH_AGENTPID_ENV_NAME);
1189 printf("echo Agent pid %ld;\n", (long)pid);
1192 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1193 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1202 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1204 if (setsid() == -1) {
1205 error("setsid: %s", strerror(errno));
1210 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1211 /* XXX might close listen socket */
1212 (void)dup2(fd, STDIN_FILENO);
1213 (void)dup2(fd, STDOUT_FILENO);
1214 (void)dup2(fd, STDERR_FILENO);
1219 #ifdef HAVE_SETRLIMIT
1220 /* deny core dumps, since memory contains unencrypted private keys */
1221 rlim.rlim_cur = rlim.rlim_max = 0;
1222 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1223 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1229 new_socket(AUTH_SOCKET, sock);
1231 mysignal(SIGALRM, check_parent_exists);
1236 signal(SIGINT, SIG_IGN);
1237 signal(SIGPIPE, SIG_IGN);
1238 signal(SIGHUP, cleanup_handler);
1239 signal(SIGTERM, cleanup_handler);
1243 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc);
1244 if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
1247 fatal("select: %s", strerror(errno));
1249 after_select(readsetp, writesetp);